From 43b5ee5918473ef6c131912f78135cf823e88738 Mon Sep 17 00:00:00 2001 From: Uli Heilmeier Date: Wed, 8 Apr 2020 22:47:13 +0200 Subject: [PATCH 01/66] legic.lua: updated to work again Fixed/changed things: * added info that virtual tag is always MIM1024 * changed reading files to read binary files (as written by 'hf legic dump') * changed extension for writing files (*.bin and *.eml) to be on par with 'hf legic dump' * CRC was calculated wrong when data was not padded with 0 for one char hex strings * readTag (rt) can now be called multiple times without using the wrong filename * tag length was calculated wrong as segment header length field includes the header itself * bytes are XORed before writing them to a tag * default name for file contains now the tag id --- CHANGELOG.md | 1 + client/luascripts/legic.lua | 161 +++++++++++++++++++----------------- 2 files changed, 87 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eff29cc79..0f15617c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) - Fix Mifare Desfire select appid handling (@bkerler) diff --git a/client/luascripts/legic.lua b/client/luascripts/legic.lua index 7e0f8d3be..393cc9e52 100644 --- a/client/luascripts/legic.lua +++ b/client/luascripts/legic.lua @@ -91,14 +91,20 @@ CRC1 = crc8 over addr 0x00..0x03+0x07..0x0E (special 'gantner crc8') CRC2 = MCD + MSB0..2+ addr 0x06 + addr 0x05 + addr 0x07 + Stamp (regular Master-Token-CRC) --]] +--[[ +Known issues; needs to be fixed: +* last byte in last segment is handled incorrectly when it is the last bytes on the card itself (MIM256: => byte 256) +--]] + example = "script run legic" -author = "Mosci" -version = "1.0.3" +author = "Mosci, uhei" +version = "1.0.4" desc = [[ This script helps you to read, create and modify Legic Prime Tags (MIM22, MIM256, MIM1024) +The virtual tag (and therefore the file to be saved) is always a MIM1024 tag. it's kinda interactive with following commands in three categories: Data I/O Segment Manipulation Token-Data @@ -108,8 +114,8 @@ it's kinda interactive with following commands in three categories: ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -128,8 +134,8 @@ it's kinda interactive with following commands in three categories: without the need of changing anything - MCD,MSN,MCC will be read from the tag before and applied to the output. - lf: 'load file' - load a (xored) file from the local Filesystem into the 'virtual inTag' - sf: 'save file' - saves the 'virtual inTag' to the local Filesystem (xored with Tag-MCC) + lf: 'load file' - load a (xored) binary file (*.bin) from the local Filesystem into the 'virtual inTag' + sf: 'save file' - saves the 'virtual inTag' to the local Filesystem as eml and bin (xored with Tag-MCC) xf: 'xor file' - saves the 'virtual inTag' to the local Filesystem (xored with choosen MCC - use '00' for plain values) ct: 'copy tag' - copy the 'virtual Tag' to a second 'virtual TAG' - not usefull yet, but inernally needed @@ -242,6 +248,16 @@ function istable(t) return type(t) == 'table' end +--- +-- To have two char string for a byte +local function padString(str) + if (#str == 1) then + return '0'..str + end + + return str +end + --- -- creates a 'deep copy' of a table (a=b only references) function deepCopy(object) @@ -387,15 +403,15 @@ end function bytesToTag(bytes, tag) if istable(tag) == false then return oops("tag is no table in: bytesToTag ("..type(tag)..")") end - tag.MCD =bytes[1]; - tag.MSN0=bytes[2]; - tag.MSN1=bytes[3]; - tag.MSN2=bytes[4]; - tag.MCC =bytes[5]; - tag.DCFl=bytes[6]; - tag.DCFh=bytes[7]; - tag.raw =bytes[8]; - tag.SSC =bytes[9]; + tag.MCD =padString(bytes[1]); + tag.MSN0=padString(bytes[2]); + tag.MSN1=padString(bytes[3]); + tag.MSN2=padString(bytes[4]); + tag.MCC =padString(bytes[5]); + tag.DCFl=padString(bytes[6]); + tag.DCFh=padString(bytes[7]); + tag.raw =padString(bytes[8]); + tag.SSC =padString(bytes[9]); tag.Type=getTokenType(tag.DCFl); tag.OLE=bbit("0x"..tag.DCFl,7,1) tag.WRP=("%d"):format(bbit("0x"..bytes[8],0,4)) @@ -500,42 +516,26 @@ function tagToBytes(tag) return bytes end + +--- --- PM3 I/O --- ---- --- read from pm3 into virtual-tag -function readFromPM3() - local tag, bytes, infile - infile="legic.temp" - -- core.console("hf legic reader") - -- core.console("hf legic esave "..infile) - core.console("hf legic dump o "..infile) - tag=readFile(infile..".bin") - return tag -end - -local function padString(str) - if (#str == 1) then - return '0'..str - end - - return str -end - ---- -- write virtual Tag to real Tag function writeToTag(tag) local bytes - local filename = 'MylegicClone.hex' local taglen = 22 - if(utils.confirm(acred.."\nplace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then + local writeDCF = false + if(utils.confirm(acred.."\nPlace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then return end + if(utils.confirm(acred.."\nShould the decremental field (DCF) be written?: "..acoff) == true) then + writeDCF = true + end -- get used bytes / tag-len if (istable(tag.SEG)) then if (istable(tag.Bck)) then for i=0, #tag.SEG do - taglen = taglen + tag.SEG[i] . len + 5 + taglen = taglen + tag.SEG[i] . len end end local uid_old = tag.MCD..tag.MSN0..tag.MSN1..tag.MSN2 @@ -571,37 +571,32 @@ function writeToTag(tag) bytes[22] = calcMtCrc(bytes) end if (bytes) then - print("write temp-file '"..filename.."'") - print(accyan) - writeFile(bytes, filename..".bin") - print(acoff) + bytes = xorBytes(bytes,tag.MCC) end end + -- write data to file if (taglen > 0) then WriteBytes = input(acyellow.."enter number of bytes to write?"..acoff, taglen) - -- load file into pm3-buffer - if (type(filename) ~= "string") then - filename = input(acyellow.."filename to load to pm3-buffer?"..acoff, "legic.temp") - end - - cmd = 'hf legic eload 2 '..filename - core.console(cmd) -- write pm3-buffer to Tag - for i=0, WriteBytes do - if (i > 6) then - cmd = ("hf legic write o %x d %s "):format(i, padString(bytes[i])) + for i=1, WriteBytes do + if (i > 7) then + cmd = ("hf legic wrbl o %02x d %s "):format(i-1, padString(bytes[i])) print(acgreen..cmd..acoff) core.console(cmd) core.clearCommandBuffer() + elseif (i == 7) then + if (writeDCF) then + -- write DCF in reverse order (requires 'mosci-patch') + cmd = ('hf legic wrbl o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) + print(acgreen..cmd..acoff) + core.console(cmd) + core.clearCommandBuffer() + else + print(acgreen.."skip byte 0x05-0x06 - DCF"..acoff) + end elseif (i == 6) then - -- write DCF in reverse order (requires 'mosci-patch') - cmd = ('hf legic write o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) - print(acgreen..cmd..acoff) - core.console(cmd) - core.clearCommandBuffer() - elseif (i == 5) then print(acgreen.."skip byte 0x05 - will be written next step"..acoff) else print(acgreen.."skip byte 0x00-0x04 - unwritable area"..acoff) @@ -641,12 +636,12 @@ end local function save_BIN(data, filename) local outfile local counter = 1 - local ext = filename:match("^.+(%..+)$") or '' - local fn = filename + local ext = ".bin" + local fn = filename..ext -- Make sure we don't overwrite a file while file_check(fn) do - fn = filename:gsub(ext, tostring(counter)..ext) + fn = filename..ext:gsub(ext, "-"..tostring(counter)..ext) counter = counter + 1 end @@ -664,26 +659,27 @@ end --- -- write bytes to file function writeFile(bytes, filename) - if (filename ~= 'MylegicClone.hex') then - if (file_check(filename)) then - local answer = confirm("\nthe output-file "..filename.." already exists!\nthis will delete the previous content!\ncontinue?") + local emlext = ".eml" + if (filename ~= 'MyLegicClone') then + if (file_check(filename..emlext)) then + local answer = confirm("\nthe output-file "..filename..emlext.." already exists!\nthis will delete the previous content!\ncontinue?") if not answer then return print("user abort") end end end local line local bcnt = 0 - local fho, err = io.open(filename, "w") + local fho, err = io.open(filename..emlext, "w") if err then - return oops("OOps ... failed to open output-file ".. filename) + return oops("OOps ... failed to open output-file ".. filename..emlext) end bytes = xorBytes(bytes, bytes[5]) for i = 1, #bytes do if (bcnt == 0) then - line = bytes[i] + line = padString(bytes[i]) elseif (bcnt <= 7) then - line = line.." "..bytes[i] + line = line.." "..padString(bytes[i]) end if (bcnt == 7) then -- write line to new file @@ -699,7 +695,7 @@ function writeFile(bytes, filename) -- save binary local fn_bin, fn_bin_num = save_BIN(bytes, filename) - print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..acoff) + print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..emlext..acoff) if fn_bin and fn_bin_num then print("\nwrote "..acyellow..fn_bin_num..acoff.." bytes to BINARY file "..acyellow..fn_bin..acoff) @@ -708,6 +704,21 @@ function writeFile(bytes, filename) return true end +--- +-- read from pm3 into virtual-tag +function readFromPM3() + local tag, bytes, infile + --infile="legic.temp" + infile=os.tmpname() + core.console("hf legic dump f "..infile) + tag=readFile(infile..".bin") + os.remove(infile) + os.remove(infile..".bin") + os.remove(infile..".eml") + os.remove(infile..".json") + return tag +end + --- Map related --- --- -- make tagMap @@ -2265,8 +2276,8 @@ function modifyHelp() ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -2352,10 +2363,10 @@ function modifyMode() -- save values of mainTAG to a file (xored with MCC of mainTAG) ["sf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) bytes = tagToBytes(inTAG) --bytes=xorBytes(bytes, inTAG.MCC) - if bytes then + if (bytes) then writeFile(bytes, outfile) end end @@ -2364,7 +2375,7 @@ function modifyMode() -- save values of mainTAG to a file (xored with 'specific' MCC) ["xf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) crc = input("enter new crc: ('00' for a plain dump)", inTAG.MCC) print("obfuscate with: "..crc) bytes=tagToBytes(inTAG) From 0904cce336c8bb428613a0e63043a29aafdfd312 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 9 Apr 2020 13:23:36 +0200 Subject: [PATCH 02/66] fix: null --- client/cmdhfmfdes.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 22e401b07..3d805631d 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -62,6 +62,7 @@ static int CmdHelp(const char *Cmd); */ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { + *result_len = 0; if (sw) *sw = 0; @@ -180,7 +181,7 @@ static int test_desfire_authenticate() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // none @@ -189,7 +190,7 @@ static int test_desfire_authenticate_iso() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } //none @@ -198,7 +199,7 @@ static int test_desfire_authenticate_aes() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // --- FREE MEM @@ -405,7 +406,7 @@ static int get_desfire_select_application(uint8_t *aid) { int recv_len = 0; uint16_t sw = 0; if (aid == NULL) return PM3_ESOFT; - return send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t)); + return send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); } // none From dcede2f8e39a724879c5083f450b31722c91a8c7 Mon Sep 17 00:00:00 2001 From: Uli Heilmeier Date: Thu, 9 Apr 2020 13:24:27 +0200 Subject: [PATCH 03/66] cmdhfmfdes: fix clang warnings Make clang happy and fix several error: expression which evaluates to zero treated as a null pointer constant of type 'uint8_t *' (aka 'unsigned char *') [-Werror,-Wnon-literal-null-conversion] and cmdhfmfdes.c:732:31: error: suggest braces around initialization of subobject [-Werror,-Wmissing-braces] Fixes RfidResearchGroup/proxmark3#659 --- client/cmdhfmfdes.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 22e401b07..d52242823 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -180,7 +180,7 @@ static int test_desfire_authenticate() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // none @@ -189,7 +189,7 @@ static int test_desfire_authenticate_iso() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } //none @@ -198,7 +198,7 @@ static int test_desfire_authenticate_aes() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // --- FREE MEM @@ -209,7 +209,7 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { - sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NONE}; // 0x6E + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; @@ -334,7 +334,7 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NONE}; //0x45 + sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; @@ -405,7 +405,7 @@ static int get_desfire_select_application(uint8_t *aid) { int recv_len = 0; uint16_t sw = 0; if (aid == NULL) return PM3_ESOFT; - return send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t)); + return send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); } // none @@ -729,7 +729,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; - dfname_t dfnames[255] = {0}; + dfname_t dfnames[255]; uint8_t dfname_count = 0; if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { From 8f07ac80d11e9d9009511661154294bc528cb1f2 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 9 Apr 2020 13:28:43 +0200 Subject: [PATCH 04/66] fix: null --- client/cmdhfmfdes.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 3d805631d..add158e0e 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -177,8 +177,8 @@ static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { //none static int test_desfire_authenticate() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); @@ -186,8 +186,8 @@ static int test_desfire_authenticate() { // none static int test_desfire_authenticate_iso() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); @@ -195,8 +195,8 @@ static int test_desfire_authenticate_iso() { //none static int test_desfire_authenticate_aes() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); @@ -210,7 +210,7 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { - sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NONE}; // 0x6E + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; @@ -335,7 +335,7 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NONE}; //0x45 + sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; From 057e611b6d336496f4c552858fdb8627bc2bc5f0 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 17:15:45 +0200 Subject: [PATCH 05/66] Fix bugs, improve error reporting, add format picc and createapplication --- client/cmdhflist.c | 2 +- client/cmdhfmfdes.c | 427 +++++++++++++++++++++++++++++++++++++------- client/cmdhfmfdes.h | 53 +----- include/protocols.h | 43 +++-- 4 files changed, 396 insertions(+), 129 deletions(-) diff --git a/client/cmdhflist.c b/client/cmdhflist.c index 871cd68a3..b40b06d56 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -819,7 +819,7 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { case MFDES_GET_KEY_VERSION: snprintf(exp, size, "GET KEY VERSION"); break; - case MFDES_AUTHENTICATION_FRAME: + case MFDES_ADDITIONAL_FRAME: snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); break; default: diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 22e401b07..fcd2f227b 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -34,6 +34,8 @@ uint8_t key_ones_data[16] = { 0x01 }; uint8_t key_defa_data[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; +#define status(x) ( ((uint16_t)(0x91<<8)) + x ) + typedef enum { UNKNOWN = 0, MF3ICD40, @@ -104,7 +106,7 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t if (sw) *sw = isw; - if (isw != 0x9000 && isw != MFDES_SUCCESS_FRAME_RESP && isw != MFDES_ADDITIONAL_FRAME_RESP) { + if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { if (GetAPDULogging()) { if (isw >> 8 == 0x61) { PrintAndLogEx(ERR, "APDU chaining len:%02x -->", isw & 0xff); @@ -114,31 +116,163 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t } } } - return PM3_SUCCESS; } +static char* GetErrorString(int res) +{ + switch(res){ + case PM3_EUNDEF: + return "Undefined error"; + case PM3_EINVARG: + return "Invalid argument(s)"; + case PM3_EDEVNOTSUPP: + return "Operation not supported by device"; + case PM3_ETIMEOUT: + return "Operation timed out"; + case PM3_EOPABORTED: + return "Operation aborted (by user)"; + case PM3_ENOTIMPL: + return "Not (yet) implemented"; + case PM3_ERFTRANS: + return "Error while RF transmission"; + case PM3_EIO: + return "Input / output error"; + case PM3_EOVFLOW: + return "Buffer overflow"; + case PM3_ESOFT: + return "Software error"; + case PM3_EFLASH: + return "Flash error"; + case PM3_EMALLOC: + return "Memory allocation error"; + case PM3_EFILE: + return "File error"; + case PM3_ENOTTY: + return "Generic TTY error"; + case PM3_EINIT: + return "Initialization error"; + case PM3_EWRONGANSVER: + return "Expected a different answer error"; + case PM3_EOUTOFBOUND: + return "Memory out-of-bounds error"; + case PM3_ECARDEXCHANGE: + return "Exchange with card error"; + case PM3_EAPDU_ENCODEFAIL: + return "Failed to create APDU"; + case PM3_ENODATA: + return "No data"; + case PM3_EFATAL: + return "Fatal error"; + default: + break; + } + return ""; +} + +static int getstatus(int res, uint16_t * sw) +{ + if (sw==NULL) return PM3_ESOFT; + + if (res==PM3_EAPDU_FAIL) + { + if (((*sw>>8)&0xFF)==0x91){ + switch (*sw&0xFF){ + case MFDES_E_OUT_OF_EEPROM: + PrintAndLogEx(ERR, "APDU error: %02x --> Out of Eeprom, insufficient NV-Memory to complete command", *sw & 0xff); + break; + case MFDES_E_ILLEGAL_COMMAND_CODE: + PrintAndLogEx(ERR, "APDU error: %02x --> Command code not supported", *sw & 0xff); + break; + case MFDES_E_INTEGRITY_ERROR: + PrintAndLogEx(ERR, "APDU error: %02x --> CRC or MAC does not match data / Padding bytes invalid", *sw & 0xff); + break; + case MFDES_E_NO_SUCH_KEY: + PrintAndLogEx(ERR, "APDU error: %02x --> Invalid key number specified", *sw & 0xff); + break; + case MFDES_E_LENGTH: + PrintAndLogEx(ERR, "APDU error: %02x --> Length of command string invalid", *sw & 0xff); + break; + case MFDES_E_PERMISSION_DENIED: + PrintAndLogEx(ERR, "APDU error: %02x --> Current configuration/status does not allow the requested command", *sw & 0xff); + break; + case MFDES_E_PARAMETER_ERROR: + PrintAndLogEx(ERR, "APDU error: %02x --> Value of the parameter(s) invalid", *sw & 0xff); + break; + case MFDES_E_APPLICATION_NOT_FOUND: + PrintAndLogEx(ERR, "APDU error: %02x --> Requested AID not present on PICC", *sw & 0xff); + break; + case MFDES_E_APPL_INTEGRITY: + PrintAndLogEx(ERR, "APDU error: %02x --> Application integrity error, application will be disabled", *sw & 0xff); + break; + case MFDES_E_AUTHENTIFICATION_ERROR: + PrintAndLogEx(ERR, "APDU error: %02x --> Current authentication status does not allow the requested command", *sw & 0xff); + break; + case MFDES_E_BOUNDARY: + PrintAndLogEx(ERR, "APDU error: %02x --> Attempted to read/write data from/to beyong the file's/record's limit", *sw & 0xff); + break; + case MFDES_E_PICC_INTEGRITY: + PrintAndLogEx(ERR, "APDU error: %02x --> PICC integrity error, PICC will be disabled", *sw & 0xff); + break; + case MFDES_E_COMMAND_ABORTED: + PrintAndLogEx(ERR, "APDU error: %02x --> Previous command was not fully completed / Not all Frames were requested or provided by the PCD", *sw & 0xff); + break; + case MFDES_E_PICC_DISABLED: + PrintAndLogEx(ERR, "APDU error: %02x --> PICC was disabled by an unrecoverable error", *sw & 0xff); + break; + case MFDES_E_COUNT: + PrintAndLogEx(ERR, "APDU error: %02x --> Application count is limited to 28, not addition CreateApplication possible", *sw & 0xff); + break; + case MFDES_E_DUPLICATE: + PrintAndLogEx(ERR, "APDU error: %02x --> Duplicate entry: File/Application does already exist", *sw & 0xff); + break; + case MFDES_E_EEPROM: + PrintAndLogEx(ERR, "APDU error: %02x --> Eeprom error due to loss of power, internal backup/rollback mechanism activated", *sw & 0xff); + break; + case MFDES_E_FILE_NOT_FOUND: + PrintAndLogEx(ERR, "APDU error: %02x --> Specified file number does not exist", *sw & 0xff); + break; + case MFDES_E_FILE_INTEGRITY: + PrintAndLogEx(ERR, "APDU error: %02x --> File integrity error, file will be disabled", *sw & 0xff); + break; + default: + PrintAndLogEx(ERR, "APDU error: %02x --> Unknown error", *sw & 0xff); + break; + } + } + } else { + PrintAndLogEx(ERR, "%s",GetErrorString(res)); + } + return res; +} static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize) { - //SetAPDULogging(true); + if (g_debugMode) + { + if (apdu==NULL) PrintAndLogEx(ERR, "APDU=NULL"); + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (sw==NULL) PrintAndLogEx(ERR, "SW=NULL"); + if (recv_len==NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); + } + if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_ESOFT; + *sw = 0; uint8_t data[255 * 5] = {0x00}; int resplen = 0; int pos = 0; int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; - if (*sw != MFDES_ADDITIONAL_FRAME_RESP && *sw != MFDES_SUCCESS_FRAME_RESP) return PM3_ESOFT; + if (res != PM3_SUCCESS) return getstatus(res,sw); if (dest != NULL) { memcpy(dest, data, resplen); } pos += resplen; - if (*sw == MFDES_ADDITIONAL_FRAME_RESP) { + while (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; + if (res != PM3_SUCCESS) return getstatus(res,sw); if (dest != NULL) { if (splitbysize) { memcpy(&dest[i * splitbysize], data, resplen); @@ -148,12 +282,12 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } } pos += resplen; + if (*sw!=status(MFDES_ADDITIONAL_FRAME)) break; } if (splitbysize) *recv_len = i; else { *recv_len = pos; } - //SetAPDULogging(false); return PM3_SUCCESS; } @@ -180,7 +314,7 @@ static int test_desfire_authenticate() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // none @@ -189,7 +323,7 @@ static int test_desfire_authenticate_iso() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } //none @@ -198,7 +332,7 @@ static int test_desfire_authenticate_aes() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NONE, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // --- FREE MEM @@ -209,7 +343,8 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { - sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NONE}; // 0x6E + if (free_mem==NULL) return PM3_ESOFT; + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; @@ -226,7 +361,7 @@ static int get_desfire_freemem(uint32_t *free_mem) { // --- GET SIGNATURE static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { - + if (uid==NULL || signature==NULL) return PM3_ESOFT; // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -278,6 +413,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign // init / disconnect static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { + if (signature==NULL || signature_len==NULL) return PM3_ESOFT; uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C int recv_len = 0; @@ -334,17 +470,14 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NONE}; //0x45 + if (key_settings==NULL || num_keys==NULL) return PM3_ESOFT; + sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; if (num_keys == NULL) return PM3_ESOFT; if (key_settings == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); - if (sw == MFDES_EAUTH_RESP) { - PrintAndLogEx(WARNING, _RED_("[get_desfire_keysettings] Authentication error")); - return PM3_ESOFT; - } if (res != PM3_SUCCESS) return res; *key_settings = data[0]; @@ -360,21 +493,19 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { // none static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { + if (num_versions==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; if (num_versions == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); - if (sw == MFDES_ENO_SUCH_KEY_RESP) { - PrintAndLogEx(WARNING, _RED_("[get_desfire_keyversion] Key %d doesn't exist"), curr_key); - return PM3_ESOFT; - } return res; } // init / disconnect static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + if (dest==NULL || app_ids_len==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; @@ -387,6 +518,7 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { } static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + if (dest==NULL || dfname_count==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; uint16_t sw = 0; @@ -401,15 +533,22 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { // init static int get_desfire_select_application(uint8_t *aid) { + if (aid==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; - if (aid == NULL) return PM3_ESOFT; - return send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t)); + int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't select AID %X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res)); + DropField(); + return res; + } + return PM3_SUCCESS; } // none static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { + if (dest==NULL || file_ids_len==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; uint16_t sw = 0; @@ -417,17 +556,179 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { if (file_ids_len == NULL) return PM3_ESOFT; *file_ids_len = 0; int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); - if (res != PM3_SUCCESS) return res; + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res)); + DropField(); + return res; + } *file_ids_len = recv_len; return res; } static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { + if (dest==NULL || destlen==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); + int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res)); + DropField(); + return res; + } + return res; } +typedef struct { + uint8_t aid[3]; + uint8_t keysetting1; + uint8_t keysetting2; + uint8_t fid[2]; + uint8_t name[16]; +} aidhdr_t; + +static int get_desfire_createapp(aidhdr_t* aidhdr) { + if (aidhdr==NULL) return PM3_ESOFT; + sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA + uint16_t sw = 0; + int recvlen=0; + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res)); + DropField(); + return res; + } + return res; +} + +static int CmdHF14ADesCreateApp(const char *Cmd) { + if (Cmd==NULL) return PM3_ESOFT; + clearCommandBuffer(); + + CLIParserInit("hf mfdes caid", + "Create Application ID", + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes caid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to create"), + arg_strx0("fF", "fid", "", "File ID"), + arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), + arg_strx0("lL", "keysetting2", "", "Key Setting 2"), + arg_strx0("nN", "name", "", "App ISO-4 Name"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + /* KeySetting 1 (AMK Setting): + 0: Allow change master key + 1: Free Directory list access without master key + 0: AMK auth needed for GetFileSettings and GetKeySettings + 1: No AMK auth needed for GetFileIDs, GetISOFileIDs, GetFileSettings, GetKeySettings + 2: Free create/delete without master key + 0: CreateFile/DeleteFile only with AMK auth + 1: CreateFile/DeleteFile always + 3: Configuration changable + 0: Configuration frozen + 1: Configuration changable if authenticated with AMK (default) + 4-7: ChangeKey Access Rights + 0: Application master key needed (default) + 0x1..0xD: Auth with specific key needed to change any key + 0xE: Auth with the key to be changed (same KeyNo) is necessary to change a key + 0xF: All Keys within this application are frozen + + */ + /* KeySetting 2: + 0..3: Number of keys stored within the application (max. 14 keys + 4: RFU + 5: Use of 2 byte ISO FID, 0: No, 1: Yes + 6..7: Crypto Method 00: DES/3DES, 01: 3K3DES, 10: AES + Example: + 2E = FID, DES, 14 keys + 6E = FID, 3K3DES, 14 keys + AE = FID, AES, 14 keys + */ + int aidlength = 3; + int fidlength = 2; + uint8_t aid[3] = {0}; + uint8_t fid[2] = {0}; + uint8_t name[16] = {0}; + uint8_t keysetting1=0; + uint8_t keysetting2=0; + int keylen1=1; + int keylen2=1; + int namelen=16; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIGetHexWithReturn(2, fid, &fidlength); + CLIGetHexWithReturn(3, &keysetting1, &keylen1); + CLIGetHexWithReturn(4, &keysetting2, &keylen2); + CLIGetHexWithReturn(5, name, &namelen); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (fidlength < 2) { + PrintAndLogEx(ERR, "FID must have 2 bytes length."); + return PM3_EINVARG; + } + + if (keylen1 < 1) { + PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); + return PM3_EINVARG; + } + + if (keylen1 < 2) { + PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); + return PM3_EINVARG; + } + + if (namelen > 16) { + PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); + return PM3_EINVARG; + } + + //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 + /*char name[]="Test"; + uint8_t aid[]={0x12,0x34,0x56}; + uint8_t fid[]={0x11,0x22}; + uint8_t keysetting1=0xEE; + uint8_t keysetting2=0xEE;*/ + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Creating root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + aidhdr_t aidhdr; + memcpy(aidhdr.aid,aid,sizeof(aid)); + aidhdr.keysetting1=keysetting1; + aidhdr.keysetting2=keysetting2; + memcpy(aidhdr.fid,fid,sizeof(fid)); + memcpy(aidhdr.name,name,sizeof(name)); + + return get_desfire_createapp(&aidhdr); +} + +static int CmdHF14ADesFormatPICC(const char *Cmd) { + (void) Cmd; // Cmd is not used so far + + sAPDU apdu = {0xFC, 0xF3, 0x10, 0x00, 0x00, NONE}; // fc f3 10 + uint16_t sw = 0; + int recvlen=0; + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res)); + DropField(); + return res; + } + + return PM3_SUCCESS; +} + + static int CmdHF14ADesInfo(const char *Cmd) { (void)Cmd; // Cmd is not used so far @@ -481,7 +782,11 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, "");// No data pm3: no data available, no host frame available (not really an error) +#define PM3_ENODATA -98 +// Quit program client: reserved, order to quit the program +#define PM3_EFATAL -99 + PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); @@ -608,22 +913,21 @@ char *getVersionStr(uint8_t major, uint8_t minor) { return buf; } -void getKeySettings(uint8_t *aid) { - +int getKeySettings(uint8_t *aid) { + if (aid==NULL) return PM3_ESOFT; + int res=0; if (memcmp(aid, "\x00\x00\x00", 3) == 0) { // CARD MASTER KEY //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return; - } + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - if (get_desfire_keysettings(&key_setting, &num_keys) == PM3_SUCCESS) { + res=get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { // number of Master keys (0x01) PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); @@ -660,15 +964,15 @@ void getKeySettings(uint8_t *aid) { // Authentication tests int res = test_desfire_authenticate(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); res = test_desfire_authenticate_iso(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); res = test_desfire_authenticate_aes(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -677,16 +981,14 @@ void getKeySettings(uint8_t *aid) { // AID - APPLICATION MASTER KEYS //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return; - } + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - if (get_desfire_keysettings(&key_setting, &num_keys) == PM3_SUCCESS) { + res=get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { desfire_print_keysetting(key_setting, num_keys); } else { PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); @@ -716,6 +1018,7 @@ void getKeySettings(uint8_t *aid) { } DropField(); + return PM3_SUCCESS; } static int CmdHF14ADesEnumApplications(const char *Cmd) { @@ -732,6 +1035,8 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { dfname_t dfnames[255] = {0}; uint8_t dfname_count = 0; + int res=0; + if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); DropField(); @@ -771,14 +1076,14 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { } } - getKeySettings(aid); + res=getKeySettings(aid); + if (res!=PM3_SUCCESS) + { + PrintAndLogEx(WARNING, _RED_(" Can't get Key Settings for AID %X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[0],GetErrorString(res)); + } - - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; // Get File IDs if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { @@ -830,6 +1135,8 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { + if (Cmd==NULL) return PM3_ESOFT; + int res=0; clearCommandBuffer(); // NR DESC KEYLENGHT // ------------------------ @@ -938,20 +1245,13 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_EINVARG; } - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; - int res = get_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Get file ids error."); - DropField(); - return res; - } + res = get_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; // algo, keylength, @@ -992,6 +1292,8 @@ static command_t CommandTable[] = { {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, + {"caid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, + {"fmtp", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, {NULL, NULL, NULL, NULL} @@ -1005,6 +1307,7 @@ static int CmdHelp(const char *Cmd) { int CmdHFMFDes(const char *Cmd) { // flush + if (Cmd==NULL) return PM3_ESOFT; clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index 4f6605cff..c1ed4ed60 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -17,7 +17,7 @@ int CmdHFMFDes(const char *Cmd); char *getCardSizeStr(uint8_t fsize); char *getProtocolStr(uint8_t id); char *getVersionStr(uint8_t major, uint8_t minor); -void getKeySettings(uint8_t *aid); +int getKeySettings(uint8_t *aid); // Ev1 card limits #define MAX_NUM_KEYS 0x0F @@ -28,55 +28,6 @@ void getKeySettings(uint8_t *aid); #define NOT_YET_AUTHENTICATED 0xFF -// status- and error codes | -#define OPERATION_OK 0x00 // Successful operation -#define NO_CHANGES 0x0C // No changes done to backup files -// ,CommitTransaction/ -// AbortTransaction not necessary -#define OUT_OF_EEPROM_ERROR 0x0E // Insufficient NV-Memory to -// complete command -#define ILLEGAL_COMMAND_CODE 0x1C // Command code not supported -#define INTEGRITY_ERROR 0x1E // CRC or MAC does not match data -// Padding bytes not valid -#define NO_SUCH_KEY 0x40 // Invalid key number specified -#define LENGTH_ERROR 0x7E // Length of command string invalid -#define PERMISSION_DENIED 0x9D // Current configuration status -// does not allow the requested -// command -#define PARAMETER_ERROR 0x9E // Value of the parameter(s) inval. -#define APPLICATION_NOT_FOUND 0xA0 // Requested AID not present on PIC -#define APPL_INTEGRITY_ERROR 0xA1 // [1] // Unrecoverable error within app- -// lication, app will be disabled -#define AUTHENTICATION_ERROR 0xAE // Current authentication status -// does not allow the requested -// command -#define ADDITIONAL_FRAME 0xAF // Additional data frame is -// expected to be sent -#define BOUNDARY_ERROR 0xBE // Attempt to read/write data from/ -// to beyond the file's/record's -// limits. Attempt to exceed the -// limits of a value file. -#define PICC_INTEGRITY_ERROR 0xC1 // [1] // Unrecoverable error within PICC -// ,PICC will be disabled -#define COMMAND_ABORTED 0xCA // Previous Command was not fully -// completed Not all Frames were -// requested or provided by PCD -#define PICC_DISABLED_ERROR 0xCD // [1] // PICC was disabled by an unrecoverable error -#define COUNT_ERROR 0xCE // Number of Applications limited -// to 28, no additional -// CreateApplication possible -#define DUPLICATE_ERROR 0xDE // Creation of file/application -// failed because file/application -// with same number already exists -#define EEPROM_ERROR 0xEE // [1] // Could not complete NV-write -// operation due to loss of power, -// internal backup/rollback -// mechanism activated -#define FILE_NOT_FOUND_ERROR 0xF0 // Specified file number does not -// exist -#define FILE_INTEGRITY_ERROR 0xF1 // [1] // Unrecoverable error within file, -// file will be disabled -// -// [1] These errors are not expected to appear during normal operation + #endif diff --git a/include/protocols.h b/include/protocols.h index 03953fcc6..1bfa588c2 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -350,21 +350,17 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // MIFARE DESFire command set: - #define MFDES_GET_VERSION 0x60 - #define MFDES_AUTHENTICATE 0x0A // AUTHENTICATE_NATIVE #define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD #define MFDES_AUTHENTICATE_AES 0xAA - +#define MFDES_CREATE_APPLICATION 0xCA #define MFDES_CREDIT 0x0C #define MFDES_LIMITED_CREDIT 0x1C #define MFDES_DEBIT 0xDC - #define MFDES_WRITE_RECORD 0x3B #define MFDES_READSIG 0x3C #define MFDES_WRITE_DATA 0x3D - #define MFDES_GET_KEY_SETTINGS 0x45 #define MFDES_CHANGE_KEY_SETTINGS 0x54 #define MFDES_SELECT_APPLICATION 0x5A @@ -376,18 +372,35 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_GET_FREE_MEMORY 0x6E #define MFDES_GET_DF_NAMES 0x6D #define MFDES_GET_FILE_IDS 0x6F - - -#define MFDES_ABORT_TRANSACTION 0xA7 -#define MFDES_AUTHENTICATION_FRAME 0xAF -#define MFDES_ADDITIONAL_FRAME 0xAF -#define MFDES_ADDITIONAL_FRAME_RESP 0x91AF -#define MFDES_SUCCESS_FRAME_RESP 0x9100 -#define MFDES_EAUTH_RESP 0x91AE -#define MFDES_ENO_SUCH_KEY_RESP 0x9140 - #define MFDES_READ_RECORDS 0xBB #define MFDES_READ_DATA 0xBD +#define MFDES_ABORT_TRANSACTION 0xA7 + +// MIFARE DESFire status set: + +#define MFDES_OPERATION_OK 0x00 +#define MFDES_NO_CHANGES 0x0C +#define MFDES_ADDITIONAL_FRAME 0xAF +#define MFDES_E_OUT_OF_EEPROM 0x0E +#define MFDES_E_ILLEGAL_COMMAND_CODE 0x1C +#define MFDES_E_INTEGRITY_ERROR 0x1E +#define MFDES_E_NO_SUCH_KEY 0x40 +#define MFDES_E_LENGTH 0x7E +#define MFDES_E_PERMISSION_DENIED 0x9D +#define MFDES_E_PARAMETER_ERROR 0x9E +#define MFDES_E_APPLICATION_NOT_FOUND 0xA0 +#define MFDES_E_APPL_INTEGRITY 0xA1 +#define MFDES_E_AUTHENTIFICATION_ERROR 0xAE +#define MFDES_E_BOUNDARY 0xBE +#define MFDES_E_PICC_INTEGRITY 0xC1 +#define MFDES_E_COMMAND_ABORTED 0xCA +#define MFDES_E_PICC_DISABLED 0xCD +#define MFDES_E_COUNT 0xCE +#define MFDES_E_DUPLICATE 0xDE +#define MFDES_E_EEPROM 0xEE +#define MFDES_E_FILE_NOT_FOUND 0xF0 +#define MFDES_E_FILE_INTEGRITY 0xF1 + #define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 #define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 From 705cb9e18a26a835be0892c06147b4e20628df2a Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 17:21:22 +0200 Subject: [PATCH 06/66] Remove non-sense --- client/cmdhfmfdes.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index fcd2f227b..b04d14dc4 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -782,11 +782,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); - PrintAndLogEx(NORMAL, "");// No data pm3: no data available, no host frame available (not really an error) -#define PM3_ENODATA -98 -// Quit program client: reserved, order to quit the program -#define PM3_EFATAL -99 - + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); From aba7c88565536597434a94cd7350e17294badb9e Mon Sep 17 00:00:00 2001 From: Iceman Date: Thu, 9 Apr 2020 18:43:26 +0200 Subject: [PATCH 07/66] Update Troubleshooting.md --- doc/md/Installation_Instructions/Troubleshooting.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index e727180bf..3fba71e1c 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -18,7 +18,7 @@ Always use the latest repository commits from *master* branch. There are always * [File not found](#file-not-found) * [Pixmap / pixbuf warnings](#pixmap--pixbuf-warnings) * [Usb cable](#usb-cable) - * [WSL 2 explorer.exe . doesnt work](WSL-2) + * [WSL 2 explorer.exe . doesnt work](#WSL-2) ## `pm3` or `pm3-flash*` doesn't see my Proxmark From 2959f91fb68c738cecf74786c5f548a542f77efd Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 19:15:17 +0200 Subject: [PATCH 08/66] Add file settings decoder --- client/cmdhfmfdes.c | 238 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 193 insertions(+), 45 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index b04d14dc4..b4db78942 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -109,9 +109,9 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { if (GetAPDULogging()) { if (isw >> 8 == 0x61) { - PrintAndLogEx(ERR, "APDU chaining len:%02x -->", isw & 0xff); + PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); } else { - PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); + PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [0x%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); return PM3_EAPDU_FAIL; } } @@ -179,64 +179,64 @@ static int getstatus(int res, uint16_t * sw) if (((*sw>>8)&0xFF)==0x91){ switch (*sw&0xFF){ case MFDES_E_OUT_OF_EEPROM: - PrintAndLogEx(ERR, "APDU error: %02x --> Out of Eeprom, insufficient NV-Memory to complete command", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Out of Eeprom, insufficient NV-Memory to complete command", *sw & 0xff); break; case MFDES_E_ILLEGAL_COMMAND_CODE: - PrintAndLogEx(ERR, "APDU error: %02x --> Command code not supported", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Command code not supported", *sw & 0xff); break; case MFDES_E_INTEGRITY_ERROR: - PrintAndLogEx(ERR, "APDU error: %02x --> CRC or MAC does not match data / Padding bytes invalid", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> CRC or MAC does not match data / Padding bytes invalid", *sw & 0xff); break; case MFDES_E_NO_SUCH_KEY: - PrintAndLogEx(ERR, "APDU error: %02x --> Invalid key number specified", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Invalid key number specified", *sw & 0xff); break; case MFDES_E_LENGTH: - PrintAndLogEx(ERR, "APDU error: %02x --> Length of command string invalid", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Length of command string invalid", *sw & 0xff); break; case MFDES_E_PERMISSION_DENIED: - PrintAndLogEx(ERR, "APDU error: %02x --> Current configuration/status does not allow the requested command", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Current configuration/status does not allow the requested command", *sw & 0xff); break; case MFDES_E_PARAMETER_ERROR: - PrintAndLogEx(ERR, "APDU error: %02x --> Value of the parameter(s) invalid", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Value of the parameter(s) invalid", *sw & 0xff); break; case MFDES_E_APPLICATION_NOT_FOUND: - PrintAndLogEx(ERR, "APDU error: %02x --> Requested AID not present on PICC", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Requested AID not present on PICC", *sw & 0xff); break; case MFDES_E_APPL_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: %02x --> Application integrity error, application will be disabled", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Application integrity error, application will be disabled", *sw & 0xff); break; case MFDES_E_AUTHENTIFICATION_ERROR: - PrintAndLogEx(ERR, "APDU error: %02x --> Current authentication status does not allow the requested command", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Current authentication status does not allow the requested command", *sw & 0xff); break; case MFDES_E_BOUNDARY: - PrintAndLogEx(ERR, "APDU error: %02x --> Attempted to read/write data from/to beyong the file's/record's limit", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Attempted to read/write data from/to beyong the file's/record's limit", *sw & 0xff); break; case MFDES_E_PICC_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: %02x --> PICC integrity error, PICC will be disabled", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> PICC integrity error, PICC will be disabled", *sw & 0xff); break; case MFDES_E_COMMAND_ABORTED: - PrintAndLogEx(ERR, "APDU error: %02x --> Previous command was not fully completed / Not all Frames were requested or provided by the PCD", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Previous command was not fully completed / Not all Frames were requested or provided by the PCD", *sw & 0xff); break; case MFDES_E_PICC_DISABLED: - PrintAndLogEx(ERR, "APDU error: %02x --> PICC was disabled by an unrecoverable error", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> PICC was disabled by an unrecoverable error", *sw & 0xff); break; case MFDES_E_COUNT: - PrintAndLogEx(ERR, "APDU error: %02x --> Application count is limited to 28, not addition CreateApplication possible", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Application count is limited to 28, not addition CreateApplication possible", *sw & 0xff); break; case MFDES_E_DUPLICATE: - PrintAndLogEx(ERR, "APDU error: %02x --> Duplicate entry: File/Application does already exist", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Duplicate entry: File/Application does already exist", *sw & 0xff); break; case MFDES_E_EEPROM: - PrintAndLogEx(ERR, "APDU error: %02x --> Eeprom error due to loss of power, internal backup/rollback mechanism activated", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Eeprom error due to loss of power, internal backup/rollback mechanism activated", *sw & 0xff); break; case MFDES_E_FILE_NOT_FOUND: - PrintAndLogEx(ERR, "APDU error: %02x --> Specified file number does not exist", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Specified file number does not exist", *sw & 0xff); break; case MFDES_E_FILE_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: %02x --> File integrity error, file will be disabled", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> File integrity error, file will be disabled", *sw & 0xff); break; default: - PrintAndLogEx(ERR, "APDU error: %02x --> Unknown error", *sw & 0xff); + PrintAndLogEx(ERR, "APDU error: 0x%02x --> Unknown error", *sw & 0xff); break; } } @@ -308,7 +308,7 @@ static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { return UNKNOWN; } -//none +//none, verified static int test_desfire_authenticate() { uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 @@ -317,7 +317,7 @@ static int test_desfire_authenticate() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } -// none +// none, verified static int test_desfire_authenticate_iso() { uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 @@ -326,7 +326,7 @@ static int test_desfire_authenticate_iso() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } -//none +//none, verified static int test_desfire_authenticate_aes() { uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 @@ -335,13 +335,13 @@ static int test_desfire_authenticate_aes() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } -// --- FREE MEM +// --- FREE MEM, verified static int desfire_print_freemem(uint32_t free_mem) { PrintAndLogEx(SUCCESS, " Available free memory on card : " _GREEN_("%d bytes"), free_mem); return PM3_SUCCESS; } -// init / disconnect +// init / disconnect, verified static int get_desfire_freemem(uint32_t *free_mem) { if (free_mem==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E @@ -359,8 +359,13 @@ static int get_desfire_freemem(uint32_t *free_mem) { } -// --- GET SIGNATURE +// --- GET SIGNATURE, verified static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { + if (g_debugMode) + { + if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); + if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + } if (uid==NULL || signature==NULL) return PM3_ESOFT; // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -411,8 +416,13 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign return PM3_SUCCESS; } -// init / disconnect +// init / disconnect, verified static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { + if (g_debugMode) + { + if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); + } if (signature==NULL || signature_len==NULL) return PM3_ESOFT; uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C @@ -439,7 +449,7 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { // --- KEY SETTING static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { - PrintAndLogEx(SUCCESS, " AID Key settings : %02x", key_settings); + PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys); PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(SUCCESS, " Changekey Access rights"); @@ -468,8 +478,13 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { return PM3_SUCCESS; } -// none +// none, verified static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { + if (g_debugMode) + { + if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); + if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); + } if (key_settings==NULL || num_keys==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; @@ -491,8 +506,12 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { return PM3_SUCCESS; } -// none +// none, verified static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { + if (g_debugMode) + { + if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); + } if (num_versions==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; @@ -503,8 +522,13 @@ static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { } -// init / disconnect +// init / disconnect, verified static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + if (g_debugMode) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); + } if (dest==NULL || app_ids_len==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; @@ -517,7 +541,13 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { return res; } +// init, verified static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + if (g_debugMode) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); + } if (dest==NULL || dfname_count==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; @@ -531,23 +561,32 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { } -// init +// init, verified static int get_desfire_select_application(uint8_t *aid) { + if (g_debugMode) + { + if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); + } if (aid==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID %X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res)); DropField(); return res; } return PM3_SUCCESS; } -// none +// none, verified static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { + if (g_debugMode) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); + } if (dest==NULL || file_ids_len==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; @@ -565,7 +604,13 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { return res; } +// none, verified static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { + if (g_debugMode) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); + } if (dest==NULL || destlen==NULL) return PM3_ESOFT; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; @@ -680,7 +725,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return PM3_EINVARG; } - if (keylen1 < 2) { + if (keylen1 < 1) { PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); return PM3_EINVARG; } @@ -777,16 +822,16 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionHW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionHW[2]); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionHW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionHW[2]); PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionSW[2]); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionSW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionSW[2]); PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); @@ -1017,6 +1062,109 @@ int getKeySettings(uint8_t *aid) { return PM3_SUCCESS; } +static void DecodeFileType(uint8_t filetype){ + switch (filetype) + { + case 0x00: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Standard Data File", filetype); + break; + case 0x01: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Backup Data File", filetype); + break; + case 0x02: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Value Files with Backup", filetype); + break; + case 0x03: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Linear Record Files with Backup", filetype); + break; + case 0x04: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Cyclic Record Files with Backup", filetype); + break; + default: + PrintAndLogEx(INFO, " File Type: 0x%02X", filetype); + break; + } +} + +static void DecodeComSet(uint8_t comset){ + switch (comset) + { + case 0x00: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain", comset); + break; + case 0x01: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain + MAC", comset); + break; + case 0x03: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Enciphered", comset); + break; + default: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X", comset); + break; + } +} + +static char* DecodeAccessValue(uint8_t value) +{ + char* car=(char*)malloc(255); + memset(car,0x0,255); + switch(value){ + case 0xE: + strcat(car, "(Free Access)"); + break; + case 0xF: + strcat(car, "(Denied Access)"); + break; + default: + sprintf(car,"(Access Key: %d)",value); + break; + } + return car; +} + +static void DecodeAccessRights(uint16_t accrights){ + int change_access_rights=accrights&0xF; + int read_write_access=(accrights>>4)&0xF; + int write_access=(accrights>>8)&0xF; + int read_access=(accrights>>12)&0xF; + char* car=DecodeAccessValue(change_access_rights); + char* rwa=DecodeAccessValue(read_write_access); + char* wa=DecodeAccessValue(write_access); + char* ra=DecodeAccessValue(read_access); + PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights,car,rwa,wa,ra); + free(car); + free(rwa); + free(wa); + free(ra); +} + +static int DecodeFileSettings(uint8_t* filesettings, int fileset_len, int maclen){ + uint8_t filetype=filesettings[0]; + uint8_t comset=filesettings[1]; + + uint16_t accrights=(filesettings[4]<<8)+filesettings[3]; + if (fileset_len==1+1+2+3+maclen) + { + int filesize=(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Filesize: %d", filesize); + return PM3_SUCCESS; + } else if (fileset_len==1+1+2+4+4+4+1+maclen) { + int lowerlimit=(filesettings[8]<<24)+(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; + int upperlimit=(filesettings[12]<<24)+(filesettings[11]<<16)+(filesettings[10]<<8)+filesettings[9]; + int limitcredvalue=(filesettings[16]<<24)+(filesettings[15]<<16)+(filesettings[14]<<8)+filesettings[13]; + uint8_t limited_credit_enabled=filesettings[17]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Lower limit: %d - Upper limit: %d - limited credit value: %d - limited credit enabled: %d", lowerlimit, upperlimit, limitcredvalue, limited_credit_enabled); + return PM3_SUCCESS; + } + return PM3_ESOFT; +} + static int CmdHF14ADesEnumApplications(const char *Cmd) { (void)Cmd; // Cmd is not used so far @@ -1090,15 +1238,15 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t filesettings[20] = {0}; int fileset_len = 0; int res = get_desfire_filesettings(j, filesettings, &fileset_len); + int maclen=0; // To be implemented if (res == PM3_SUCCESS) { - PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + if (DecodeFileSettings(filesettings,fileset_len,maclen)!=PM3_SUCCESS){ + PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + } } } } - - - /* // Get ISO File IDs { From b14dbf19974dc8ef9f001b3f564006a48c593546 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 19:22:57 +0200 Subject: [PATCH 09/66] Add fixes --- client/cmdhfmfdes.c | 48 +++++++++++++++++---------------------------- 1 file changed, 18 insertions(+), 30 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index b4db78942..2d52e4bd8 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -172,7 +172,7 @@ static char* GetErrorString(int res) static int getstatus(int res, uint16_t * sw) { - if (sw==NULL) return PM3_ESOFT; + if (sw==NULL) return PM3_EINVARG; if (res==PM3_EAPDU_FAIL) { @@ -254,7 +254,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l if (sw==NULL) PrintAndLogEx(ERR, "SW=NULL"); if (recv_len==NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); } - if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_ESOFT; + if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_EINVARG; *sw = 0; uint8_t data[255 * 5] = {0x00}; @@ -343,7 +343,7 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect, verified static int get_desfire_freemem(uint32_t *free_mem) { - if (free_mem==NULL) return PM3_ESOFT; + if (free_mem==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E int recv_len = 0; uint16_t sw = 0; @@ -366,7 +366,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); } - if (uid==NULL || signature==NULL) return PM3_ESOFT; + if (uid==NULL || signature==NULL) return PM3_EINVARG; // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -423,7 +423,7 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); } - if (signature==NULL || signature_len==NULL) return PM3_ESOFT; + if (signature==NULL || signature_len==NULL) return PM3_EINVARG; uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C int recv_len = 0; @@ -485,13 +485,11 @@ static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); } - if (key_settings==NULL || num_keys==NULL) return PM3_ESOFT; + if (key_settings==NULL || num_keys==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; - if (num_keys == NULL) return PM3_ESOFT; - if (key_settings == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); if (res != PM3_SUCCESS) return res; @@ -512,11 +510,10 @@ static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { { if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); } - if (num_versions==NULL) return PM3_ESOFT; + if (num_versions==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; - if (num_versions == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); return res; } @@ -529,12 +526,10 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); } - if (dest==NULL || app_ids_len==NULL) return PM3_ESOFT; + if (dest==NULL || app_ids_len==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (app_ids_len == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0); if (res != PM3_SUCCESS) return res; *app_ids_len = (uint8_t)recv_len & 0xFF; @@ -548,12 +543,10 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); } - if (dest==NULL || dfname_count==NULL) return PM3_ESOFT; + if (dest==NULL || dfname_count==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (dfname_count == NULL) return PM3_ESOFT; int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t)); if (res != PM3_SUCCESS) return res; *dfname_count = recv_len; @@ -567,7 +560,7 @@ static int get_desfire_select_application(uint8_t *aid) { { if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); } - if (aid==NULL) return PM3_ESOFT; + if (aid==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; @@ -587,12 +580,10 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); } - if (dest==NULL || file_ids_len==NULL) return PM3_ESOFT; + if (dest==NULL || file_ids_len==NULL) return return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (file_ids_len == NULL) return PM3_ESOFT; *file_ids_len = 0; int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); if (res != PM3_SUCCESS) { @@ -611,7 +602,7 @@ static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); } - if (dest==NULL || destlen==NULL) return PM3_ESOFT; + if (dest==NULL || destlen==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); @@ -632,7 +623,7 @@ typedef struct { } aidhdr_t; static int get_desfire_createapp(aidhdr_t* aidhdr) { - if (aidhdr==NULL) return PM3_ESOFT; + if (aidhdr==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA uint16_t sw = 0; int recvlen=0; @@ -646,13 +637,12 @@ static int get_desfire_createapp(aidhdr_t* aidhdr) { } static int CmdHF14ADesCreateApp(const char *Cmd) { - if (Cmd==NULL) return PM3_ESOFT; clearCommandBuffer(); - CLIParserInit("hf mfdes caid", + CLIParserInit("hf mfdes createaid", "Create Application ID", "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes caid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" + "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" ); void *argtable[] = { @@ -955,7 +945,7 @@ char *getVersionStr(uint8_t major, uint8_t minor) { } int getKeySettings(uint8_t *aid) { - if (aid==NULL) return PM3_ESOFT; + if (aid==NULL) return PM3_EINVARG; int res=0; if (memcmp(aid, "\x00\x00\x00", 3) == 0) { @@ -1279,7 +1269,6 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { - if (Cmd==NULL) return PM3_ESOFT; int res=0; clearCommandBuffer(); // NR DESC KEYLENGHT @@ -1436,8 +1425,8 @@ static command_t CommandTable[] = { {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, - {"caid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, - {"fmtp", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, + {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, + {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, {NULL, NULL, NULL, NULL} @@ -1451,7 +1440,6 @@ static int CmdHelp(const char *Cmd) { int CmdHFMFDes(const char *Cmd) { // flush - if (Cmd==NULL) return PM3_ESOFT; clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } From 3b915d343b6cb71b051bf95cf9f2a0479fa9fd75 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 19:51:35 +0200 Subject: [PATCH 10/66] Add delete aid and minor fix --- client/cmdhfmfdes.c | 51 ++++++++++++++++++++++++++++++++++++++++++++- include/protocols.h | 1 + 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 2d52e4bd8..28ae124f1 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -580,7 +580,7 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); } - if (dest==NULL || file_ids_len==NULL) return return PM3_EINVARG; + if (dest==NULL || file_ids_len==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; uint16_t sw = 0; @@ -636,6 +636,20 @@ static int get_desfire_createapp(aidhdr_t* aidhdr) { return res; } +static int get_desfire_deleteapp(uint8_t* aid) { + if (aid==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA + uint16_t sw = 0; + int recvlen=0; + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res)); + DropField(); + return res; + } + return res; +} + static int CmdHF14ADesCreateApp(const char *Cmd) { clearCommandBuffer(); @@ -747,6 +761,40 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return get_desfire_createapp(&aidhdr); } +static int CmdHF14ADesDeleteApp(const char *Cmd) { + clearCommandBuffer(); + + CLIParserInit("hf mfdes deleteaid", + "Delete Application ID", + "Usage:\n\t-a aid (3 bytes)\n\n" + "Example:\n\thf mfdes deleteaid -a 123456\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to delete"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Deleting root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + return get_desfire_deleteapp(aid); +} + + static int CmdHF14ADesFormatPICC(const char *Cmd) { (void) Cmd; // Cmd is not used so far @@ -1426,6 +1474,7 @@ static command_t CommandTable[] = { {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, + {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, diff --git a/include/protocols.h b/include/protocols.h index 1bfa588c2..3bb2dcc3c 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -355,6 +355,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD #define MFDES_AUTHENTICATE_AES 0xAA #define MFDES_CREATE_APPLICATION 0xCA +#define MFDES_DELETE_APPLICATION 0xDA #define MFDES_CREDIT 0x0C #define MFDES_LIMITED_CREDIT 0x1C #define MFDES_DEBIT 0xDC From 68733cd7cf74b68a2b00620036aa3e6b69f84cc6 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 20:03:59 +0200 Subject: [PATCH 11/66] Minor fixes. Create AID and Delete AID working. --- client/cmdhfmfdes.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 28ae124f1..a1882b762 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -241,7 +241,7 @@ static int getstatus(int res, uint16_t * sw) } } } else { - PrintAndLogEx(ERR, "%s",GetErrorString(res)); + PrintAndLogEx(ERR, "sw: 0x%04X, err: %s",*sw,GetErrorString(res)); } return res; } @@ -629,7 +629,7 @@ static int get_desfire_createapp(aidhdr_t* aidhdr) { int recvlen=0; int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),getstatus(res,&sw)); DropField(); return res; } @@ -665,7 +665,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { arg_strx0("fF", "fid", "", "File ID"), arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), arg_strx0("lL", "keysetting2", "", "Key Setting 2"), - arg_strx0("nN", "name", "", "App ISO-4 Name"), + arg_str0("nN", "name", "", "App ISO-4 Name"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, true); @@ -711,7 +711,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { CLIGetHexWithReturn(2, fid, &fidlength); CLIGetHexWithReturn(3, &keysetting1, &keylen1); CLIGetHexWithReturn(4, &keysetting2, &keylen2); - CLIGetHexWithReturn(5, name, &namelen); + CLIGetStrWithReturn(5, name, &namelen); CLIParserFree(); if (aidlength < 3) { @@ -758,6 +758,10 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { memcpy(aidhdr.fid,fid,sizeof(fid)); memcpy(aidhdr.name,name,sizeof(name)); + uint8_t rootaid[3]={0x00,0x00,0x00}; + int res=get_desfire_select_application(rootaid); + if (res!=PM3_SUCCESS) return res; + return get_desfire_createapp(&aidhdr); } @@ -791,6 +795,9 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { return PM3_ESOFT; } + uint8_t rootaid[3]={0x00,0x00,0x00}; + int res=get_desfire_select_application(rootaid); + if (res!=PM3_SUCCESS) return res; return get_desfire_deleteapp(aid); } From 58af8c004d1719d955bc057490d6ed89409a3612 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 22:08:17 +0200 Subject: [PATCH 12/66] FormatPICC not working. Other things look good --- client/cmdhfmfdes.c | 295 +++++++++++++++++++++++++------------------- 1 file changed, 171 insertions(+), 124 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index a1882b762..173b8e125 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -115,13 +115,84 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t return PM3_EAPDU_FAIL; } } + return PM3_EAPDU_FAIL; } return PM3_SUCCESS; } -static char* GetErrorString(int res) +static char* getstatus(uint16_t * sw) +{ + if (sw==NULL) return "--> sw argument error. This should never happen !"; + if (((*sw>>8)&0xFF)==0x91){ + switch (*sw&0xFF){ + case MFDES_E_OUT_OF_EEPROM: + return "Out of Eeprom, insufficient NV-Memory to complete command"; + case MFDES_E_ILLEGAL_COMMAND_CODE: + return "Command code not supported"; + + case MFDES_E_INTEGRITY_ERROR: + return "CRC or MAC does not match data / Padding bytes invalid"; + + case MFDES_E_NO_SUCH_KEY: + return "Invalid key number specified"; + + case MFDES_E_LENGTH: + return "Length of command string invalid"; + + case MFDES_E_PERMISSION_DENIED: + return "Current configuration/status does not allow the requested command"; + + case MFDES_E_PARAMETER_ERROR: + return "Value of the parameter(s) invalid"; + + case MFDES_E_APPLICATION_NOT_FOUND: + return "Requested AID not present on PICC"; + + case MFDES_E_APPL_INTEGRITY: + return "Application integrity error, application will be disabled"; + + case MFDES_E_AUTHENTIFICATION_ERROR: + return "Current authentication status does not allow the requested command"; + + case MFDES_E_BOUNDARY: + return "Attempted to read/write data from/to beyong the file's/record's limit"; + + case MFDES_E_PICC_INTEGRITY: + return "PICC integrity error, PICC will be disabled"; + + case MFDES_E_COMMAND_ABORTED: + return "Previous command was not fully completed / Not all Frames were requested or provided by the PCD"; + + case MFDES_E_PICC_DISABLED: + return "PICC was disabled by an unrecoverable error"; + + case MFDES_E_COUNT: + return "Application count is limited to 28, not addition CreateApplication possible"; + + case MFDES_E_DUPLICATE: + return "Duplicate entry: File/Application does already exist"; + + case MFDES_E_EEPROM: + return "Eeprom error due to loss of power, internal backup/rollback mechanism activated"; + + case MFDES_E_FILE_NOT_FOUND: + return "Specified file number does not exist"; + + case MFDES_E_FILE_INTEGRITY: + return "File integrity error, file will be disabled"; + + default: + return "Unknown error"; + } + } + return "Unknown error"; +} + +static char* GetErrorString(int res,uint16_t* sw) { switch(res){ + case PM3_EAPDU_FAIL: + return getstatus(sw); case PM3_EUNDEF: return "Undefined error"; case PM3_EINVARG: @@ -170,84 +241,9 @@ static char* GetErrorString(int res) return ""; } -static int getstatus(int res, uint16_t * sw) -{ - if (sw==NULL) return PM3_EINVARG; - if (res==PM3_EAPDU_FAIL) - { - if (((*sw>>8)&0xFF)==0x91){ - switch (*sw&0xFF){ - case MFDES_E_OUT_OF_EEPROM: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Out of Eeprom, insufficient NV-Memory to complete command", *sw & 0xff); - break; - case MFDES_E_ILLEGAL_COMMAND_CODE: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Command code not supported", *sw & 0xff); - break; - case MFDES_E_INTEGRITY_ERROR: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> CRC or MAC does not match data / Padding bytes invalid", *sw & 0xff); - break; - case MFDES_E_NO_SUCH_KEY: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Invalid key number specified", *sw & 0xff); - break; - case MFDES_E_LENGTH: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Length of command string invalid", *sw & 0xff); - break; - case MFDES_E_PERMISSION_DENIED: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Current configuration/status does not allow the requested command", *sw & 0xff); - break; - case MFDES_E_PARAMETER_ERROR: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Value of the parameter(s) invalid", *sw & 0xff); - break; - case MFDES_E_APPLICATION_NOT_FOUND: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Requested AID not present on PICC", *sw & 0xff); - break; - case MFDES_E_APPL_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Application integrity error, application will be disabled", *sw & 0xff); - break; - case MFDES_E_AUTHENTIFICATION_ERROR: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Current authentication status does not allow the requested command", *sw & 0xff); - break; - case MFDES_E_BOUNDARY: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Attempted to read/write data from/to beyong the file's/record's limit", *sw & 0xff); - break; - case MFDES_E_PICC_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> PICC integrity error, PICC will be disabled", *sw & 0xff); - break; - case MFDES_E_COMMAND_ABORTED: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Previous command was not fully completed / Not all Frames were requested or provided by the PCD", *sw & 0xff); - break; - case MFDES_E_PICC_DISABLED: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> PICC was disabled by an unrecoverable error", *sw & 0xff); - break; - case MFDES_E_COUNT: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Application count is limited to 28, not addition CreateApplication possible", *sw & 0xff); - break; - case MFDES_E_DUPLICATE: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Duplicate entry: File/Application does already exist", *sw & 0xff); - break; - case MFDES_E_EEPROM: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Eeprom error due to loss of power, internal backup/rollback mechanism activated", *sw & 0xff); - break; - case MFDES_E_FILE_NOT_FOUND: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Specified file number does not exist", *sw & 0xff); - break; - case MFDES_E_FILE_INTEGRITY: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> File integrity error, file will be disabled", *sw & 0xff); - break; - default: - PrintAndLogEx(ERR, "APDU error: 0x%02x --> Unknown error", *sw & 0xff); - break; - } - } - } else { - PrintAndLogEx(ERR, "sw: 0x%04X, err: %s",*sw,GetErrorString(res)); - } - return res; -} - -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize) { - if (g_debugMode) +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize,bool readalldata) { + if (g_debugMode>1) { if (apdu==NULL) PrintAndLogEx(ERR, "APDU=NULL"); if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); @@ -262,17 +258,39 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l int pos = 0; int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return getstatus(res,sw); + if (res != PM3_SUCCESS) { + if (apdu->INS==MFDES_READSIG) return PM3_SUCCESS; //Fix me ! Error code 0x9190 ??? + if (g_debugMode>1) GetErrorString(res,sw); + return res; + } if (dest != NULL) { memcpy(dest, data, resplen); } pos += resplen; + if (!readalldata) + { + if (*sw==status(MFDES_ADDITIONAL_FRAME)) { + apdu->INS = MFDES_ABORT_TRANSACTION; + apdu->Lc = 0; + apdu->P1 = 0; + apdu->P2 = 0; + res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); + return PM3_SUCCESS; + } + return res; + } while (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF + apdu->Lc=0; + apdu->P1=0; + apdu->P2=0; res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return getstatus(res,sw); + if (res != PM3_SUCCESS){ + if (g_debugMode>1) GetErrorString(res,sw); + return res; + } if (dest != NULL) { if (splitbysize) { memcpy(&dest[i * splitbysize], data, resplen); @@ -314,7 +332,7 @@ static int test_desfire_authenticate() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); } // none, verified @@ -323,7 +341,7 @@ static int test_desfire_authenticate_iso() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); } //none, verified @@ -332,7 +350,7 @@ static int test_desfire_authenticate_aes() { sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); } // --- FREE MEM, verified @@ -349,7 +367,7 @@ static int get_desfire_freemem(uint32_t *free_mem) { uint16_t sw = 0; uint8_t fmem[4] = {0}; - int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0,true); if (res == PM3_SUCCESS) { *free_mem = le24toh(fmem); return res; @@ -361,7 +379,7 @@ static int get_desfire_freemem(uint32_t *free_mem) { // --- GET SIGNATURE, verified static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { - if (g_debugMode) + if (g_debugMode>1) { if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); @@ -418,7 +436,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign // init / disconnect, verified static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - if (g_debugMode) + if (g_debugMode>1) { if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); @@ -428,7 +446,7 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0,true); if (res == PM3_SUCCESS) { if (recv_len != 56) { *signature_len = 0; @@ -480,7 +498,7 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none, verified static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - if (g_debugMode) + if (g_debugMode>1) { if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); @@ -490,7 +508,7 @@ static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; - int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0,true); if (res != PM3_SUCCESS) return res; *key_settings = data[0]; @@ -506,7 +524,7 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { // none, verified static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - if (g_debugMode) + if (g_debugMode>1) { if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); } @@ -514,14 +532,14 @@ static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0,true); return res; } // init / disconnect, verified static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { - if (g_debugMode) + if (g_debugMode>1) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); @@ -530,7 +548,7 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0,true); if (res != PM3_SUCCESS) return res; *app_ids_len = (uint8_t)recv_len & 0xFF; return res; @@ -538,7 +556,7 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { // init, verified static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { - if (g_debugMode) + if (g_debugMode>1) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); @@ -547,7 +565,7 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t)); + int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t),true); if (res != PM3_SUCCESS) return res; *dfname_count = recv_len; return res; @@ -556,7 +574,7 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { // init, verified static int get_desfire_select_application(uint8_t *aid) { - if (g_debugMode) + if (g_debugMode>1) { if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); } @@ -564,9 +582,9 @@ static int get_desfire_select_application(uint8_t *aid) { sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); + int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t),true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res,&sw)); DropField(); return res; } @@ -575,7 +593,7 @@ static int get_desfire_select_application(uint8_t *aid) { // none, verified static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { - if (g_debugMode) + if (g_debugMode>1) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); @@ -585,9 +603,9 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { int recv_len = 0; uint16_t sw = 0; *file_ids_len = 0; - int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0,true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res,&sw)); DropField(); return res; } @@ -597,7 +615,7 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { // none, verified static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { - if (g_debugMode) + if (g_debugMode>1) { if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); @@ -605,9 +623,9 @@ static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen if (dest==NULL || destlen==NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); + int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0,true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res,&sw)); DropField(); return res; } @@ -627,9 +645,9 @@ static int get_desfire_createapp(aidhdr_t* aidhdr) { sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA uint16_t sw = 0; int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),getstatus(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res,&sw)); DropField(); return res; } @@ -641,9 +659,9 @@ static int get_desfire_deleteapp(uint8_t* aid) { sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA uint16_t sw = 0; int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res,&sw)); DropField(); return res; } @@ -802,22 +820,52 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { } +/* static int CmdHF14ADesFormatPICC(const char *Cmd) { (void) Cmd; // Cmd is not used so far + DropField(); + + + int keylength=8; + uint8_t key[8]={0}; + uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) + memcpy(data + 1, key, keylength); + SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylength + 1); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + uint8_t isOK = resp.oldarg[0] & 0xff; + if (isOK) { + uint8_t *session_key = resp.data.asBytes; + + PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); + PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + //PrintAndLogEx(NORMAL, " Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); + } else { + PrintAndLogEx(WARNING, _RED_("Client command failed.")); + } + + sAPDU apdu = {0xFC, 0xF3, 0x10, 0x00, 0x00, NONE}; // fc f3 10 uint16_t sw = 0; int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0); + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res)); + PrintAndLogEx(WARNING, _RED_(" Can't create format picc 0x%x -> %s"),sw,GetErrorString(res,&sw)); DropField(); return res; } return PM3_SUCCESS; } - +*/ static int CmdHF14ADesInfo(const char *Cmd) { (void)Cmd; // Cmd is not used so far @@ -1266,13 +1314,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { } res=getKeySettings(aid); - if (res!=PM3_SUCCESS) - { - PrintAndLogEx(WARNING, _RED_(" Can't get Key Settings for AID %X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[0],GetErrorString(res)); - } + if (res!=PM3_SUCCESS) return res; res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + // Get File IDs if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { @@ -1433,14 +1478,15 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_EINVARG; } - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; - - uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; - res = get_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) return res; + if (memcmp(aid,"\x00\x00\x00",3)!=0){ + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + uint8_t file_ids[33] = {0}; + uint8_t file_ids_len = 0; + res = get_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; + } // algo, keylength, uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) @@ -1482,7 +1528,7 @@ static command_t CommandTable[] = { {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, - {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, + //{"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, {NULL, NULL, NULL, NULL} @@ -1497,5 +1543,6 @@ static int CmdHelp(const char *Cmd) { int CmdHFMFDes(const char *Cmd) { // flush clearCommandBuffer(); + //g_debugMode=2; return CmdsParse(CommandTable, Cmd); } From 7aba4ffff132dbffb4a82b468a7e34931aa8508b Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 22:39:31 +0200 Subject: [PATCH 13/66] Fix frame command for auth --- armsrc/mifareutil.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index b0bf532b0..6d269e38e 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -697,7 +697,7 @@ int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData) { int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData) { int len; - uint8_t data[17] = {MFDES_AUTHENTICATION_FRAME}; + uint8_t data[17] = {MFDES_ADDITIONAL_FRAME}; memcpy(data + 1, key, 16); uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; From d49885dd12b435be7f843cc21ace978c02b68125 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 23:16:18 +0200 Subject: [PATCH 14/66] Fix des auth --- armsrc/mifaredesfire.c | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index b2f45d117..f913268e6 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -246,9 +246,18 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) else if (arg1 == 1) Desfire_des_key_new(keybytes, key); + cmd[0] = AUTHENTICATE; + cmd[1] = 0x0; + cmd[2] = 0x0; + cmd[3] = 0x1; + cmd[4] = arg2; //keynumber + cmd[5] = 0x0; + len = DesfireAPDU(cmd, 6, resp); + + /*cmd[0] = AUTHENTICATE; cmd[1] = arg2; //keynumber - len = DesfireAPDU(cmd, 2, resp); + len = DesfireAPDU(cmd, 2, resp);*/ if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -257,14 +266,13 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[2] == 0xaf) { - } else { + if (resp[2] == (uint8_t)0xaf) { DbpString("Authentication failed. Invalid key number."); OnError(3); return; } - memcpy(encRndB, resp + 3, 8); + memcpy(encRndB, resp + 1, 8); if (arg1 == 2) tdes_dec(&decRndB, &encRndB, key->data); else if (arg1 == 1) @@ -298,9 +306,12 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(both + 8, encRndB, 8); cmd[0] = ADDITIONAL_FRAME; - memcpy(cmd + 1, both, 16); - - len = DesfireAPDU(cmd, 17, resp); + cmd[1] = 0x00; + cmd[2] = 0x00; + cmd[3] = 0x10; + memcpy(cmd + 4, both, 16); + cmd[16+4]=0x0; + len = DesfireAPDU(cmd, 4+16+1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -309,14 +320,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[2] == 0x00) { + if (resp[len-3] == 0x00) { struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; Desfire_session_key_new(RndA, RndB, key, skey); //print_result("SESSION : ", skey->data, 8); - memcpy(encRndA, resp + 3, 8); + memcpy(encRndA, resp + 1, 8); if (arg1 == 2) tdes_dec(&encRndA, &encRndA, key->data); @@ -326,15 +337,15 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) rol(decRndA, 8); for (int x = 0; x < 8; x++) { if (decRndA[x] != encRndA[x]) { - DbpString("Authentication failed. Cannot varify PICC."); + DbpString("Authentication failed. Cannot verify PICC."); OnError(4); return; } } //Change the selected key to a new value. - /* + /* // Current key is a 3DES key, change it to a DES key if (arg1 == 2) { cmd[0] = CHANGE_KEY; From 8571a770feb5008895eeb424df7f16bb4dee178e Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 23:30:49 +0200 Subject: [PATCH 15/66] Make auth random --- armsrc/mifaredesfire.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index f913268e6..572779900 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -16,6 +16,7 @@ #include "commonutil.h" #include "util.h" #include "mifare.h" +#include "ticks.h" #define MAX_APPLICATION_COUNT 28 #define MAX_FILE_COUNT 16 @@ -283,6 +284,11 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) // This should be random uint8_t decRndA[8] = {0x00}; + uint32_t value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[0]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[4]); + memcpy(RndA, decRndA, 8); uint8_t encRndA[8] = {0x00}; @@ -448,7 +454,6 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp); break; case 3: { - //defaultkey uint8_t keybytes[16] = {0x00}; if (datain[1] == 0xff) { @@ -493,6 +498,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, decRndB); rol(decRndB, 16); uint8_t nonce[16] = {0x00}; + uint32_t val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[0]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[4]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[8]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[12]); memcpy(both, nonce, 16); memcpy(both + 16, decRndB, 16); uint8_t encBoth[32] = {0x00}; From 8983324c21c7a0c35c0070a0db9595d9185dc3cc Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Thu, 9 Apr 2020 23:49:14 +0200 Subject: [PATCH 16/66] Make host cmds more flexible --- armsrc/mifaredesfire.c | 68 +++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 572779900..17e411e72 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -138,7 +138,7 @@ void MifareDesfireGetInformation() { memcpy(payload.uid, card.uid, sizeof(payload.uid)); LED_A_ON(); - uint8_t cmd[] = {GET_VERSION, 0x00, 0x00, 0x00}; + uint8_t cmd[] = {0x90, GET_VERSION, 0x00, 0x00, 0x00}; size_t cmd_len = sizeof(cmd); len = DesfireAPDU(cmd, cmd_len, resp); @@ -153,7 +153,7 @@ void MifareDesfireGetInformation() { memcpy(payload.versionHW, resp + 1, sizeof(payload.versionHW)); // ADDITION_FRAME 1 - cmd[0] = ADDITIONAL_FRAME; + cmd[1] = ADDITIONAL_FRAME; len = DesfireAPDU(cmd, cmd_len, resp); if (!len) { print_result("ERROR <--: ", resp, len); @@ -247,18 +247,15 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) else if (arg1 == 1) Desfire_des_key_new(keybytes, key); - - cmd[0] = AUTHENTICATE; - cmd[1] = 0x0; + cmd[0] = 0x90; + cmd[1] = AUTHENTICATE; cmd[2] = 0x0; - cmd[3] = 0x1; - cmd[4] = arg2; //keynumber - cmd[5] = 0x0; - len = DesfireAPDU(cmd, 6, resp); + cmd[3] = 0x0; + cmd[4] = 0x1; + cmd[5] = arg2; //keynumber + cmd[6] = 0x0; + len = DesfireAPDU(cmd, 7, resp); - /*cmd[0] = AUTHENTICATE; - cmd[1] = arg2; //keynumber - len = DesfireAPDU(cmd, 2, resp);*/ if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -311,13 +308,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(both + 8, encRndB, 8); - cmd[0] = ADDITIONAL_FRAME; - cmd[1] = 0x00; + cmd[0] = 0x90; + cmd[1] = ADDITIONAL_FRAME; cmd[2] = 0x00; - cmd[3] = 0x10; - memcpy(cmd + 4, both, 16); - cmd[16+4]=0x0; - len = DesfireAPDU(cmd, 4+16+1, resp); + cmd[3] = 0x00; + cmd[4] = 0x10; + memcpy(cmd + 5, both, 16); + cmd[16+5]=0x0; + len = DesfireAPDU(cmd, 5+16+1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -470,13 +468,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t IV[16] = {0x00}; mbedtls_aes_init(&ctx); - cmd[0] = AUTHENTICATE_AES; - cmd[1] = 0x0; + cmd[0] = 0x90; + cmd[1] = AUTHENTICATE_AES; cmd[2] = 0x0; - cmd[3] = 0x1; - cmd[4] = arg2; //keynumber - cmd[5] = 0x0; - len = DesfireAPDU(cmd, 6, resp); + cmd[3] = 0x0; + cmd[4] = 0x1; + cmd[5] = arg2; //keynumber + cmd[6] = 0x0; + len = DesfireAPDU(cmd, 7, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -518,14 +517,15 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, both, encBoth); - cmd[0] = ADDITIONAL_FRAME; - cmd[1] = 0x00; + cmd[0] = 0x90; + cmd[1] = ADDITIONAL_FRAME; cmd[2] = 0x00; - cmd[3] = 0x20; - memcpy(cmd + 4, encBoth, 32); - cmd[36]=0x0; + cmd[3] = 0x00; + cmd[4] = 0x20; + memcpy(cmd + 5, encBoth, 32); + cmd[32+5]=0x0; - len = DesfireAPDU(cmd, 37, resp); // 4 + 32 + 1 == 37 + len = DesfireAPDU(cmd, 5+32+1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -594,7 +594,7 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout) { // CreateAPDU size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) { - size_t cmdlen = MIN(len + 4, PM3_CMD_DATA_SIZE - 1); + size_t cmdlen = MIN(len + 3, PM3_CMD_DATA_SIZE - 1); uint8_t cmd[cmdlen]; memset(cmd, 0, cmdlen); @@ -604,10 +604,10 @@ size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) { if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("pcb_blocknum %d == %d ", pcb_blocknum, cmd[0] ); - cmd[1] = 0x90; // CID: 0x00 //TODO: allow multiple selected cards + //cmd[1] = 0x90; // CID: 0x00 //TODO: allow multiple selected cards - memcpy(cmd + 2, datain, len); - AddCrc14A(cmd, len + 2); + memcpy(cmd + 1, datain, len); + AddCrc14A(cmd, len + 1); /* hf 14a apdu -sk 90 60 00 00 00 From c4831ccd9bfd2c99383ce091528ec948a64f823d Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:03:23 +0200 Subject: [PATCH 17/66] Do not deselect at end of auth --- armsrc/mifaredesfire.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 17e411e72..67c0329a4 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -436,7 +436,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } */ - OnSuccess(); + //OnSuccess(); if (arg1 == 2) reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); else if (arg1 == 1) @@ -550,7 +550,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } } - OnSuccess(); + //OnSuccess(); reply_mix(CMD_ACK, 1, len, 0, resp, len); } From c9b27732f52d6b43f098aa1f2d10bb336b60c600 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:14:45 +0200 Subject: [PATCH 18/66] Make ISO auth work --- armsrc/mifaredesfire.c | 152 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 142 insertions(+), 10 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 67c0329a4..d01384279 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -352,8 +352,9 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) /* // Current key is a 3DES key, change it to a DES key if (arg1 == 2) { - cmd[0] = CHANGE_KEY; - cmd[1] = arg2; + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = arg2; uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; @@ -382,20 +383,21 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) buff3[x] = buff3[x] ^ buff2[x]; } tdes_dec(&buff3, &buff3, skey->data); - memcpy(cmd+18,buff3,8); + memcpy(cmd+19,buff3,8); // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; while(!len) { - len = DesfireAPDU(cmd,26,resp); + len = DesfireAPDU(cmd,27,resp); } } else { // Current key is a DES key, change it to a 3DES key if (arg1 == 1) { - cmd[0] = CHANGE_KEY; - cmd[1] = arg2; + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = arg2; uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; @@ -412,25 +414,25 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(buff3 + 1, &second, 1); des_dec(&buff1, &buff1, skey->data); - memcpy(cmd+2,buff1,8); + memcpy(cmd+3,buff1,8); for (int x = 0; x < 8; x++) { buff2[x] = buff2[x] ^ buff1[x]; } des_dec(&buff2, &buff2, skey->data); - memcpy(cmd+10,buff2,8); + memcpy(cmd+11,buff2,8); for (int x = 0; x < 8; x++) { buff3[x] = buff3[x] ^ buff2[x]; } des_dec(&buff3, &buff3, skey->data); - memcpy(cmd+18,buff3,8); + memcpy(cmd+19,buff3,8); // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; while(!len) { - len = DesfireAPDU(cmd,26,resp); + len = DesfireAPDU(cmd,27,resp); } } } @@ -449,7 +451,137 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } break; case 2: + { //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp); + uint8_t keybytes[16]; + uint8_t RndA[8] = {0x00}; + uint8_t RndB[8] = {0x00}; + + if (arg1 == 2) { + if (datain[1] == 0xff) { + memcpy(keybytes, PICC_MASTER_KEY16, 16); + } else { + memcpy(keybytes, datain + 1, datalen); + } + } else { + if (arg1 == 1) { + if (datain[1] == 0xff) { + uint8_t null_key_data8[8] = {0x00}; + memcpy(keybytes, null_key_data8, 8); + } else { + memcpy(keybytes, datain + 1, datalen); + } + } + } + + struct desfire_key defaultkey = {0}; + desfirekey_t key = &defaultkey; + + if (arg1 == 2) + Desfire_3des_key_new_with_version(keybytes, key); + else if (arg1 == 1) + Desfire_des_key_new(keybytes, key); + + cmd[0] = AUTHENTICATE; + cmd[1] = arg2; //keynumber + len = DesfireAPDU(cmd, 2, resp); + + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if (resp[2] == (uint8_t)0xaf) { + DbpString("Authentication failed. Invalid key number."); + OnError(3); + return; + } + + memcpy(encRndB, resp + 2, 8); + if (arg1 == 2) + tdes_dec(&decRndB, &encRndB, key->data); + else if (arg1 == 1) + des_dec(&decRndB, &encRndB, key->data); + + memcpy(RndB, decRndB, 8); + rol(decRndB, 8); + + // This should be random + uint8_t decRndA[8] = {0x00}; + uint32_t value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[0]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[4]); + + memcpy(RndA, decRndA, 8); + uint8_t encRndA[8] = {0x00}; + + if (arg1 == 2) + tdes_dec(&encRndA, &decRndA, key->data); + else if (arg1 == 1) + des_dec(&encRndA, &decRndA, key->data); + + memcpy(both, encRndA, 8); + + for (int x = 0; x < 8; x++) { + decRndB[x] = decRndB[x] ^ encRndA[x]; + + } + + if (arg1 == 2) + tdes_dec(&encRndB, &decRndB, key->data); + else if (arg1 == 1) + des_dec(&encRndB, &decRndB, key->data); + + memcpy(both + 8, encRndB, 8); + + cmd[0] = ADDITIONAL_FRAME; + memcpy(cmd + 1, both, 16); + len = DesfireAPDU(cmd, 1+16, resp); + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if (resp[1] == 0x00) { + struct desfire_key sessionKey = {0}; + desfirekey_t skey = &sessionKey; + Desfire_session_key_new(RndA, RndB, key, skey); + //print_result("SESSION : ", skey->data, 8); + + memcpy(encRndA, resp + 2, 8); + + if (arg1 == 2) + tdes_dec(&encRndA, &encRndA, key->data); + else if (arg1 == 1) + des_dec(&encRndA, &encRndA, key->data); + + rol(decRndA, 8); + for (int x = 0; x < 8; x++) { + if (decRndA[x] != encRndA[x]) { + DbpString("Authentication failed. Cannot verify PICC."); + OnError(4); + return; + } + } + + //OnSuccess(); + if (arg1 == 2) + reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); + else if (arg1 == 1) + reply_old(CMD_ACK, 1, 0, 0, skey->data, 8); + } else { + DbpString("Authentication failed."); + OnError(6); + return; + } + } break; case 3: { //defaultkey From 3098a6bca007648bc159247b67680061ecfffbe2 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:36:15 +0200 Subject: [PATCH 19/66] Format PICC working --- client/cmdhfmfdes.c | 80 +++++++++++++++++++++++++++------------------ 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 173b8e125..dbbba844a 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -820,18 +820,40 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { } -/* static int CmdHF14ADesFormatPICC(const char *Cmd) { (void) Cmd; // Cmd is not used so far + CLIParserInit("hf mfdes formatpicc", + "Formats MIFARE DESFire PICC to factory state", + "Usage:\n\t-k PICC key (8 bytes)\n\n" + "Example:\n\thf mfdes formatpicc -k 0000000000000000\n" + ); + void *argtable[] = { + arg_param_begin, + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + + uint8_t key[8] = {0}; + int keylen = 8; + CLIGetHexWithReturn(1, key, &keylen); + CLIParserFree(); + + if ((keylen < 8) || (keylen > 8)) { + PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + clearCommandBuffer(); DropField(); - - - int keylength=8; - uint8_t key[8]={0}; - uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) - memcpy(data + 1, key, keylength); - SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylength + 1); + uint8_t aid[3]={0}; + int res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) + memcpy(data + 1, key, keylen); + SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); PacketResponseNG resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { @@ -842,30 +864,24 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { uint8_t isOK = resp.oldarg[0] & 0xff; if (isOK) { - uint8_t *session_key = resp.data.asBytes; - - PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); - PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - //PrintAndLogEx(NORMAL, " Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); + uint8_t rdata[] = {0xFC}; // 0xFC + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client reset command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + if (resp.oldarg[0]&0xFF){ + PrintAndLogEx(INFO, "Card successfully reset"); + return PM3_SUCCESS; + } } else { - PrintAndLogEx(WARNING, _RED_("Client command failed.")); - } - - - sAPDU apdu = {0xFC, 0xF3, 0x10, 0x00, 0x00, NONE}; // fc f3 10 - uint16_t sw = 0; - int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create format picc 0x%x -> %s"),sw,GetErrorString(res,&sw)); - DropField(); - return res; + PrintAndLogEx(WARNING, _RED_("Auth command failed.")); } return PM3_SUCCESS; } -*/ + static int CmdHF14ADesInfo(const char *Cmd) { (void)Cmd; // Cmd is not used so far @@ -1370,6 +1386,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { int res=0; + DropField(); clearCommandBuffer(); // NR DESC KEYLENGHT // ------------------------ @@ -1478,10 +1495,11 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_EINVARG; } - if (memcmp(aid,"\x00\x00\x00",3)!=0){ - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + + if (memcmp(aid,"\x00\x00\x00",3)!=0){ uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; res = get_desfire_fileids(file_ids, &file_ids_len); @@ -1528,7 +1546,7 @@ static command_t CommandTable[] = { {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, - //{"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, + {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, {NULL, NULL, NULL, NULL} From 7191aa8b1442c9c8d89a8edbcc23b0102ca8dbaf Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:56:37 +0200 Subject: [PATCH 20/66] Fix signature command. Special response 0x9190 ? --- client/cmdhfmfdes.c | 7 +++++-- include/protocols.h | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index dbbba844a..7a6e78b6f 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -106,7 +106,7 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t if (sw) *sw = isw; - if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { + if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_SIGNATURE) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { if (GetAPDULogging()) { if (isw >> 8 == 0x61) { PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); @@ -259,7 +259,6 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { - if (apdu->INS==MFDES_READSIG) return PM3_SUCCESS; //Fix me ! Error code 0x9190 ??? if (g_debugMode>1) GetErrorString(res,sw); return res; } @@ -451,6 +450,7 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { if (recv_len != 56) { *signature_len = 0; DropField(); + PrintAndLogEx(SUCCESS, " Signature verified: %d " _GREEN_("successful"), recv_len); return PM3_ESOFT; } else { *signature_len = recv_len; @@ -974,6 +974,9 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) desfire_print_signature(package->uid, signature, signature_len, cardtype); + else{ + PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature.")); + } // Master Key settings uint8_t master_aid[3] = {0x00, 0x00, 0x00}; diff --git a/include/protocols.h b/include/protocols.h index 3bb2dcc3c..357fa9e4d 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -401,6 +401,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_E_EEPROM 0xEE #define MFDES_E_FILE_NOT_FOUND 0xF0 #define MFDES_E_FILE_INTEGRITY 0xF1 +#define MFDES_SIGNATURE 0x90 #define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 From 685b1e47ef7d28701ec8824e38dab00d186c5754 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:58:08 +0200 Subject: [PATCH 21/66] Fix unnecessary stuff. --- client/cmdhfmfdes.c | 1 - 1 file changed, 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 7a6e78b6f..d3c0577b2 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -450,7 +450,6 @@ static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { if (recv_len != 56) { *signature_len = 0; DropField(); - PrintAndLogEx(SUCCESS, " Signature verified: %d " _GREEN_("successful"), recv_len); return PM3_ESOFT; } else { *signature_len = recv_len; From 7af0f07c4e476332dd1c3151639445ffebd267e8 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 00:59:06 +0200 Subject: [PATCH 22/66] Add useful signature info. --- client/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index d3c0577b2..4053d58a9 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -974,7 +974,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) desfire_print_signature(package->uid, signature, signature_len, cardtype); else{ - PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature.")); + PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature. Unknown public key ?")); } // Master Key settings From 82323b14e221afacfdf0b9fff3acebe70cc8bbf6 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 01:18:48 +0200 Subject: [PATCH 23/66] Make style --- CHANGELOG.md | 1 + armsrc/mifaredesfire.c | 47 +- client/cmdhflist.c | 6 +- client/cmdhfmfdes.c | 368 ++-- client/luascripts/legic.lua | 161 +- cmdhfmfdes.c | 1569 +++++++++++++++++ .../Troubleshooting.md | 2 +- 7 files changed, 1859 insertions(+), 295 deletions(-) create mode 100644 cmdhfmfdes.c diff --git a/CHANGELOG.md b/CHANGELOG.md index eff29cc79..0f15617c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) - Fix Mifare Desfire select appid handling (@bkerler) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index d01384279..ba2b20d2d 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -104,7 +104,7 @@ void MifareDesfireGetInformation() { uint8_t versionSW[7]; uint8_t details[14]; } PACKED payload; - + /* 1 = PCB 1 2 = cid 2 @@ -179,7 +179,7 @@ void MifareDesfireGetInformation() { LED_B_ON(); reply_ng(CMD_HF_DESFIRE_INFO, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload)); LED_B_OFF(); - + // reset the pcb_blocknum, pcb_blocknum = 0; OnSuccess(); @@ -314,8 +314,8 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) cmd[3] = 0x00; cmd[4] = 0x10; memcpy(cmd + 5, both, 16); - cmd[16+5]=0x0; - len = DesfireAPDU(cmd, 5+16+1, resp); + cmd[16 + 5] = 0x0; + len = DesfireAPDU(cmd, 5 + 16 + 1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -324,7 +324,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[len-3] == 0x00) { + if (resp[len - 3] == 0x00) { struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; @@ -450,8 +450,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } } break; - case 2: - { + case 2: { //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp); uint8_t keybytes[16]; uint8_t RndA[8] = {0x00}; @@ -540,7 +539,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) cmd[0] = ADDITIONAL_FRAME; memcpy(cmd + 1, both, 16); - len = DesfireAPDU(cmd, 1+16, resp); + len = DesfireAPDU(cmd, 1 + 16, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -580,9 +579,9 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) DbpString("Authentication failed."); OnError(6); return; - } } - break; + } + break; case 3: { //defaultkey uint8_t keybytes[16] = {0x00}; @@ -655,9 +654,9 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) cmd[3] = 0x00; cmd[4] = 0x20; memcpy(cmd + 5, encBoth, 32); - cmd[32+5]=0x0; + cmd[32 + 5] = 0x0; - len = DesfireAPDU(cmd, 5+32+1, resp); + len = DesfireAPDU(cmd, 5 + 32 + 1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -666,7 +665,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if ((resp[1+16] == 0x91)&&(resp[1+16+1] == 0x00)) { + if ((resp[1 + 16] == 0x91) && (resp[1 + 16 + 1] == 0x00)) { // Create AES Session key struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; @@ -713,10 +712,10 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout) { // if we received an I- or R(ACK)-Block with a block number equal to the // current block number, toggle the current block number if (len >= 4 // PCB+CID+CRC = 4 bytes - && ((resp[0] & 0xC0) == 0 // I-Block - || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 - && (resp[0] & 0x01) == pcb_blocknum) { // equal block numbers - pcb_blocknum ^= 1; //toggle next block + && ((resp[0] & 0xC0) == 0 // I-Block + || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 + && (resp[0] & 0x01) == pcb_blocknum) { // equal block numbers + pcb_blocknum ^= 1; //toggle next block } memcpy(dataout, resp, len); @@ -734,18 +733,18 @@ size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) { cmd[0] = 0x02; // 0x0A = send cid, 0x02 = no cid. cmd[0] |= pcb_blocknum; // OR the block number into the PCB - if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("pcb_blocknum %d == %d ", pcb_blocknum, cmd[0] ); + if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("pcb_blocknum %d == %d ", pcb_blocknum, cmd[0]); //cmd[1] = 0x90; // CID: 0x00 //TODO: allow multiple selected cards memcpy(cmd + 1, datain, len); AddCrc14A(cmd, len + 1); - -/* -hf 14a apdu -sk 90 60 00 00 00 -hf 14a apdu -k 90 AF 00 00 00 -hf 14a apdu 90AF000000 -*/ + + /* + hf 14a apdu -sk 90 60 00 00 00 + hf 14a apdu -k 90 AF 00 00 00 + hf 14a apdu 90AF000000 + */ memcpy(dataout, cmd, cmdlen); return cmdlen; } diff --git a/client/cmdhflist.c b/client/cmdhflist.c index b40b06d56..52894c52b 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -675,7 +675,7 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { // it's basically a ISO14443a tag, so try annotation from there if (applyIso14443a(exp, size, cmd, cmdsize) == 0) { - + // S-block 11xxx010 if ((cmd[0] & 0xC0) && (cmdsize == 3)) { switch ((cmd[0] & 0x30)) { @@ -707,9 +707,9 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { if ((cmd[0] & 0x04) == 0x04) // nad byte following pos++; - + for (uint8_t i = 0; i < 2; i++, pos++) { - + switch (cmd[pos]) { case MFDES_CREATE_APPLICATION: snprintf(exp, size, "CREATE APPLICATION"); diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 4053d58a9..3912bbe1f 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -64,6 +64,7 @@ static int CmdHelp(const char *Cmd); */ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { + *result_len = 0; if (sw) *sw = 0; @@ -120,11 +121,10 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t return PM3_SUCCESS; } -static char* getstatus(uint16_t * sw) -{ - if (sw==NULL) return "--> sw argument error. This should never happen !"; - if (((*sw>>8)&0xFF)==0x91){ - switch (*sw&0xFF){ +static char *getstatus(uint16_t *sw) { + if (sw == NULL) return "--> sw argument error. This should never happen !"; + if (((*sw >> 8) & 0xFF) == 0x91) { + switch (*sw & 0xFF) { case MFDES_E_OUT_OF_EEPROM: return "Out of Eeprom, insufficient NV-Memory to complete command"; case MFDES_E_ILLEGAL_COMMAND_CODE: @@ -188,9 +188,8 @@ static char* getstatus(uint16_t * sw) return "Unknown error"; } -static char* GetErrorString(int res,uint16_t* sw) -{ - switch(res){ +static char *GetErrorString(int res, uint16_t *sw) { + switch (res) { case PM3_EAPDU_FAIL: return getstatus(sw); case PM3_EUNDEF: @@ -242,15 +241,14 @@ static char* GetErrorString(int res,uint16_t* sw) } -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize,bool readalldata) { - if (g_debugMode>1) - { - if (apdu==NULL) PrintAndLogEx(ERR, "APDU=NULL"); - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (sw==NULL) PrintAndLogEx(ERR, "SW=NULL"); - if (recv_len==NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize, bool readalldata) { + if (g_debugMode > 1) { + if (apdu == NULL) PrintAndLogEx(ERR, "APDU=NULL"); + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (sw == NULL) PrintAndLogEx(ERR, "SW=NULL"); + if (recv_len == NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); } - if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_EINVARG; + if (apdu == NULL || sw == NULL || recv_len == NULL) return PM3_EINVARG; *sw = 0; uint8_t data[255 * 5] = {0x00}; @@ -259,7 +257,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { - if (g_debugMode>1) GetErrorString(res,sw); + if (g_debugMode > 1) GetErrorString(res, sw); return res; } if (dest != NULL) { @@ -267,9 +265,8 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } pos += resplen; - if (!readalldata) - { - if (*sw==status(MFDES_ADDITIONAL_FRAME)) { + if (!readalldata) { + if (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ABORT_TRANSACTION; apdu->Lc = 0; apdu->P1 = 0; @@ -281,13 +278,13 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } while (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF - apdu->Lc=0; - apdu->P1=0; - apdu->P2=0; + apdu->Lc = 0; + apdu->P1 = 0; + apdu->P2 = 0; res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS){ - if (g_debugMode>1) GetErrorString(res,sw); + if (res != PM3_SUCCESS) { + if (g_debugMode > 1) GetErrorString(res, sw); return res; } if (dest != NULL) { @@ -299,7 +296,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } } pos += resplen; - if (*sw!=status(MFDES_ADDITIONAL_FRAME)) break; + if (*sw != status(MFDES_ADDITIONAL_FRAME)) break; } if (splitbysize) *recv_len = i; else { @@ -327,29 +324,29 @@ static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { //none, verified static int test_desfire_authenticate() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, &c}; // 0x0A, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } // none, verified static int test_desfire_authenticate_iso() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, &c}; // 0x1A, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } //none, verified static int test_desfire_authenticate_aes() { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, &c}; // 0xAA, KEY 0 + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } // --- FREE MEM, verified @@ -360,13 +357,13 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect, verified static int get_desfire_freemem(uint32_t *free_mem) { - if (free_mem==NULL) return PM3_EINVARG; + if (free_mem == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; - int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { *free_mem = le24toh(fmem); return res; @@ -378,12 +375,11 @@ static int get_desfire_freemem(uint32_t *free_mem) { // --- GET SIGNATURE, verified static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { - if (g_debugMode>1) - { - if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); - if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + if (g_debugMode > 1) { + if (uid == NULL) PrintAndLogEx(ERR, "UID=NULL"); + if (signature == NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); } - if (uid==NULL || signature==NULL) return PM3_EINVARG; + if (uid == NULL || signature == NULL) return PM3_EINVARG; // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -435,17 +431,16 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign // init / disconnect, verified static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - if (g_debugMode>1) - { - if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); - if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); + if (g_debugMode > 1) { + if (signature == NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + if (signature_len == NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); } - if (signature==NULL || signature_len==NULL) return PM3_EINVARG; + if (signature == NULL || signature_len == NULL) return PM3_EINVARG; uint8_t c = 0x00; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { if (recv_len != 56) { *signature_len = 0; @@ -497,17 +492,16 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none, verified static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - if (g_debugMode>1) - { - if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); - if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); + if (g_debugMode > 1) { + if (key_settings == NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); + if (num_keys == NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); } - if (key_settings==NULL || num_keys==NULL) return PM3_EINVARG; + if (key_settings == NULL || num_keys == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; - int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) return res; *key_settings = data[0]; @@ -523,31 +517,29 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { // none, verified static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - if (g_debugMode>1) - { - if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); + if (g_debugMode > 1) { + if (num_versions == NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); } - if (num_versions==NULL) return PM3_EINVARG; + if (num_versions == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); return res; } // init / disconnect, verified static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (app_ids_len == NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); } - if (dest==NULL || app_ids_len==NULL) return PM3_EINVARG; + if (dest == NULL || app_ids_len == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) return res; *app_ids_len = (uint8_t)recv_len & 0xFF; return res; @@ -555,16 +547,15 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { // init, verified static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); } - if (dest==NULL || dfname_count==NULL) return PM3_EINVARG; + if (dest == NULL || dfname_count == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t),true); + int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t), true); if (res != PM3_SUCCESS) return res; *dfname_count = recv_len; return res; @@ -573,17 +564,16 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { // init, verified static int get_desfire_select_application(uint8_t *aid) { - if (g_debugMode>1) - { - if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); + if (g_debugMode > 1) { + if (aid == NULL) PrintAndLogEx(ERR, "AID=NULL"); } - if (aid==NULL) return PM3_EINVARG; + if (aid == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t),true); + int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t), true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[0] << 16) + (aid[1] << 8) + aid[2], GetErrorString(res, &sw)); DropField(); return res; } @@ -592,19 +582,18 @@ static int get_desfire_select_application(uint8_t *aid) { // none, verified static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (file_ids_len == NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); } - if (dest==NULL || file_ids_len==NULL) return PM3_EINVARG; + if (dest == NULL || file_ids_len == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; uint16_t sw = 0; *file_ids_len = 0; - int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0,true); + int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"), GetErrorString(res, &sw)); DropField(); return res; } @@ -614,17 +603,16 @@ static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { // none, verified static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (destlen == NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); } - if (dest==NULL || destlen==NULL) return PM3_EINVARG; + if (dest == NULL || destlen == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0,true); + int res = send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0, true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"), GetErrorString(res, &sw)); DropField(); return res; } @@ -639,28 +627,28 @@ typedef struct { uint8_t name[16]; } aidhdr_t; -static int get_desfire_createapp(aidhdr_t* aidhdr) { - if (aidhdr==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA +static int get_desfire_createapp(aidhdr_t *aidhdr) { + if (aidhdr == NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t *)aidhdr}; // 0xCA uint16_t sw = 0; - int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); + int recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"), GetErrorString(res, &sw)); DropField(); return res; } return res; } -static int get_desfire_deleteapp(uint8_t* aid) { - if (aid==NULL) return PM3_EINVARG; +static int get_desfire_deleteapp(uint8_t *aid) { + if (aid == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA uint16_t sw = 0; - int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); + int recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res,&sw)); + PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"), GetErrorString(res, &sw)); DropField(); return res; } @@ -674,16 +662,16 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { "Create Application ID", "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to create"), - arg_strx0("fF", "fid", "", "File ID"), - arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), - arg_strx0("lL", "keysetting2", "", "Key Setting 2"), - arg_str0("nN", "name", "", "App ISO-4 Name"), - arg_param_end + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to create"), + arg_strx0("fF", "fid", "", "File ID"), + arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), + arg_strx0("lL", "keysetting2", "", "Key Setting 2"), + arg_str0("nN", "name", "", "App ISO-4 Name"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, true); /* KeySetting 1 (AMK Setting): @@ -719,11 +707,11 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { uint8_t aid[3] = {0}; uint8_t fid[2] = {0}; uint8_t name[16] = {0}; - uint8_t keysetting1=0; - uint8_t keysetting2=0; - int keylen1=1; - int keylen2=1; - int namelen=16; + uint8_t keysetting1 = 0; + uint8_t keysetting2 = 0; + int keylen1 = 1; + int keylen2 = 1; + int namelen = 16; CLIGetHexWithReturn(1, aid, &aidlength); CLIGetHexWithReturn(2, fid, &fidlength); CLIGetHexWithReturn(3, &keysetting1, &keylen1); @@ -769,15 +757,15 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { } aidhdr_t aidhdr; - memcpy(aidhdr.aid,aid,sizeof(aid)); - aidhdr.keysetting1=keysetting1; - aidhdr.keysetting2=keysetting2; - memcpy(aidhdr.fid,fid,sizeof(fid)); - memcpy(aidhdr.name,name,sizeof(name)); + memcpy(aidhdr.aid, aid, sizeof(aid)); + aidhdr.keysetting1 = keysetting1; + aidhdr.keysetting2 = keysetting2; + memcpy(aidhdr.fid, fid, sizeof(fid)); + memcpy(aidhdr.name, name, sizeof(name)); - uint8_t rootaid[3]={0x00,0x00,0x00}; - int res=get_desfire_select_application(rootaid); - if (res!=PM3_SUCCESS) return res; + uint8_t rootaid[3] = {0x00, 0x00, 0x00}; + int res = get_desfire_select_application(rootaid); + if (res != PM3_SUCCESS) return res; return get_desfire_createapp(&aidhdr); } @@ -789,12 +777,12 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { "Delete Application ID", "Usage:\n\t-a aid (3 bytes)\n\n" "Example:\n\thf mfdes deleteaid -a 123456\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to delete"), - arg_param_end + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to delete"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, true); int aidlength = 3; @@ -812,9 +800,9 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { return PM3_ESOFT; } - uint8_t rootaid[3]={0x00,0x00,0x00}; - int res=get_desfire_select_application(rootaid); - if (res!=PM3_SUCCESS) return res; + uint8_t rootaid[3] = {0x00, 0x00, 0x00}; + int res = get_desfire_select_application(rootaid); + if (res != PM3_SUCCESS) return res; return get_desfire_deleteapp(aid); } @@ -825,12 +813,12 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { "Formats MIFARE DESFire PICC to factory state", "Usage:\n\t-k PICC key (8 bytes)\n\n" "Example:\n\thf mfdes formatpicc -k 0000000000000000\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end + arg_param_begin, + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, true); @@ -847,9 +835,9 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { clearCommandBuffer(); DropField(); - uint8_t aid[3]={0}; - int res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + uint8_t aid[3] = {0}; + int res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) memcpy(data + 1, key, keylen); SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); @@ -870,7 +858,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { DropField(); return PM3_ETIMEOUT; } - if (resp.oldarg[0]&0xFF){ + if (resp.oldarg[0] & 0xFF) { PrintAndLogEx(INFO, "Card successfully reset"); return PM3_SUCCESS; } @@ -973,7 +961,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) desfire_print_signature(package->uid, signature, signature_len, cardtype); - else{ + else { PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature. Unknown public key ?")); } @@ -1066,19 +1054,19 @@ char *getVersionStr(uint8_t major, uint8_t minor) { } int getKeySettings(uint8_t *aid) { - if (aid==NULL) return PM3_EINVARG; - int res=0; + if (aid == NULL) return PM3_EINVARG; + int res = 0; if (memcmp(aid, "\x00\x00\x00", 3) == 0) { // CARD MASTER KEY //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res=get_desfire_keysettings(&key_setting, &num_keys); + res = get_desfire_keysettings(&key_setting, &num_keys); if (res == PM3_SUCCESS) { // number of Master keys (0x01) PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); @@ -1133,13 +1121,13 @@ int getKeySettings(uint8_t *aid) { // AID - APPLICATION MASTER KEYS //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res=get_desfire_keysettings(&key_setting, &num_keys); + res = get_desfire_keysettings(&key_setting, &num_keys); if (res == PM3_SUCCESS) { desfire_print_keysetting(key_setting, num_keys); } else { @@ -1173,9 +1161,8 @@ int getKeySettings(uint8_t *aid) { return PM3_SUCCESS; } -static void DecodeFileType(uint8_t filetype){ - switch (filetype) - { +static void DecodeFileType(uint8_t filetype) { + switch (filetype) { case 0x00: PrintAndLogEx(INFO, " File Type: 0x%02X -> Standard Data File", filetype); break; @@ -1197,9 +1184,8 @@ static void DecodeFileType(uint8_t filetype){ } } -static void DecodeComSet(uint8_t comset){ - switch (comset) - { +static void DecodeComSet(uint8_t comset) { + switch (comset) { case 0x00: PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain", comset); break; @@ -1215,11 +1201,10 @@ static void DecodeComSet(uint8_t comset){ } } -static char* DecodeAccessValue(uint8_t value) -{ - char* car=(char*)malloc(255); - memset(car,0x0,255); - switch(value){ +static char *DecodeAccessValue(uint8_t value) { + char *car = (char *)malloc(255); + memset(car, 0x0, 255); + switch (value) { case 0xE: strcat(car, "(Free Access)"); break; @@ -1227,46 +1212,45 @@ static char* DecodeAccessValue(uint8_t value) strcat(car, "(Denied Access)"); break; default: - sprintf(car,"(Access Key: %d)",value); + sprintf(car, "(Access Key: %d)", value); break; } return car; } -static void DecodeAccessRights(uint16_t accrights){ - int change_access_rights=accrights&0xF; - int read_write_access=(accrights>>4)&0xF; - int write_access=(accrights>>8)&0xF; - int read_access=(accrights>>12)&0xF; - char* car=DecodeAccessValue(change_access_rights); - char* rwa=DecodeAccessValue(read_write_access); - char* wa=DecodeAccessValue(write_access); - char* ra=DecodeAccessValue(read_access); - PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights,car,rwa,wa,ra); +static void DecodeAccessRights(uint16_t accrights) { + int change_access_rights = accrights & 0xF; + int read_write_access = (accrights >> 4) & 0xF; + int write_access = (accrights >> 8) & 0xF; + int read_access = (accrights >> 12) & 0xF; + char *car = DecodeAccessValue(change_access_rights); + char *rwa = DecodeAccessValue(read_write_access); + char *wa = DecodeAccessValue(write_access); + char *ra = DecodeAccessValue(read_access); + PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights, car, rwa, wa, ra); free(car); free(rwa); free(wa); free(ra); } -static int DecodeFileSettings(uint8_t* filesettings, int fileset_len, int maclen){ - uint8_t filetype=filesettings[0]; - uint8_t comset=filesettings[1]; +static int DecodeFileSettings(uint8_t *filesettings, int fileset_len, int maclen) { + uint8_t filetype = filesettings[0]; + uint8_t comset = filesettings[1]; - uint16_t accrights=(filesettings[4]<<8)+filesettings[3]; - if (fileset_len==1+1+2+3+maclen) - { - int filesize=(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; + uint16_t accrights = (filesettings[4] << 8) + filesettings[3]; + if (fileset_len == 1 + 1 + 2 + 3 + maclen) { + int filesize = (filesettings[7] << 16) + (filesettings[6] << 8) + filesettings[5]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); PrintAndLogEx(INFO, " Filesize: %d", filesize); return PM3_SUCCESS; - } else if (fileset_len==1+1+2+4+4+4+1+maclen) { - int lowerlimit=(filesettings[8]<<24)+(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; - int upperlimit=(filesettings[12]<<24)+(filesettings[11]<<16)+(filesettings[10]<<8)+filesettings[9]; - int limitcredvalue=(filesettings[16]<<24)+(filesettings[15]<<16)+(filesettings[14]<<8)+filesettings[13]; - uint8_t limited_credit_enabled=filesettings[17]; + } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) { + int lowerlimit = (filesettings[8] << 24) + (filesettings[7] << 16) + (filesettings[6] << 8) + filesettings[5]; + int upperlimit = (filesettings[12] << 24) + (filesettings[11] << 16) + (filesettings[10] << 8) + filesettings[9]; + int limitcredvalue = (filesettings[16] << 24) + (filesettings[15] << 16) + (filesettings[14] << 8) + filesettings[13]; + uint8_t limited_credit_enabled = filesettings[17]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); @@ -1287,10 +1271,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; - dfname_t dfnames[255] = {0}; + dfname_t dfnames[255]; uint8_t dfname_count = 0; - int res=0; + int res = 0; if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); @@ -1331,10 +1315,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { } } - res=getKeySettings(aid); - if (res!=PM3_SUCCESS) return res; + res = getKeySettings(aid); + if (res != PM3_SUCCESS) return res; - res=get_desfire_select_application(aid); + res = get_desfire_select_application(aid); // Get File IDs @@ -1346,9 +1330,9 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t filesettings[20] = {0}; int fileset_len = 0; int res = get_desfire_filesettings(j, filesettings, &fileset_len); - int maclen=0; // To be implemented + int maclen = 0; // To be implemented if (res == PM3_SUCCESS) { - if (DecodeFileSettings(filesettings,fileset_len,maclen)!=PM3_SUCCESS){ + if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) { PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); } } @@ -1387,7 +1371,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { - int res=0; + int res = 0; DropField(); clearCommandBuffer(); // NR DESC KEYLENGHT @@ -1498,10 +1482,10 @@ static int CmdHF14ADesAuth(const char *Cmd) { } - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; - if (memcmp(aid,"\x00\x00\x00",3)!=0){ + if (memcmp(aid, "\x00\x00\x00", 3) != 0) { uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; res = get_desfire_fileids(file_ids, &file_ids_len); diff --git a/client/luascripts/legic.lua b/client/luascripts/legic.lua index 7e0f8d3be..393cc9e52 100644 --- a/client/luascripts/legic.lua +++ b/client/luascripts/legic.lua @@ -91,14 +91,20 @@ CRC1 = crc8 over addr 0x00..0x03+0x07..0x0E (special 'gantner crc8') CRC2 = MCD + MSB0..2+ addr 0x06 + addr 0x05 + addr 0x07 + Stamp (regular Master-Token-CRC) --]] +--[[ +Known issues; needs to be fixed: +* last byte in last segment is handled incorrectly when it is the last bytes on the card itself (MIM256: => byte 256) +--]] + example = "script run legic" -author = "Mosci" -version = "1.0.3" +author = "Mosci, uhei" +version = "1.0.4" desc = [[ This script helps you to read, create and modify Legic Prime Tags (MIM22, MIM256, MIM1024) +The virtual tag (and therefore the file to be saved) is always a MIM1024 tag. it's kinda interactive with following commands in three categories: Data I/O Segment Manipulation Token-Data @@ -108,8 +114,8 @@ it's kinda interactive with following commands in three categories: ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -128,8 +134,8 @@ it's kinda interactive with following commands in three categories: without the need of changing anything - MCD,MSN,MCC will be read from the tag before and applied to the output. - lf: 'load file' - load a (xored) file from the local Filesystem into the 'virtual inTag' - sf: 'save file' - saves the 'virtual inTag' to the local Filesystem (xored with Tag-MCC) + lf: 'load file' - load a (xored) binary file (*.bin) from the local Filesystem into the 'virtual inTag' + sf: 'save file' - saves the 'virtual inTag' to the local Filesystem as eml and bin (xored with Tag-MCC) xf: 'xor file' - saves the 'virtual inTag' to the local Filesystem (xored with choosen MCC - use '00' for plain values) ct: 'copy tag' - copy the 'virtual Tag' to a second 'virtual TAG' - not usefull yet, but inernally needed @@ -242,6 +248,16 @@ function istable(t) return type(t) == 'table' end +--- +-- To have two char string for a byte +local function padString(str) + if (#str == 1) then + return '0'..str + end + + return str +end + --- -- creates a 'deep copy' of a table (a=b only references) function deepCopy(object) @@ -387,15 +403,15 @@ end function bytesToTag(bytes, tag) if istable(tag) == false then return oops("tag is no table in: bytesToTag ("..type(tag)..")") end - tag.MCD =bytes[1]; - tag.MSN0=bytes[2]; - tag.MSN1=bytes[3]; - tag.MSN2=bytes[4]; - tag.MCC =bytes[5]; - tag.DCFl=bytes[6]; - tag.DCFh=bytes[7]; - tag.raw =bytes[8]; - tag.SSC =bytes[9]; + tag.MCD =padString(bytes[1]); + tag.MSN0=padString(bytes[2]); + tag.MSN1=padString(bytes[3]); + tag.MSN2=padString(bytes[4]); + tag.MCC =padString(bytes[5]); + tag.DCFl=padString(bytes[6]); + tag.DCFh=padString(bytes[7]); + tag.raw =padString(bytes[8]); + tag.SSC =padString(bytes[9]); tag.Type=getTokenType(tag.DCFl); tag.OLE=bbit("0x"..tag.DCFl,7,1) tag.WRP=("%d"):format(bbit("0x"..bytes[8],0,4)) @@ -500,42 +516,26 @@ function tagToBytes(tag) return bytes end + +--- --- PM3 I/O --- ---- --- read from pm3 into virtual-tag -function readFromPM3() - local tag, bytes, infile - infile="legic.temp" - -- core.console("hf legic reader") - -- core.console("hf legic esave "..infile) - core.console("hf legic dump o "..infile) - tag=readFile(infile..".bin") - return tag -end - -local function padString(str) - if (#str == 1) then - return '0'..str - end - - return str -end - ---- -- write virtual Tag to real Tag function writeToTag(tag) local bytes - local filename = 'MylegicClone.hex' local taglen = 22 - if(utils.confirm(acred.."\nplace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then + local writeDCF = false + if(utils.confirm(acred.."\nPlace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then return end + if(utils.confirm(acred.."\nShould the decremental field (DCF) be written?: "..acoff) == true) then + writeDCF = true + end -- get used bytes / tag-len if (istable(tag.SEG)) then if (istable(tag.Bck)) then for i=0, #tag.SEG do - taglen = taglen + tag.SEG[i] . len + 5 + taglen = taglen + tag.SEG[i] . len end end local uid_old = tag.MCD..tag.MSN0..tag.MSN1..tag.MSN2 @@ -571,37 +571,32 @@ function writeToTag(tag) bytes[22] = calcMtCrc(bytes) end if (bytes) then - print("write temp-file '"..filename.."'") - print(accyan) - writeFile(bytes, filename..".bin") - print(acoff) + bytes = xorBytes(bytes,tag.MCC) end end + -- write data to file if (taglen > 0) then WriteBytes = input(acyellow.."enter number of bytes to write?"..acoff, taglen) - -- load file into pm3-buffer - if (type(filename) ~= "string") then - filename = input(acyellow.."filename to load to pm3-buffer?"..acoff, "legic.temp") - end - - cmd = 'hf legic eload 2 '..filename - core.console(cmd) -- write pm3-buffer to Tag - for i=0, WriteBytes do - if (i > 6) then - cmd = ("hf legic write o %x d %s "):format(i, padString(bytes[i])) + for i=1, WriteBytes do + if (i > 7) then + cmd = ("hf legic wrbl o %02x d %s "):format(i-1, padString(bytes[i])) print(acgreen..cmd..acoff) core.console(cmd) core.clearCommandBuffer() + elseif (i == 7) then + if (writeDCF) then + -- write DCF in reverse order (requires 'mosci-patch') + cmd = ('hf legic wrbl o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) + print(acgreen..cmd..acoff) + core.console(cmd) + core.clearCommandBuffer() + else + print(acgreen.."skip byte 0x05-0x06 - DCF"..acoff) + end elseif (i == 6) then - -- write DCF in reverse order (requires 'mosci-patch') - cmd = ('hf legic write o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) - print(acgreen..cmd..acoff) - core.console(cmd) - core.clearCommandBuffer() - elseif (i == 5) then print(acgreen.."skip byte 0x05 - will be written next step"..acoff) else print(acgreen.."skip byte 0x00-0x04 - unwritable area"..acoff) @@ -641,12 +636,12 @@ end local function save_BIN(data, filename) local outfile local counter = 1 - local ext = filename:match("^.+(%..+)$") or '' - local fn = filename + local ext = ".bin" + local fn = filename..ext -- Make sure we don't overwrite a file while file_check(fn) do - fn = filename:gsub(ext, tostring(counter)..ext) + fn = filename..ext:gsub(ext, "-"..tostring(counter)..ext) counter = counter + 1 end @@ -664,26 +659,27 @@ end --- -- write bytes to file function writeFile(bytes, filename) - if (filename ~= 'MylegicClone.hex') then - if (file_check(filename)) then - local answer = confirm("\nthe output-file "..filename.." already exists!\nthis will delete the previous content!\ncontinue?") + local emlext = ".eml" + if (filename ~= 'MyLegicClone') then + if (file_check(filename..emlext)) then + local answer = confirm("\nthe output-file "..filename..emlext.." already exists!\nthis will delete the previous content!\ncontinue?") if not answer then return print("user abort") end end end local line local bcnt = 0 - local fho, err = io.open(filename, "w") + local fho, err = io.open(filename..emlext, "w") if err then - return oops("OOps ... failed to open output-file ".. filename) + return oops("OOps ... failed to open output-file ".. filename..emlext) end bytes = xorBytes(bytes, bytes[5]) for i = 1, #bytes do if (bcnt == 0) then - line = bytes[i] + line = padString(bytes[i]) elseif (bcnt <= 7) then - line = line.." "..bytes[i] + line = line.." "..padString(bytes[i]) end if (bcnt == 7) then -- write line to new file @@ -699,7 +695,7 @@ function writeFile(bytes, filename) -- save binary local fn_bin, fn_bin_num = save_BIN(bytes, filename) - print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..acoff) + print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..emlext..acoff) if fn_bin and fn_bin_num then print("\nwrote "..acyellow..fn_bin_num..acoff.." bytes to BINARY file "..acyellow..fn_bin..acoff) @@ -708,6 +704,21 @@ function writeFile(bytes, filename) return true end +--- +-- read from pm3 into virtual-tag +function readFromPM3() + local tag, bytes, infile + --infile="legic.temp" + infile=os.tmpname() + core.console("hf legic dump f "..infile) + tag=readFile(infile..".bin") + os.remove(infile) + os.remove(infile..".bin") + os.remove(infile..".eml") + os.remove(infile..".json") + return tag +end + --- Map related --- --- -- make tagMap @@ -2265,8 +2276,8 @@ function modifyHelp() ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -2352,10 +2363,10 @@ function modifyMode() -- save values of mainTAG to a file (xored with MCC of mainTAG) ["sf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) bytes = tagToBytes(inTAG) --bytes=xorBytes(bytes, inTAG.MCC) - if bytes then + if (bytes) then writeFile(bytes, outfile) end end @@ -2364,7 +2375,7 @@ function modifyMode() -- save values of mainTAG to a file (xored with 'specific' MCC) ["xf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) crc = input("enter new crc: ('00' for a plain dump)", inTAG.MCC) print("obfuscate with: "..crc) bytes=tagToBytes(inTAG) diff --git a/cmdhfmfdes.c b/cmdhfmfdes.c new file mode 100644 index 000000000..89463a255 --- /dev/null +++ b/cmdhfmfdes.c @@ -0,0 +1,1569 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2014 Iceman +// +// 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. +//----------------------------------------------------------------------------- +// High frequency MIFARE Desfire commands +//----------------------------------------------------------------------------- +#include "cmdhfmfdes.h" + +#include +#include + +#include "commonutil.h" // ARRAYLEN +#include "cmdparser.h" // command_t +#include "comms.h" +#include "ui.h" +#include "cmdhw.h" +#include "cmdhf14a.h" +#include "mbedtls/des.h" +#include "crypto/libpcrypto.h" +#include "protocols.h" +#include "mifare.h" // desfire raw command options +#include "cmdtrace.h" +#include "cliparser/cliparser.h" +#include "emv/apduinfo.h" // APDU manipulation / errorcodes +#include "emv/emvcore.h" // APDU logging +#include "util_posix.h" // msleep +#include "mifare/mifare4.h" // MIFARE Authenticate / MAC + +uint8_t key_zero_data[16] = { 0x00 }; +uint8_t key_ones_data[16] = { 0x01 }; +uint8_t key_defa_data[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; +uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; + +#define status(x) ( ((uint16_t)(0x91<<8)) + x ) + +typedef enum { + UNKNOWN = 0, + MF3ICD40, + EV1, + EV2, + EV3, + LIGHT, +} desfire_cardtype_t; + +typedef struct { + uint8_t aid[3]; + uint8_t fid[2]; + uint8_t name[16]; +} dfname_t; + +static int CmdHelp(const char *Cmd); + +/* + uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; + int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); + + if (!res && datalen > 1 && data[0] == 0x09) { + SLmode = 0; + } + +*/ + +int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { + + *result_len = 0; + if (sw) *sw = 0; + + uint16_t isw = 0; + int res = 0; + + if (activate_field) { + DropField(); + msleep(50); + } + + // select? + uint8_t data[APDU_RES_LEN] = {0}; + + // COMPUTE APDU + int datalen = 0; + //if (APDUEncodeS(&apdu, false, IncludeLe ? 0x100 : 0x00, data, &datalen)) { + if (APDUEncodeS(&apdu, false, 0x100, data, &datalen)) { + PrintAndLogEx(ERR, "APDU encoding error."); + return PM3_EAPDU_ENCODEFAIL; + } + + if (GetAPDULogging() || (g_debugMode > 1)) + PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen)); + + res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, result_len); + if (res) { + return res; + } + + if (GetAPDULogging() || (g_debugMode > 1)) + PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(result, *result_len)); + + if (*result_len < 2) { + return PM3_SUCCESS; + } + + *result_len -= 2; + isw = (result[*result_len] << 8) + result[*result_len + 1]; + if (sw) + *sw = isw; + + if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_SIGNATURE) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { + if (GetAPDULogging()) { + if (isw >> 8 == 0x61) { + PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); + } else { + PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [0x%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); + return PM3_EAPDU_FAIL; + } + } + return PM3_EAPDU_FAIL; + } + return PM3_SUCCESS; +} + +static char* getstatus(uint16_t * sw) +{ + if (sw==NULL) return "--> sw argument error. This should never happen !"; + if (((*sw>>8)&0xFF)==0x91){ + switch (*sw&0xFF){ + case MFDES_E_OUT_OF_EEPROM: + return "Out of Eeprom, insufficient NV-Memory to complete command"; + case MFDES_E_ILLEGAL_COMMAND_CODE: + return "Command code not supported"; + + case MFDES_E_INTEGRITY_ERROR: + return "CRC or MAC does not match data / Padding bytes invalid"; + + case MFDES_E_NO_SUCH_KEY: + return "Invalid key number specified"; + + case MFDES_E_LENGTH: + return "Length of command string invalid"; + + case MFDES_E_PERMISSION_DENIED: + return "Current configuration/status does not allow the requested command"; + + case MFDES_E_PARAMETER_ERROR: + return "Value of the parameter(s) invalid"; + + case MFDES_E_APPLICATION_NOT_FOUND: + return "Requested AID not present on PICC"; + + case MFDES_E_APPL_INTEGRITY: + return "Application integrity error, application will be disabled"; + + case MFDES_E_AUTHENTIFICATION_ERROR: + return "Current authentication status does not allow the requested command"; + + case MFDES_E_BOUNDARY: + return "Attempted to read/write data from/to beyong the file's/record's limit"; + + case MFDES_E_PICC_INTEGRITY: + return "PICC integrity error, PICC will be disabled"; + + case MFDES_E_COMMAND_ABORTED: + return "Previous command was not fully completed / Not all Frames were requested or provided by the PCD"; + + case MFDES_E_PICC_DISABLED: + return "PICC was disabled by an unrecoverable error"; + + case MFDES_E_COUNT: + return "Application count is limited to 28, not addition CreateApplication possible"; + + case MFDES_E_DUPLICATE: + return "Duplicate entry: File/Application does already exist"; + + case MFDES_E_EEPROM: + return "Eeprom error due to loss of power, internal backup/rollback mechanism activated"; + + case MFDES_E_FILE_NOT_FOUND: + return "Specified file number does not exist"; + + case MFDES_E_FILE_INTEGRITY: + return "File integrity error, file will be disabled"; + + default: + return "Unknown error"; + } + } + return "Unknown error"; +} + +static char* GetErrorString(int res,uint16_t* sw) +{ + switch(res){ + case PM3_EAPDU_FAIL: + return getstatus(sw); + case PM3_EUNDEF: + return "Undefined error"; + case PM3_EINVARG: + return "Invalid argument(s)"; + case PM3_EDEVNOTSUPP: + return "Operation not supported by device"; + case PM3_ETIMEOUT: + return "Operation timed out"; + case PM3_EOPABORTED: + return "Operation aborted (by user)"; + case PM3_ENOTIMPL: + return "Not (yet) implemented"; + case PM3_ERFTRANS: + return "Error while RF transmission"; + case PM3_EIO: + return "Input / output error"; + case PM3_EOVFLOW: + return "Buffer overflow"; + case PM3_ESOFT: + return "Software error"; + case PM3_EFLASH: + return "Flash error"; + case PM3_EMALLOC: + return "Memory allocation error"; + case PM3_EFILE: + return "File error"; + case PM3_ENOTTY: + return "Generic TTY error"; + case PM3_EINIT: + return "Initialization error"; + case PM3_EWRONGANSVER: + return "Expected a different answer error"; + case PM3_EOUTOFBOUND: + return "Memory out-of-bounds error"; + case PM3_ECARDEXCHANGE: + return "Exchange with card error"; + case PM3_EAPDU_ENCODEFAIL: + return "Failed to create APDU"; + case PM3_ENODATA: + return "No data"; + case PM3_EFATAL: + return "Fatal error"; + default: + break; + } + return ""; +} + + +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize,bool readalldata) { + if (g_debugMode>1) + { + if (apdu==NULL) PrintAndLogEx(ERR, "APDU=NULL"); + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (sw==NULL) PrintAndLogEx(ERR, "SW=NULL"); + if (recv_len==NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); + } + if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_EINVARG; + + *sw = 0; + uint8_t data[255 * 5] = {0x00}; + int resplen = 0; + int pos = 0; + int i = 1; + int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); + if (res != PM3_SUCCESS) { + if (g_debugMode>1) GetErrorString(res,sw); + return res; + } + if (dest != NULL) { + memcpy(dest, data, resplen); + } + + pos += resplen; + if (!readalldata) + { + if (*sw==status(MFDES_ADDITIONAL_FRAME)) { + apdu->INS = MFDES_ABORT_TRANSACTION; + apdu->Lc = 0; + apdu->P1 = 0; + apdu->P2 = 0; + res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); + return PM3_SUCCESS; + } + return res; + } + while (*sw == status(MFDES_ADDITIONAL_FRAME)) { + apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF + apdu->Lc=0; + apdu->P1=0; + apdu->P2=0; + + res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); + if (res != PM3_SUCCESS){ + if (g_debugMode>1) GetErrorString(res,sw); + return res; + } + if (dest != NULL) { + if (splitbysize) { + memcpy(&dest[i * splitbysize], data, resplen); + i += 1; + } else { + memcpy(&dest[pos], data, resplen); + } + } + pos += resplen; + if (*sw!=status(MFDES_ADDITIONAL_FRAME)) break; + } + if (splitbysize) *recv_len = i; + else { + *recv_len = pos; + } + return PM3_SUCCESS; + +} + +static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { + + if (major == 0x00) + return MF3ICD40; + else if (major == 0x01 && minor == 0x00) + return EV1; + else if (major == 0x12 && minor == 0x00) + return EV2; +// else if (major == 0x13 && minor == 0x00) +// return EV3; + else if (major == 0x30 && minor == 0x00) + return LIGHT; + else + return UNKNOWN; +} + +//none, verified +static int test_desfire_authenticate() { + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); +} + +// none, verified +static int test_desfire_authenticate_iso() { + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); +} + +//none, verified +static int test_desfire_authenticate_aes() { + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); +} + +// --- FREE MEM, verified +static int desfire_print_freemem(uint32_t free_mem) { + PrintAndLogEx(SUCCESS, " Available free memory on card : " _GREEN_("%d bytes"), free_mem); + return PM3_SUCCESS; +} + +// init / disconnect, verified +static int get_desfire_freemem(uint32_t *free_mem) { + if (free_mem==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E + int recv_len = 0; + uint16_t sw = 0; + uint8_t fmem[4] = {0}; + + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0,true); + if (res == PM3_SUCCESS) { + *free_mem = le24toh(fmem); + return res; + } + *free_mem = 0; + return res; +} + + +// --- GET SIGNATURE, verified +static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { + if (g_debugMode>1) + { + if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); + if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + } + if (uid==NULL || signature==NULL) return PM3_EINVARG; + // DESFire Ev3 - wanted + // ref: MIFARE Desfire Originality Signature Validation + +#define PUBLIC_DESFIRE_ECDA_KEYLEN 57 + const ecdsa_publickey_t nxp_desfire_public_keys[] = { + {"NTAG424DNA, DESFire EV2", "048A9B380AF2EE1B98DC417FECC263F8449C7625CECE82D9B916C992DA209D68422B81EC20B65A66B5102A61596AF3379200599316A00A1410"}, + {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, + {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, + {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, + {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, + {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} + }; + + uint8_t i; + int res; + bool is_valid = false; + + for (i = 0; i < ARRAYLEN(nxp_desfire_public_keys); i++) { + + int dl = 0; + uint8_t key[PUBLIC_DESFIRE_ECDA_KEYLEN]; + param_gethex_to_eol(nxp_desfire_public_keys[i].value, 0, key, PUBLIC_DESFIRE_ECDA_KEYLEN, &dl); + + res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP224R1, key, uid, 7, signature, signature_len, false); + is_valid = (res == 0); + if (is_valid) + break; + } + if (is_valid == false) { + PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); + return PM3_ESOFT; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); + PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); + PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); + PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 32); + PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 48); + PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); + PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); + PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); + return PM3_SUCCESS; +} + +// init / disconnect, verified +static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { + if (g_debugMode>1) + { + if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); + } + if (signature==NULL || signature_len==NULL) return PM3_EINVARG; + uint8_t c = 0x00; + sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0,true); + if (res == PM3_SUCCESS) { + if (recv_len != 56) { + *signature_len = 0; + DropField(); + return PM3_ESOFT; + } else { + *signature_len = recv_len; + + } + DropField(); + return PM3_SUCCESS; + } + DropField(); + return res; +} + + +// --- KEY SETTING +static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { + + PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); + PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(SUCCESS, " Changekey Access rights"); + + // Access rights. + uint8_t rights = (key_settings >> 4 & 0x0F); + switch (rights) { + case 0x0: + PrintAndLogEx(SUCCESS, " -- AMK authentication is necessary to change any key (default)"); + break; + case 0xE: + PrintAndLogEx(SUCCESS, " -- Authentication with the key to be changed (same KeyNo) is necessary to change a key"); + break; + case 0xF: + PrintAndLogEx(SUCCESS, " -- All keys (except AMK,see Bit0) within this application are frozen"); + break; + default: + PrintAndLogEx(SUCCESS, " -- Authentication with the specified key is necessary to change any key.\nA change key and a PICC master key (CMK) can only be changed after authentication with the master key.\nFor keys other then the master or change key, an authentication with the same key is needed."); + break; + } + + PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_settings & (1 << 3)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x04] AMK required for create/delete : %s", (key_settings & (1 << 2)) ? "NO" : "YES"); + PrintAndLogEx(SUCCESS, " [0x02] Directory list access with AMK : %s", (key_settings & (1 << 1)) ? "NO" : "YES"); + PrintAndLogEx(SUCCESS, " [0x01] AMK is changeable : %s", (key_settings & (1 << 0)) ? _GREEN_("YES") : "NO"); + return PM3_SUCCESS; +} + +// none, verified +static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { + if (g_debugMode>1) + { + if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); + if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); + } + if (key_settings==NULL || num_keys==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 + int recv_len = 0; + uint16_t sw = 0; + uint8_t data[2] = {0}; + int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0,true); + if (res != PM3_SUCCESS) return res; + + *key_settings = data[0]; + *num_keys = data[1]; + return PM3_SUCCESS; +} + +// --- KEY VERSION +static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { + PrintAndLogEx(SUCCESS, " Key [%u] Version : %d (0x%02x)", key_idx, key_version, key_version); + return PM3_SUCCESS; +} + +// none, verified +static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { + if (g_debugMode>1) + { + if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); + } + if (num_versions==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0,true); + return res; +} + + +// init / disconnect, verified +static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + if (g_debugMode>1) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); + } + if (dest==NULL || app_ids_len==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0,true); + if (res != PM3_SUCCESS) return res; + *app_ids_len = (uint8_t)recv_len & 0xFF; + return res; +} + +// init, verified +static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + if (g_debugMode>1) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); + } + if (dest==NULL || dfname_count==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t),true); + if (res != PM3_SUCCESS) return res; + *dfname_count = recv_len; + return res; +} + + +// init, verified +static int get_desfire_select_application(uint8_t *aid) { + if (g_debugMode>1) + { + if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); + } + if (aid==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a + int recv_len = 0; + uint16_t sw = 0; + int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t),true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res,&sw)); + DropField(); + return res; + } + return PM3_SUCCESS; +} + +// none, verified +static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { + if (g_debugMode>1) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); + } + if (dest==NULL || file_ids_len==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f + int recv_len = 0; + uint16_t sw = 0; + *file_ids_len = 0; + int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0,true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res,&sw)); + DropField(); + return res; + } + *file_ids_len = recv_len; + return res; +} + +// none, verified +static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { + if (g_debugMode>1) + { + if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); + } + if (dest==NULL || destlen==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 + uint16_t sw = 0; + int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0,true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res,&sw)); + DropField(); + return res; + } + return res; +} + +typedef struct { + uint8_t aid[3]; + uint8_t keysetting1; + uint8_t keysetting2; + uint8_t fid[2]; + uint8_t name[16]; +} aidhdr_t; + +static int get_desfire_createapp(aidhdr_t* aidhdr) { + if (aidhdr==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA + uint16_t sw = 0; + int recvlen=0; + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res,&sw)); + DropField(); + return res; + } + return res; +} + +static int get_desfire_deleteapp(uint8_t* aid) { + if (aid==NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA + uint16_t sw = 0; + int recvlen=0; + int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res,&sw)); + DropField(); + return res; + } + return res; +} + +static int CmdHF14ADesCreateApp(const char *Cmd) { + clearCommandBuffer(); + + CLIParserInit("hf mfdes createaid", + "Create Application ID", + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to create"), + arg_strx0("fF", "fid", "", "File ID"), + arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), + arg_strx0("lL", "keysetting2", "", "Key Setting 2"), + arg_str0("nN", "name", "", "App ISO-4 Name"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + /* KeySetting 1 (AMK Setting): + 0: Allow change master key + 1: Free Directory list access without master key + 0: AMK auth needed for GetFileSettings and GetKeySettings + 1: No AMK auth needed for GetFileIDs, GetISOFileIDs, GetFileSettings, GetKeySettings + 2: Free create/delete without master key + 0: CreateFile/DeleteFile only with AMK auth + 1: CreateFile/DeleteFile always + 3: Configuration changable + 0: Configuration frozen + 1: Configuration changable if authenticated with AMK (default) + 4-7: ChangeKey Access Rights + 0: Application master key needed (default) + 0x1..0xD: Auth with specific key needed to change any key + 0xE: Auth with the key to be changed (same KeyNo) is necessary to change a key + 0xF: All Keys within this application are frozen + + */ + /* KeySetting 2: + 0..3: Number of keys stored within the application (max. 14 keys + 4: RFU + 5: Use of 2 byte ISO FID, 0: No, 1: Yes + 6..7: Crypto Method 00: DES/3DES, 01: 3K3DES, 10: AES + Example: + 2E = FID, DES, 14 keys + 6E = FID, 3K3DES, 14 keys + AE = FID, AES, 14 keys + */ + int aidlength = 3; + int fidlength = 2; + uint8_t aid[3] = {0}; + uint8_t fid[2] = {0}; + uint8_t name[16] = {0}; + uint8_t keysetting1=0; + uint8_t keysetting2=0; + int keylen1=1; + int keylen2=1; + int namelen=16; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIGetHexWithReturn(2, fid, &fidlength); + CLIGetHexWithReturn(3, &keysetting1, &keylen1); + CLIGetHexWithReturn(4, &keysetting2, &keylen2); + CLIGetStrWithReturn(5, name, &namelen); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (fidlength < 2) { + PrintAndLogEx(ERR, "FID must have 2 bytes length."); + return PM3_EINVARG; + } + + if (keylen1 < 1) { + PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); + return PM3_EINVARG; + } + + if (keylen1 < 1) { + PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); + return PM3_EINVARG; + } + + if (namelen > 16) { + PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); + return PM3_EINVARG; + } + + //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 + /*char name[]="Test"; + uint8_t aid[]={0x12,0x34,0x56}; + uint8_t fid[]={0x11,0x22}; + uint8_t keysetting1=0xEE; + uint8_t keysetting2=0xEE;*/ + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Creating root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + aidhdr_t aidhdr; + memcpy(aidhdr.aid,aid,sizeof(aid)); + aidhdr.keysetting1=keysetting1; + aidhdr.keysetting2=keysetting2; + memcpy(aidhdr.fid,fid,sizeof(fid)); + memcpy(aidhdr.name,name,sizeof(name)); + + uint8_t rootaid[3]={0x00,0x00,0x00}; + int res=get_desfire_select_application(rootaid); + if (res!=PM3_SUCCESS) return res; + + return get_desfire_createapp(&aidhdr); +} + +static int CmdHF14ADesDeleteApp(const char *Cmd) { + clearCommandBuffer(); + + CLIParserInit("hf mfdes deleteaid", + "Delete Application ID", + "Usage:\n\t-a aid (3 bytes)\n\n" + "Example:\n\thf mfdes deleteaid -a 123456\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to delete"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Deleting root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + uint8_t rootaid[3]={0x00,0x00,0x00}; + int res=get_desfire_select_application(rootaid); + if (res!=PM3_SUCCESS) return res; + return get_desfire_deleteapp(aid); +} + + +static int CmdHF14ADesFormatPICC(const char *Cmd) { + (void) Cmd; // Cmd is not used so far + CLIParserInit("hf mfdes formatpicc", + "Formats MIFARE DESFire PICC to factory state", + "Usage:\n\t-k PICC key (8 bytes)\n\n" + "Example:\n\thf mfdes formatpicc -k 0000000000000000\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + + uint8_t key[8] = {0}; + int keylen = 8; + CLIGetHexWithReturn(1, key, &keylen); + CLIParserFree(); + + if ((keylen < 8) || (keylen > 8)) { + PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + clearCommandBuffer(); + DropField(); + uint8_t aid[3]={0}; + int res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) + memcpy(data + 1, key, keylen); + SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + uint8_t isOK = resp.oldarg[0] & 0xff; + if (isOK) { + uint8_t rdata[] = {0xFC}; // 0xFC + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client reset command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + if (resp.oldarg[0]&0xFF){ + PrintAndLogEx(INFO, "Card successfully reset"); + return PM3_SUCCESS; + } + } else { + PrintAndLogEx(WARNING, _RED_("Auth command failed.")); + } + + return PM3_SUCCESS; +} + + +static int CmdHF14ADesInfo(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + + SendCommandNG(CMD_HF_DESFIRE_INFO, NULL, 0); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_HF_DESFIRE_INFO, &resp, 1500)) { + PrintAndLogEx(WARNING, "Command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + struct p { + uint8_t isOK; + uint8_t uid[7]; + uint8_t versionHW[7]; + uint8_t versionSW[7]; + uint8_t details[14]; + } PACKED; + + struct p *package = (struct p *) resp.data.asBytes; + + if (resp.status != PM3_SUCCESS) { + + switch (package->isOK) { + case 1: + PrintAndLogEx(WARNING, "Can't select card"); + break; + case 2: + PrintAndLogEx(WARNING, "Card is most likely not Desfire. Its UID has wrong size"); + break; + case 3: + default: + PrintAndLogEx(WARNING, _RED_("Command unsuccessful")); + break; + } + return PM3_ESOFT; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(package->uid, sizeof(package->uid))); + PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(package->details + 7, 5)); + PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), package->details[12], package->details[13]); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionHW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionHW[2]); + PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionSW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionSW[2]); + PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Card capabilities")); + uint8_t major = package->versionSW[3]; + uint8_t minor = package->versionSW[4]; + if (major == 0 && minor == 4) + PrintAndLogEx(INFO, "\t0.4 - DESFire MF3ICD40, No support for APDU (only native commands)"); + if (major == 0 && minor == 5) + PrintAndLogEx(INFO, "\t0.5 - DESFire MF3ICD40, Support for wrapping commands inside ISO 7816 style APDUs"); + if (major == 0 && minor == 6) + PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); + if (major == 1 && minor == 3) + PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); + if (major == 1 && minor == 4) + PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); + if (major == 2 && minor == 0) + PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); +// if (major == 3 && minor == 0) +// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); + + if (major == 0 && minor == 2) + PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); + + // Signature originality check + uint8_t signature[56] = {0}; + size_t signature_len = 0; + desfire_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); + + if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) + desfire_print_signature(package->uid, signature, signature_len, cardtype); + else{ + PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature. Unknown public key ?")); + } + + // Master Key settings + uint8_t master_aid[3] = {0x00, 0x00, 0x00}; + getKeySettings(master_aid); + + // Free memory on card + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); + uint32_t free_mem = 0; + if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { + desfire_print_freemem(free_mem); + } else { + PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); + } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + + /* + Card Master key (CMK) 0x00 AID = 00 00 00 (card level) + Application Master Key (AMK) 0x00 AID != 00 00 00 + Application keys (APK) 0x01-0x0D + Application free 0x0E + Application never 0x0F + + ACCESS RIGHTS: + keys 0,1,2,3 C + keys 4,5,6,7 RW + keys 8,9,10,11 W + keys 12,13,14,15 R + + */ + + DropField(); + return PM3_SUCCESS; +} + +/* + The 7 MSBits (= n) code the storage size itself based on 2^n, + the LSBit is set to '0' if the size is exactly 2^n + and set to '1' if the storage size is between 2^n and 2^(n+1). + For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. +*/ +char *getCardSizeStr(uint8_t fsize) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + uint16_t usize = 1 << ((fsize >> 1) + 1); + uint16_t lsize = 1 << (fsize >> 1); + + // is LSB set? + if (fsize & 1) + sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); + return buf; +} + +char *getProtocolStr(uint8_t id) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (id == 0x05) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + return buf; +} + +char *getVersionStr(uint8_t major, uint8_t minor) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (major == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); + else if (major == 0x01 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); + else if (major == 0x12 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); +// else if (major == 0x13 && minor == 0x00) +// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); + else if (major == 0x30 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); + else + sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); + return buf; +} + +int getKeySettings(uint8_t *aid) { + if (aid==NULL) return PM3_EINVARG; + int res=0; + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + + // CARD MASTER KEY + //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + + // KEY Settings - AMK + uint8_t num_keys = 0; + uint8_t key_setting = 0; + res=get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { + // number of Master keys (0x01) + PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); + + PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_setting & (1 << 3)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x04] CMK required for create/delete : %s", (key_setting & (1 << 2)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x02] Directory list access with CMK : %s", (key_setting & (1 << 1)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x01] CMK is changeable : %s", (key_setting & (1 << 0)) ? _GREEN_("YES") : "NO"); + } else { + PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); + } + + const char *str = " Operation of PICC master key : " _YELLOW_("%s"); + + // 2 MSB denotes + switch (num_keys >> 6) { + case 0: + PrintAndLogEx(SUCCESS, str, "(3)DES"); + break; + case 1: + PrintAndLogEx(SUCCESS, str, "3K3DES"); + break; + case 2: + PrintAndLogEx(SUCCESS, str, "AES"); + break; + default: + break; + } + + uint8_t cmk_num_versions = 0; + if (get_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, " PICC Master key Version : " _YELLOW_("%d (0x%02x)"), cmk_num_versions, cmk_num_versions); + PrintAndLogEx(INFO, " ----------------------------------------------------------"); + } + + // Authentication tests + int res = test_desfire_authenticate(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + res = test_desfire_authenticate_iso(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + res = test_desfire_authenticate_aes(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + + } else { + + // AID - APPLICATION MASTER KEYS + //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + + // KEY Settings - AMK + uint8_t num_keys = 0; + uint8_t key_setting = 0; + res=get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { + desfire_print_keysetting(key_setting, num_keys); + } else { + PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); + } + + // KEY VERSION - AMK + uint8_t num_version = 0; + if (get_desfire_keyversion(0, &num_version) == PM3_SUCCESS) { + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(INFO, " Application keys"); + desfire_print_keyversion(0, num_version); + } else { + PrintAndLogEx(WARNING, " Can't read AID master key version. Trying all keys"); + } + + // From 0x01 to numOfKeys. We already got 0x00. (AMK) + num_keys &= 0x3F; + if (num_keys > 1) { + for (uint8_t i = 0x01; i < num_keys; ++i) { + if (get_desfire_keyversion(i, &num_version) == PM3_SUCCESS) { + desfire_print_keyversion(i, num_version); + } else { + PrintAndLogEx(WARNING, " Can't read key %d (0x%02x) version", i, i); + } + } + } + } + + DropField(); + return PM3_SUCCESS; +} + +static void DecodeFileType(uint8_t filetype){ + switch (filetype) + { + case 0x00: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Standard Data File", filetype); + break; + case 0x01: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Backup Data File", filetype); + break; + case 0x02: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Value Files with Backup", filetype); + break; + case 0x03: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Linear Record Files with Backup", filetype); + break; + case 0x04: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Cyclic Record Files with Backup", filetype); + break; + default: + PrintAndLogEx(INFO, " File Type: 0x%02X", filetype); + break; + } +} + +static void DecodeComSet(uint8_t comset){ + switch (comset) + { + case 0x00: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain", comset); + break; + case 0x01: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain + MAC", comset); + break; + case 0x03: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Enciphered", comset); + break; + default: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X", comset); + break; + } +} + +static char* DecodeAccessValue(uint8_t value) +{ + char* car=(char*)malloc(255); + memset(car,0x0,255); + switch(value){ + case 0xE: + strcat(car, "(Free Access)"); + break; + case 0xF: + strcat(car, "(Denied Access)"); + break; + default: + sprintf(car,"(Access Key: %d)",value); + break; + } + return car; +} + +static void DecodeAccessRights(uint16_t accrights){ + int change_access_rights=accrights&0xF; + int read_write_access=(accrights>>4)&0xF; + int write_access=(accrights>>8)&0xF; + int read_access=(accrights>>12)&0xF; + char* car=DecodeAccessValue(change_access_rights); + char* rwa=DecodeAccessValue(read_write_access); + char* wa=DecodeAccessValue(write_access); + char* ra=DecodeAccessValue(read_access); + PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights,car,rwa,wa,ra); + free(car); + free(rwa); + free(wa); + free(ra); +} + +static int DecodeFileSettings(uint8_t* filesettings, int fileset_len, int maclen){ + uint8_t filetype=filesettings[0]; + uint8_t comset=filesettings[1]; + + uint16_t accrights=(filesettings[4]<<8)+filesettings[3]; + if (fileset_len==1+1+2+3+maclen) + { + int filesize=(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Filesize: %d", filesize); + return PM3_SUCCESS; + } else if (fileset_len==1+1+2+4+4+4+1+maclen) { + int lowerlimit=(filesettings[8]<<24)+(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; + int upperlimit=(filesettings[12]<<24)+(filesettings[11]<<16)+(filesettings[10]<<8)+filesettings[9]; + int limitcredvalue=(filesettings[16]<<24)+(filesettings[15]<<16)+(filesettings[14]<<8)+filesettings[13]; + uint8_t limited_credit_enabled=filesettings[17]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Lower limit: %d - Upper limit: %d - limited credit value: %d - limited credit enabled: %d", lowerlimit, upperlimit, limitcredvalue, limited_credit_enabled); + return PM3_SUCCESS; + } + return PM3_ESOFT; +} + +static int CmdHF14ADesEnumApplications(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + +// uint8_t isOK = 0x00; + uint8_t aid[3] = {0}; + uint8_t app_ids[78] = {0}; + uint8_t app_ids_len = 0; + + uint8_t file_ids[33] = {0}; + uint8_t file_ids_len = 0; + + dfname_t dfnames[255]; + uint8_t dfname_count = 0; + + int res=0; + + if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Can't get list of applications on tag"); + DropField(); + return PM3_ESOFT; + } + + if (get_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_("Can't get DF Names")); + DropField(); + return PM3_ESOFT; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "-- Mifare DESFire Enumerate applications --------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "application%c", app_ids_len / 3, (app_ids_len == 3) ? ' ' : 's'); + + for (int i = 0; i < app_ids_len; i += 3) { + + aid[0] = app_ids[i]; + aid[1] = app_ids[i + 1]; + aid[2] = app_ids[i + 2]; + + PrintAndLogEx(NORMAL, ""); + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + // CARD MASTER KEY + PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + } else { + PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + } + + PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X %02X %02X"), aid[0], aid[1], aid[2]); + for (int m = 0; m < dfname_count; m++) { + if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { + PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X %02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[0], dfnames[m].fid[1], dfnames[m].name); + } + } + + res=getKeySettings(aid); + if (res!=PM3_SUCCESS) return res; + + res=get_desfire_select_application(aid); + + + // Get File IDs + if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); + for (int j = 0; j < file_ids_len; ++j) { + PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); + + uint8_t filesettings[20] = {0}; + int fileset_len = 0; + int res = get_desfire_filesettings(j, filesettings, &fileset_len); + int maclen=0; // To be implemented + if (res == PM3_SUCCESS) { + if (DecodeFileSettings(filesettings,fileset_len,maclen)!=PM3_SUCCESS){ + PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + } + } + } + } + + /* + // Get ISO File IDs + { + uint8_t data[] = {GET_ISOFILE_IDS, 0x00, 0x00, 0x00}; // 0x61 + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, DISCONNECT, sizeof(data), 0, data, sizeof(data)); + } + + if (!WaitForResponseTimeout(CMD_ACK, &respFiles, 1500)) { + PrintAndLogEx(WARNING, _RED_(" Timed-out")); + continue; + } else { + isOK = respFiles.data.asBytes[2] & 0xff; + if (!isOK) { + PrintAndLogEx(WARNING, _RED_(" Can't get ISO file ids")); + } else { + int respfileLen = resp.oldarg[1] - 3 - 2; + for (int j = 0; j < respfileLen; ++j) { + PrintAndLogEx(SUCCESS, " ISO Fileid %d :", resp.data.asBytes[j + 3]); + } + } + } + */ + } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + DropField(); + return PM3_SUCCESS; +} + +// MIAFRE DESFire Authentication +// +#define BUFSIZE 256 +static int CmdHF14ADesAuth(const char *Cmd) { + int res=0; + DropField(); + clearCommandBuffer(); + // NR DESC KEYLENGHT + // ------------------------ + // 1 = DES 8 + // 2 = 3DES 16 + // 3 = 3K 3DES 24 + // 4 = AES 16 + //SetAPDULogging(true); + uint8_t keylength = 8; + + CLIParserInit("hf mfdes auth", + "Authenticates Mifare DESFire using Key", + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes auth -m 3 -t 4 -a 018380 -n 0 -k 404142434445464748494a4b4c4d4e4f\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), + arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), + arg_strx0("aA", "aid", "", "AID used for authentification"), + arg_int0("nN", "keyno", "Key number used for authentification", NULL), + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + + uint8_t cmdAuthMode = arg_get_int_def(1, 0); + uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); + + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(3, aid, &aidlength); + + uint8_t cmdKeyNo = arg_get_int_def(4, 0); + + uint8_t key[24] = {0}; + int keylen = 0; + CLIGetHexWithReturn(5, key, &keylen); + CLIParserFree(); + + if ((keylen < 8) || (keylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + // AID + if (aidlength != 3) { + PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + switch (cmdAuthMode) { + case 1: + if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); + return PM3_EINVARG; + } + break; + case 2: + if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); + return PM3_EINVARG; + } + break; + case 3: + if (cmdAuthAlgo != 4) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); + return PM3_EINVARG; + } + break; + default: + PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + switch (cmdAuthAlgo) { + case 2: + keylength = 16; + PrintAndLogEx(NORMAL, "3DES selected"); + break; + case 3: + keylength = 24; + PrintAndLogEx(NORMAL, "3 key 3DES selected"); + break; + case 4: + keylength = 16; + PrintAndLogEx(NORMAL, "AES selected"); + break; + default: + cmdAuthAlgo = 1; + keylength = 8; + PrintAndLogEx(NORMAL, "DES selected"); + break; + } + + // KEY + if (keylen != keylength) { + PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + + + res=get_desfire_select_application(aid); + if (res!=PM3_SUCCESS) return res; + + if (memcmp(aid,"\x00\x00\x00",3)!=0){ + uint8_t file_ids[33] = {0}; + uint8_t file_ids_len = 0; + res = get_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; + } + + // algo, keylength, + uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) + memcpy(data + 1, key, keylength); + SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + uint8_t isOK = resp.oldarg[0] & 0xff; + if (isOK) { + uint8_t *session_key = resp.data.asBytes; + + PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); + PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + //PrintAndLogEx(NORMAL, " Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); + } else { + PrintAndLogEx(WARNING, _RED_("Client command failed.")); + } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + return PM3_SUCCESS; +} + +static int CmdHF14ADesList(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + return CmdTraceList("des"); +} + +static command_t CommandTable[] = { + {"help", CmdHelp, AlwaysAvailable, "This help"}, + {"info", CmdHF14ADesInfo, IfPm3Iso14443a, "Tag information"}, + {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, + {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, + {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, + {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, + {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, + {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, +// {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, +// {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelp(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + CmdsHelp(CommandTable); + return PM3_SUCCESS; +} + +int CmdHFMFDes(const char *Cmd) { + // flush + clearCommandBuffer(); + //g_debugMode=2; + return CmdsParse(CommandTable, Cmd); +} diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index e727180bf..3fba71e1c 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -18,7 +18,7 @@ Always use the latest repository commits from *master* branch. There are always * [File not found](#file-not-found) * [Pixmap / pixbuf warnings](#pixmap--pixbuf-warnings) * [Usb cable](#usb-cable) - * [WSL 2 explorer.exe . doesnt work](WSL-2) + * [WSL 2 explorer.exe . doesnt work](#WSL-2) ## `pm3` or `pm3-flash*` doesn't see my Proxmark From d88db10aafbc5af55857339ad8bd30089b720f2e Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 01:19:16 +0200 Subject: [PATCH 24/66] Make style --- cmdhfmfdes.c | 1569 -------------------------------------------------- 1 file changed, 1569 deletions(-) delete mode 100644 cmdhfmfdes.c diff --git a/cmdhfmfdes.c b/cmdhfmfdes.c deleted file mode 100644 index 89463a255..000000000 --- a/cmdhfmfdes.c +++ /dev/null @@ -1,1569 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (C) 2014 Iceman -// -// 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. -//----------------------------------------------------------------------------- -// High frequency MIFARE Desfire commands -//----------------------------------------------------------------------------- -#include "cmdhfmfdes.h" - -#include -#include - -#include "commonutil.h" // ARRAYLEN -#include "cmdparser.h" // command_t -#include "comms.h" -#include "ui.h" -#include "cmdhw.h" -#include "cmdhf14a.h" -#include "mbedtls/des.h" -#include "crypto/libpcrypto.h" -#include "protocols.h" -#include "mifare.h" // desfire raw command options -#include "cmdtrace.h" -#include "cliparser/cliparser.h" -#include "emv/apduinfo.h" // APDU manipulation / errorcodes -#include "emv/emvcore.h" // APDU logging -#include "util_posix.h" // msleep -#include "mifare/mifare4.h" // MIFARE Authenticate / MAC - -uint8_t key_zero_data[16] = { 0x00 }; -uint8_t key_ones_data[16] = { 0x01 }; -uint8_t key_defa_data[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; -uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; - -#define status(x) ( ((uint16_t)(0x91<<8)) + x ) - -typedef enum { - UNKNOWN = 0, - MF3ICD40, - EV1, - EV2, - EV3, - LIGHT, -} desfire_cardtype_t; - -typedef struct { - uint8_t aid[3]; - uint8_t fid[2]; - uint8_t name[16]; -} dfname_t; - -static int CmdHelp(const char *Cmd); - -/* - uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; - int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); - - if (!res && datalen > 1 && data[0] == 0x09) { - SLmode = 0; - } - -*/ - -int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { - - *result_len = 0; - if (sw) *sw = 0; - - uint16_t isw = 0; - int res = 0; - - if (activate_field) { - DropField(); - msleep(50); - } - - // select? - uint8_t data[APDU_RES_LEN] = {0}; - - // COMPUTE APDU - int datalen = 0; - //if (APDUEncodeS(&apdu, false, IncludeLe ? 0x100 : 0x00, data, &datalen)) { - if (APDUEncodeS(&apdu, false, 0x100, data, &datalen)) { - PrintAndLogEx(ERR, "APDU encoding error."); - return PM3_EAPDU_ENCODEFAIL; - } - - if (GetAPDULogging() || (g_debugMode > 1)) - PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen)); - - res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, result_len); - if (res) { - return res; - } - - if (GetAPDULogging() || (g_debugMode > 1)) - PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(result, *result_len)); - - if (*result_len < 2) { - return PM3_SUCCESS; - } - - *result_len -= 2; - isw = (result[*result_len] << 8) + result[*result_len + 1]; - if (sw) - *sw = isw; - - if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_SIGNATURE) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { - if (GetAPDULogging()) { - if (isw >> 8 == 0x61) { - PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); - } else { - PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [0x%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); - return PM3_EAPDU_FAIL; - } - } - return PM3_EAPDU_FAIL; - } - return PM3_SUCCESS; -} - -static char* getstatus(uint16_t * sw) -{ - if (sw==NULL) return "--> sw argument error. This should never happen !"; - if (((*sw>>8)&0xFF)==0x91){ - switch (*sw&0xFF){ - case MFDES_E_OUT_OF_EEPROM: - return "Out of Eeprom, insufficient NV-Memory to complete command"; - case MFDES_E_ILLEGAL_COMMAND_CODE: - return "Command code not supported"; - - case MFDES_E_INTEGRITY_ERROR: - return "CRC or MAC does not match data / Padding bytes invalid"; - - case MFDES_E_NO_SUCH_KEY: - return "Invalid key number specified"; - - case MFDES_E_LENGTH: - return "Length of command string invalid"; - - case MFDES_E_PERMISSION_DENIED: - return "Current configuration/status does not allow the requested command"; - - case MFDES_E_PARAMETER_ERROR: - return "Value of the parameter(s) invalid"; - - case MFDES_E_APPLICATION_NOT_FOUND: - return "Requested AID not present on PICC"; - - case MFDES_E_APPL_INTEGRITY: - return "Application integrity error, application will be disabled"; - - case MFDES_E_AUTHENTIFICATION_ERROR: - return "Current authentication status does not allow the requested command"; - - case MFDES_E_BOUNDARY: - return "Attempted to read/write data from/to beyong the file's/record's limit"; - - case MFDES_E_PICC_INTEGRITY: - return "PICC integrity error, PICC will be disabled"; - - case MFDES_E_COMMAND_ABORTED: - return "Previous command was not fully completed / Not all Frames were requested or provided by the PCD"; - - case MFDES_E_PICC_DISABLED: - return "PICC was disabled by an unrecoverable error"; - - case MFDES_E_COUNT: - return "Application count is limited to 28, not addition CreateApplication possible"; - - case MFDES_E_DUPLICATE: - return "Duplicate entry: File/Application does already exist"; - - case MFDES_E_EEPROM: - return "Eeprom error due to loss of power, internal backup/rollback mechanism activated"; - - case MFDES_E_FILE_NOT_FOUND: - return "Specified file number does not exist"; - - case MFDES_E_FILE_INTEGRITY: - return "File integrity error, file will be disabled"; - - default: - return "Unknown error"; - } - } - return "Unknown error"; -} - -static char* GetErrorString(int res,uint16_t* sw) -{ - switch(res){ - case PM3_EAPDU_FAIL: - return getstatus(sw); - case PM3_EUNDEF: - return "Undefined error"; - case PM3_EINVARG: - return "Invalid argument(s)"; - case PM3_EDEVNOTSUPP: - return "Operation not supported by device"; - case PM3_ETIMEOUT: - return "Operation timed out"; - case PM3_EOPABORTED: - return "Operation aborted (by user)"; - case PM3_ENOTIMPL: - return "Not (yet) implemented"; - case PM3_ERFTRANS: - return "Error while RF transmission"; - case PM3_EIO: - return "Input / output error"; - case PM3_EOVFLOW: - return "Buffer overflow"; - case PM3_ESOFT: - return "Software error"; - case PM3_EFLASH: - return "Flash error"; - case PM3_EMALLOC: - return "Memory allocation error"; - case PM3_EFILE: - return "File error"; - case PM3_ENOTTY: - return "Generic TTY error"; - case PM3_EINIT: - return "Initialization error"; - case PM3_EWRONGANSVER: - return "Expected a different answer error"; - case PM3_EOUTOFBOUND: - return "Memory out-of-bounds error"; - case PM3_ECARDEXCHANGE: - return "Exchange with card error"; - case PM3_EAPDU_ENCODEFAIL: - return "Failed to create APDU"; - case PM3_ENODATA: - return "No data"; - case PM3_EFATAL: - return "Fatal error"; - default: - break; - } - return ""; -} - - -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize,bool readalldata) { - if (g_debugMode>1) - { - if (apdu==NULL) PrintAndLogEx(ERR, "APDU=NULL"); - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (sw==NULL) PrintAndLogEx(ERR, "SW=NULL"); - if (recv_len==NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); - } - if (apdu==NULL || sw==NULL || recv_len==NULL) return PM3_EINVARG; - - *sw = 0; - uint8_t data[255 * 5] = {0x00}; - int resplen = 0; - int pos = 0; - int i = 1; - int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) { - if (g_debugMode>1) GetErrorString(res,sw); - return res; - } - if (dest != NULL) { - memcpy(dest, data, resplen); - } - - pos += resplen; - if (!readalldata) - { - if (*sw==status(MFDES_ADDITIONAL_FRAME)) { - apdu->INS = MFDES_ABORT_TRANSACTION; - apdu->Lc = 0; - apdu->P1 = 0; - apdu->P2 = 0; - res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - return PM3_SUCCESS; - } - return res; - } - while (*sw == status(MFDES_ADDITIONAL_FRAME)) { - apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF - apdu->Lc=0; - apdu->P1=0; - apdu->P2=0; - - res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS){ - if (g_debugMode>1) GetErrorString(res,sw); - return res; - } - if (dest != NULL) { - if (splitbysize) { - memcpy(&dest[i * splitbysize], data, resplen); - i += 1; - } else { - memcpy(&dest[pos], data, resplen); - } - } - pos += resplen; - if (*sw!=status(MFDES_ADDITIONAL_FRAME)) break; - } - if (splitbysize) *recv_len = i; - else { - *recv_len = pos; - } - return PM3_SUCCESS; - -} - -static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { - - if (major == 0x00) - return MF3ICD40; - else if (major == 0x01 && minor == 0x00) - return EV1; - else if (major == 0x12 && minor == 0x00) - return EV2; -// else if (major == 0x13 && minor == 0x00) -// return EV3; - else if (major == 0x30 && minor == 0x00) - return LIGHT; - else - return UNKNOWN; -} - -//none, verified -static int test_desfire_authenticate() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); -} - -// none, verified -static int test_desfire_authenticate_iso() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); -} - -//none, verified -static int test_desfire_authenticate_aes() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0,false); -} - -// --- FREE MEM, verified -static int desfire_print_freemem(uint32_t free_mem) { - PrintAndLogEx(SUCCESS, " Available free memory on card : " _GREEN_("%d bytes"), free_mem); - return PM3_SUCCESS; -} - -// init / disconnect, verified -static int get_desfire_freemem(uint32_t *free_mem) { - if (free_mem==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E - int recv_len = 0; - uint16_t sw = 0; - uint8_t fmem[4] = {0}; - - int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0,true); - if (res == PM3_SUCCESS) { - *free_mem = le24toh(fmem); - return res; - } - *free_mem = 0; - return res; -} - - -// --- GET SIGNATURE, verified -static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { - if (g_debugMode>1) - { - if (uid==NULL) PrintAndLogEx(ERR, "UID=NULL"); - if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); - } - if (uid==NULL || signature==NULL) return PM3_EINVARG; - // DESFire Ev3 - wanted - // ref: MIFARE Desfire Originality Signature Validation - -#define PUBLIC_DESFIRE_ECDA_KEYLEN 57 - const ecdsa_publickey_t nxp_desfire_public_keys[] = { - {"NTAG424DNA, DESFire EV2", "048A9B380AF2EE1B98DC417FECC263F8449C7625CECE82D9B916C992DA209D68422B81EC20B65A66B5102A61596AF3379200599316A00A1410"}, - {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, - {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, - {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, - {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, - {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} - }; - - uint8_t i; - int res; - bool is_valid = false; - - for (i = 0; i < ARRAYLEN(nxp_desfire_public_keys); i++) { - - int dl = 0; - uint8_t key[PUBLIC_DESFIRE_ECDA_KEYLEN]; - param_gethex_to_eol(nxp_desfire_public_keys[i].value, 0, key, PUBLIC_DESFIRE_ECDA_KEYLEN, &dl); - - res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP224R1, key, uid, 7, signature, signature_len, false); - is_valid = (res == 0); - if (is_valid) - break; - } - if (is_valid == false) { - PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); - return PM3_ESOFT; - } - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); - PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); - PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); - PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); - PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 32); - PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 48); - PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); - PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); - PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); - return PM3_SUCCESS; -} - -// init / disconnect, verified -static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - if (g_debugMode>1) - { - if (signature==NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); - if (signature_len==NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); - } - if (signature==NULL || signature_len==NULL) return PM3_EINVARG; - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C - int recv_len = 0; - uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0,true); - if (res == PM3_SUCCESS) { - if (recv_len != 56) { - *signature_len = 0; - DropField(); - return PM3_ESOFT; - } else { - *signature_len = recv_len; - - } - DropField(); - return PM3_SUCCESS; - } - DropField(); - return res; -} - - -// --- KEY SETTING -static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { - - PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); - PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(SUCCESS, " Changekey Access rights"); - - // Access rights. - uint8_t rights = (key_settings >> 4 & 0x0F); - switch (rights) { - case 0x0: - PrintAndLogEx(SUCCESS, " -- AMK authentication is necessary to change any key (default)"); - break; - case 0xE: - PrintAndLogEx(SUCCESS, " -- Authentication with the key to be changed (same KeyNo) is necessary to change a key"); - break; - case 0xF: - PrintAndLogEx(SUCCESS, " -- All keys (except AMK,see Bit0) within this application are frozen"); - break; - default: - PrintAndLogEx(SUCCESS, " -- Authentication with the specified key is necessary to change any key.\nA change key and a PICC master key (CMK) can only be changed after authentication with the master key.\nFor keys other then the master or change key, an authentication with the same key is needed."); - break; - } - - PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_settings & (1 << 3)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x04] AMK required for create/delete : %s", (key_settings & (1 << 2)) ? "NO" : "YES"); - PrintAndLogEx(SUCCESS, " [0x02] Directory list access with AMK : %s", (key_settings & (1 << 1)) ? "NO" : "YES"); - PrintAndLogEx(SUCCESS, " [0x01] AMK is changeable : %s", (key_settings & (1 << 0)) ? _GREEN_("YES") : "NO"); - return PM3_SUCCESS; -} - -// none, verified -static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - if (g_debugMode>1) - { - if (key_settings==NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); - if (num_keys==NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); - } - if (key_settings==NULL || num_keys==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 - int recv_len = 0; - uint16_t sw = 0; - uint8_t data[2] = {0}; - int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0,true); - if (res != PM3_SUCCESS) return res; - - *key_settings = data[0]; - *num_keys = data[1]; - return PM3_SUCCESS; -} - -// --- KEY VERSION -static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { - PrintAndLogEx(SUCCESS, " Key [%u] Version : %d (0x%02x)", key_idx, key_version, key_version); - return PM3_SUCCESS; -} - -// none, verified -static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - if (g_debugMode>1) - { - if (num_versions==NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); - } - if (num_versions==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 - int recv_len = 0; - uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0,true); - return res; -} - - -// init / disconnect, verified -static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (app_ids_len==NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); - } - if (dest==NULL || app_ids_len==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a - int recv_len = 0; - uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0,true); - if (res != PM3_SUCCESS) return res; - *app_ids_len = (uint8_t)recv_len & 0xFF; - return res; -} - -// init, verified -static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (dfname_count==NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); - } - if (dest==NULL || dfname_count==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d - int recv_len = 0; - uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t),true); - if (res != PM3_SUCCESS) return res; - *dfname_count = recv_len; - return res; -} - - -// init, verified -static int get_desfire_select_application(uint8_t *aid) { - if (g_debugMode>1) - { - if (aid==NULL) PrintAndLogEx(ERR, "AID=NULL"); - } - if (aid==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a - int recv_len = 0; - uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t),true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"),(aid[0]<<16)+(aid[1]<<8)+aid[2],GetErrorString(res,&sw)); - DropField(); - return res; - } - return PM3_SUCCESS; -} - -// none, verified -static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (file_ids_len==NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); - } - if (dest==NULL || file_ids_len==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f - int recv_len = 0; - uint16_t sw = 0; - *file_ids_len = 0; - int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0,true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"),GetErrorString(res,&sw)); - DropField(); - return res; - } - *file_ids_len = recv_len; - return res; -} - -// none, verified -static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { - if (g_debugMode>1) - { - if (dest==NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (destlen==NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); - } - if (dest==NULL || destlen==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 - uint16_t sw = 0; - int res=send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0,true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"),GetErrorString(res,&sw)); - DropField(); - return res; - } - return res; -} - -typedef struct { - uint8_t aid[3]; - uint8_t keysetting1; - uint8_t keysetting2; - uint8_t fid[2]; - uint8_t name[16]; -} aidhdr_t; - -static int get_desfire_createapp(aidhdr_t* aidhdr) { - if (aidhdr==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t*)aidhdr}; // 0xCA - uint16_t sw = 0; - int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"),GetErrorString(res,&sw)); - DropField(); - return res; - } - return res; -} - -static int get_desfire_deleteapp(uint8_t* aid) { - if (aid==NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA - uint16_t sw = 0; - int recvlen=0; - int res=send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0,true); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"),GetErrorString(res,&sw)); - DropField(); - return res; - } - return res; -} - -static int CmdHF14ADesCreateApp(const char *Cmd) { - clearCommandBuffer(); - - CLIParserInit("hf mfdes createaid", - "Create Application ID", - "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to create"), - arg_strx0("fF", "fid", "", "File ID"), - arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), - arg_strx0("lL", "keysetting2", "", "Key Setting 2"), - arg_str0("nN", "name", "", "App ISO-4 Name"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, true); - /* KeySetting 1 (AMK Setting): - 0: Allow change master key - 1: Free Directory list access without master key - 0: AMK auth needed for GetFileSettings and GetKeySettings - 1: No AMK auth needed for GetFileIDs, GetISOFileIDs, GetFileSettings, GetKeySettings - 2: Free create/delete without master key - 0: CreateFile/DeleteFile only with AMK auth - 1: CreateFile/DeleteFile always - 3: Configuration changable - 0: Configuration frozen - 1: Configuration changable if authenticated with AMK (default) - 4-7: ChangeKey Access Rights - 0: Application master key needed (default) - 0x1..0xD: Auth with specific key needed to change any key - 0xE: Auth with the key to be changed (same KeyNo) is necessary to change a key - 0xF: All Keys within this application are frozen - - */ - /* KeySetting 2: - 0..3: Number of keys stored within the application (max. 14 keys - 4: RFU - 5: Use of 2 byte ISO FID, 0: No, 1: Yes - 6..7: Crypto Method 00: DES/3DES, 01: 3K3DES, 10: AES - Example: - 2E = FID, DES, 14 keys - 6E = FID, 3K3DES, 14 keys - AE = FID, AES, 14 keys - */ - int aidlength = 3; - int fidlength = 2; - uint8_t aid[3] = {0}; - uint8_t fid[2] = {0}; - uint8_t name[16] = {0}; - uint8_t keysetting1=0; - uint8_t keysetting2=0; - int keylen1=1; - int keylen2=1; - int namelen=16; - CLIGetHexWithReturn(1, aid, &aidlength); - CLIGetHexWithReturn(2, fid, &fidlength); - CLIGetHexWithReturn(3, &keysetting1, &keylen1); - CLIGetHexWithReturn(4, &keysetting2, &keylen2); - CLIGetStrWithReturn(5, name, &namelen); - CLIParserFree(); - - if (aidlength < 3) { - PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_EINVARG; - } - - if (fidlength < 2) { - PrintAndLogEx(ERR, "FID must have 2 bytes length."); - return PM3_EINVARG; - } - - if (keylen1 < 1) { - PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); - return PM3_EINVARG; - } - - if (keylen1 < 1) { - PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); - return PM3_EINVARG; - } - - if (namelen > 16) { - PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); - return PM3_EINVARG; - } - - //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 - /*char name[]="Test"; - uint8_t aid[]={0x12,0x34,0x56}; - uint8_t fid[]={0x11,0x22}; - uint8_t keysetting1=0xEE; - uint8_t keysetting2=0xEE;*/ - - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - PrintAndLogEx(WARNING, _RED_(" Creating root aid 000000 is forbidden.")); - return PM3_ESOFT; - } - - aidhdr_t aidhdr; - memcpy(aidhdr.aid,aid,sizeof(aid)); - aidhdr.keysetting1=keysetting1; - aidhdr.keysetting2=keysetting2; - memcpy(aidhdr.fid,fid,sizeof(fid)); - memcpy(aidhdr.name,name,sizeof(name)); - - uint8_t rootaid[3]={0x00,0x00,0x00}; - int res=get_desfire_select_application(rootaid); - if (res!=PM3_SUCCESS) return res; - - return get_desfire_createapp(&aidhdr); -} - -static int CmdHF14ADesDeleteApp(const char *Cmd) { - clearCommandBuffer(); - - CLIParserInit("hf mfdes deleteaid", - "Delete Application ID", - "Usage:\n\t-a aid (3 bytes)\n\n" - "Example:\n\thf mfdes deleteaid -a 123456\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to delete"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, true); - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - CLIParserFree(); - - if (aidlength < 3) { - PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_EINVARG; - } - - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - PrintAndLogEx(WARNING, _RED_(" Deleting root aid 000000 is forbidden.")); - return PM3_ESOFT; - } - - uint8_t rootaid[3]={0x00,0x00,0x00}; - int res=get_desfire_select_application(rootaid); - if (res!=PM3_SUCCESS) return res; - return get_desfire_deleteapp(aid); -} - - -static int CmdHF14ADesFormatPICC(const char *Cmd) { - (void) Cmd; // Cmd is not used so far - CLIParserInit("hf mfdes formatpicc", - "Formats MIFARE DESFire PICC to factory state", - "Usage:\n\t-k PICC key (8 bytes)\n\n" - "Example:\n\thf mfdes formatpicc -k 0000000000000000\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, true); - - uint8_t key[8] = {0}; - int keylen = 8; - CLIGetHexWithReturn(1, key, &keylen); - CLIParserFree(); - - if ((keylen < 8) || (keylen > 8)) { - PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); - //SetAPDULogging(false); - return PM3_EINVARG; - } - - clearCommandBuffer(); - DropField(); - uint8_t aid[3]={0}; - int res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; - uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) - memcpy(data + 1, key, keylen); - SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - - uint8_t isOK = resp.oldarg[0] & 0xff; - if (isOK) { - uint8_t rdata[] = {0xFC}; // 0xFC - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client reset command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - if (resp.oldarg[0]&0xFF){ - PrintAndLogEx(INFO, "Card successfully reset"); - return PM3_SUCCESS; - } - } else { - PrintAndLogEx(WARNING, _RED_("Auth command failed.")); - } - - return PM3_SUCCESS; -} - - -static int CmdHF14ADesInfo(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - - SendCommandNG(CMD_HF_DESFIRE_INFO, NULL, 0); - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_INFO, &resp, 1500)) { - PrintAndLogEx(WARNING, "Command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - - struct p { - uint8_t isOK; - uint8_t uid[7]; - uint8_t versionHW[7]; - uint8_t versionSW[7]; - uint8_t details[14]; - } PACKED; - - struct p *package = (struct p *) resp.data.asBytes; - - if (resp.status != PM3_SUCCESS) { - - switch (package->isOK) { - case 1: - PrintAndLogEx(WARNING, "Can't select card"); - break; - case 2: - PrintAndLogEx(WARNING, "Card is most likely not Desfire. Its UID has wrong size"); - break; - case 3: - default: - PrintAndLogEx(WARNING, _RED_("Command unsuccessful")); - break; - } - return PM3_ESOFT; - } - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(package->uid, sizeof(package->uid))); - PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(package->details + 7, 5)); - PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), package->details[12], package->details[13]); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionHW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionHW[2]); - PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionSW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionSW[2]); - PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Card capabilities")); - uint8_t major = package->versionSW[3]; - uint8_t minor = package->versionSW[4]; - if (major == 0 && minor == 4) - PrintAndLogEx(INFO, "\t0.4 - DESFire MF3ICD40, No support for APDU (only native commands)"); - if (major == 0 && minor == 5) - PrintAndLogEx(INFO, "\t0.5 - DESFire MF3ICD40, Support for wrapping commands inside ISO 7816 style APDUs"); - if (major == 0 && minor == 6) - PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); - if (major == 1 && minor == 3) - PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); - if (major == 1 && minor == 4) - PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); - if (major == 2 && minor == 0) - PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); -// if (major == 3 && minor == 0) -// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); - - if (major == 0 && minor == 2) - PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); - - // Signature originality check - uint8_t signature[56] = {0}; - size_t signature_len = 0; - desfire_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); - - if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) - desfire_print_signature(package->uid, signature, signature_len, cardtype); - else{ - PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature. Unknown public key ?")); - } - - // Master Key settings - uint8_t master_aid[3] = {0x00, 0x00, 0x00}; - getKeySettings(master_aid); - - // Free memory on card - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); - uint32_t free_mem = 0; - if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { - desfire_print_freemem(free_mem); - } else { - PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); - } - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - - /* - Card Master key (CMK) 0x00 AID = 00 00 00 (card level) - Application Master Key (AMK) 0x00 AID != 00 00 00 - Application keys (APK) 0x01-0x0D - Application free 0x0E - Application never 0x0F - - ACCESS RIGHTS: - keys 0,1,2,3 C - keys 4,5,6,7 RW - keys 8,9,10,11 W - keys 12,13,14,15 R - - */ - - DropField(); - return PM3_SUCCESS; -} - -/* - The 7 MSBits (= n) code the storage size itself based on 2^n, - the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). - For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. -*/ -char *getCardSizeStr(uint8_t fsize) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - uint16_t usize = 1 << ((fsize >> 1) + 1); - uint16_t lsize = 1 << (fsize >> 1); - - // is LSB set? - if (fsize & 1) - sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); - return buf; -} - -char *getProtocolStr(uint8_t id) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); - return buf; -} - -char *getVersionStr(uint8_t major, uint8_t minor) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (major == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); - else if (major == 0x01 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); - else if (major == 0x12 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); -// else if (major == 0x13 && minor == 0x00) -// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); - else if (major == 0x30 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); - else - sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); - return buf; -} - -int getKeySettings(uint8_t *aid) { - if (aid==NULL) return PM3_EINVARG; - int res=0; - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - - // CARD MASTER KEY - //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; - - // KEY Settings - AMK - uint8_t num_keys = 0; - uint8_t key_setting = 0; - res=get_desfire_keysettings(&key_setting, &num_keys); - if (res == PM3_SUCCESS) { - // number of Master keys (0x01) - PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); - - PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_setting & (1 << 3)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x04] CMK required for create/delete : %s", (key_setting & (1 << 2)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x02] Directory list access with CMK : %s", (key_setting & (1 << 1)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x01] CMK is changeable : %s", (key_setting & (1 << 0)) ? _GREEN_("YES") : "NO"); - } else { - PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); - } - - const char *str = " Operation of PICC master key : " _YELLOW_("%s"); - - // 2 MSB denotes - switch (num_keys >> 6) { - case 0: - PrintAndLogEx(SUCCESS, str, "(3)DES"); - break; - case 1: - PrintAndLogEx(SUCCESS, str, "3K3DES"); - break; - case 2: - PrintAndLogEx(SUCCESS, str, "AES"); - break; - default: - break; - } - - uint8_t cmk_num_versions = 0; - if (get_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, " PICC Master key Version : " _YELLOW_("%d (0x%02x)"), cmk_num_versions, cmk_num_versions); - PrintAndLogEx(INFO, " ----------------------------------------------------------"); - } - - // Authentication tests - int res = test_desfire_authenticate(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - res = test_desfire_authenticate_iso(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - res = test_desfire_authenticate_aes(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - - } else { - - // AID - APPLICATION MASTER KEYS - //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; - - // KEY Settings - AMK - uint8_t num_keys = 0; - uint8_t key_setting = 0; - res=get_desfire_keysettings(&key_setting, &num_keys); - if (res == PM3_SUCCESS) { - desfire_print_keysetting(key_setting, num_keys); - } else { - PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); - } - - // KEY VERSION - AMK - uint8_t num_version = 0; - if (get_desfire_keyversion(0, &num_version) == PM3_SUCCESS) { - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(INFO, " Application keys"); - desfire_print_keyversion(0, num_version); - } else { - PrintAndLogEx(WARNING, " Can't read AID master key version. Trying all keys"); - } - - // From 0x01 to numOfKeys. We already got 0x00. (AMK) - num_keys &= 0x3F; - if (num_keys > 1) { - for (uint8_t i = 0x01; i < num_keys; ++i) { - if (get_desfire_keyversion(i, &num_version) == PM3_SUCCESS) { - desfire_print_keyversion(i, num_version); - } else { - PrintAndLogEx(WARNING, " Can't read key %d (0x%02x) version", i, i); - } - } - } - } - - DropField(); - return PM3_SUCCESS; -} - -static void DecodeFileType(uint8_t filetype){ - switch (filetype) - { - case 0x00: - PrintAndLogEx(INFO, " File Type: 0x%02X -> Standard Data File", filetype); - break; - case 0x01: - PrintAndLogEx(INFO, " File Type: 0x%02X -> Backup Data File", filetype); - break; - case 0x02: - PrintAndLogEx(INFO, " File Type: 0x%02X -> Value Files with Backup", filetype); - break; - case 0x03: - PrintAndLogEx(INFO, " File Type: 0x%02X -> Linear Record Files with Backup", filetype); - break; - case 0x04: - PrintAndLogEx(INFO, " File Type: 0x%02X -> Cyclic Record Files with Backup", filetype); - break; - default: - PrintAndLogEx(INFO, " File Type: 0x%02X", filetype); - break; - } -} - -static void DecodeComSet(uint8_t comset){ - switch (comset) - { - case 0x00: - PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain", comset); - break; - case 0x01: - PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain + MAC", comset); - break; - case 0x03: - PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Enciphered", comset); - break; - default: - PrintAndLogEx(INFO, " Com.Setting: 0x%02X", comset); - break; - } -} - -static char* DecodeAccessValue(uint8_t value) -{ - char* car=(char*)malloc(255); - memset(car,0x0,255); - switch(value){ - case 0xE: - strcat(car, "(Free Access)"); - break; - case 0xF: - strcat(car, "(Denied Access)"); - break; - default: - sprintf(car,"(Access Key: %d)",value); - break; - } - return car; -} - -static void DecodeAccessRights(uint16_t accrights){ - int change_access_rights=accrights&0xF; - int read_write_access=(accrights>>4)&0xF; - int write_access=(accrights>>8)&0xF; - int read_access=(accrights>>12)&0xF; - char* car=DecodeAccessValue(change_access_rights); - char* rwa=DecodeAccessValue(read_write_access); - char* wa=DecodeAccessValue(write_access); - char* ra=DecodeAccessValue(read_access); - PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights,car,rwa,wa,ra); - free(car); - free(rwa); - free(wa); - free(ra); -} - -static int DecodeFileSettings(uint8_t* filesettings, int fileset_len, int maclen){ - uint8_t filetype=filesettings[0]; - uint8_t comset=filesettings[1]; - - uint16_t accrights=(filesettings[4]<<8)+filesettings[3]; - if (fileset_len==1+1+2+3+maclen) - { - int filesize=(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; - DecodeFileType(filetype); - DecodeComSet(comset); - DecodeAccessRights(accrights); - PrintAndLogEx(INFO, " Filesize: %d", filesize); - return PM3_SUCCESS; - } else if (fileset_len==1+1+2+4+4+4+1+maclen) { - int lowerlimit=(filesettings[8]<<24)+(filesettings[7]<<16)+(filesettings[6]<<8)+filesettings[5]; - int upperlimit=(filesettings[12]<<24)+(filesettings[11]<<16)+(filesettings[10]<<8)+filesettings[9]; - int limitcredvalue=(filesettings[16]<<24)+(filesettings[15]<<16)+(filesettings[14]<<8)+filesettings[13]; - uint8_t limited_credit_enabled=filesettings[17]; - DecodeFileType(filetype); - DecodeComSet(comset); - DecodeAccessRights(accrights); - PrintAndLogEx(INFO, " Lower limit: %d - Upper limit: %d - limited credit value: %d - limited credit enabled: %d", lowerlimit, upperlimit, limitcredvalue, limited_credit_enabled); - return PM3_SUCCESS; - } - return PM3_ESOFT; -} - -static int CmdHF14ADesEnumApplications(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - -// uint8_t isOK = 0x00; - uint8_t aid[3] = {0}; - uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; - - uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; - - dfname_t dfnames[255]; - uint8_t dfname_count = 0; - - int res=0; - - if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Can't get list of applications on tag"); - DropField(); - return PM3_ESOFT; - } - - if (get_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_("Can't get DF Names")); - DropField(); - return PM3_ESOFT; - } - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "-- Mifare DESFire Enumerate applications --------------------"); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "application%c", app_ids_len / 3, (app_ids_len == 3) ? ' ' : 's'); - - for (int i = 0; i < app_ids_len; i += 3) { - - aid[0] = app_ids[i]; - aid[1] = app_ids[i + 1]; - aid[2] = app_ids[i + 2]; - - PrintAndLogEx(NORMAL, ""); - - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - // CARD MASTER KEY - PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - } else { - PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - } - - PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X %02X %02X"), aid[0], aid[1], aid[2]); - for (int m = 0; m < dfname_count; m++) { - if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { - PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X %02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[0], dfnames[m].fid[1], dfnames[m].name); - } - } - - res=getKeySettings(aid); - if (res!=PM3_SUCCESS) return res; - - res=get_desfire_select_application(aid); - - - // Get File IDs - if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); - for (int j = 0; j < file_ids_len; ++j) { - PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); - - uint8_t filesettings[20] = {0}; - int fileset_len = 0; - int res = get_desfire_filesettings(j, filesettings, &fileset_len); - int maclen=0; // To be implemented - if (res == PM3_SUCCESS) { - if (DecodeFileSettings(filesettings,fileset_len,maclen)!=PM3_SUCCESS){ - PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); - } - } - } - } - - /* - // Get ISO File IDs - { - uint8_t data[] = {GET_ISOFILE_IDS, 0x00, 0x00, 0x00}; // 0x61 - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, DISCONNECT, sizeof(data), 0, data, sizeof(data)); - } - - if (!WaitForResponseTimeout(CMD_ACK, &respFiles, 1500)) { - PrintAndLogEx(WARNING, _RED_(" Timed-out")); - continue; - } else { - isOK = respFiles.data.asBytes[2] & 0xff; - if (!isOK) { - PrintAndLogEx(WARNING, _RED_(" Can't get ISO file ids")); - } else { - int respfileLen = resp.oldarg[1] - 3 - 2; - for (int j = 0; j < respfileLen; ++j) { - PrintAndLogEx(SUCCESS, " ISO Fileid %d :", resp.data.asBytes[j + 3]); - } - } - } - */ - } - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - DropField(); - return PM3_SUCCESS; -} - -// MIAFRE DESFire Authentication -// -#define BUFSIZE 256 -static int CmdHF14ADesAuth(const char *Cmd) { - int res=0; - DropField(); - clearCommandBuffer(); - // NR DESC KEYLENGHT - // ------------------------ - // 1 = DES 8 - // 2 = 3DES 16 - // 3 = 3K 3DES 24 - // 4 = AES 16 - //SetAPDULogging(true); - uint8_t keylength = 8; - - CLIParserInit("hf mfdes auth", - "Authenticates Mifare DESFire using Key", - "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes auth -m 3 -t 4 -a 018380 -n 0 -k 404142434445464748494a4b4c4d4e4f\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), - arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), - arg_strx0("aA", "aid", "", "AID used for authentification"), - arg_int0("nN", "keyno", "Key number used for authentification", NULL), - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, true); - - uint8_t cmdAuthMode = arg_get_int_def(1, 0); - uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); - - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(3, aid, &aidlength); - - uint8_t cmdKeyNo = arg_get_int_def(4, 0); - - uint8_t key[24] = {0}; - int keylen = 0; - CLIGetHexWithReturn(5, key, &keylen); - CLIParserFree(); - - if ((keylen < 8) || (keylen > 24)) { - PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); - //SetAPDULogging(false); - return PM3_EINVARG; - } - - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - //SetAPDULogging(false); - return PM3_EINVARG; - } - - switch (cmdAuthMode) { - case 1: - if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); - return PM3_EINVARG; - } - break; - case 2: - if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); - return PM3_EINVARG; - } - break; - case 3: - if (cmdAuthAlgo != 4) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); - return PM3_EINVARG; - } - break; - default: - PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - //SetAPDULogging(false); - return PM3_EINVARG; - } - - switch (cmdAuthAlgo) { - case 2: - keylength = 16; - PrintAndLogEx(NORMAL, "3DES selected"); - break; - case 3: - keylength = 24; - PrintAndLogEx(NORMAL, "3 key 3DES selected"); - break; - case 4: - keylength = 16; - PrintAndLogEx(NORMAL, "AES selected"); - break; - default: - cmdAuthAlgo = 1; - keylength = 8; - PrintAndLogEx(NORMAL, "DES selected"); - break; - } - - // KEY - if (keylen != keylength) { - PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); - return PM3_EINVARG; - } - - - res=get_desfire_select_application(aid); - if (res!=PM3_SUCCESS) return res; - - if (memcmp(aid,"\x00\x00\x00",3)!=0){ - uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; - res = get_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) return res; - } - - // algo, keylength, - uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) - memcpy(data + 1, key, keylength); - SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - - uint8_t isOK = resp.oldarg[0] & 0xff; - if (isOK) { - uint8_t *session_key = resp.data.asBytes; - - PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); - PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - //PrintAndLogEx(NORMAL, " Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); - } else { - PrintAndLogEx(WARNING, _RED_("Client command failed.")); - } - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - return PM3_SUCCESS; -} - -static int CmdHF14ADesList(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - return CmdTraceList("des"); -} - -static command_t CommandTable[] = { - {"help", CmdHelp, AlwaysAvailable, "This help"}, - {"info", CmdHF14ADesInfo, IfPm3Iso14443a, "Tag information"}, - {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, - {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, - {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, - {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, - {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, - {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, -// {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, -// {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, - {NULL, NULL, NULL, NULL} -}; - -static int CmdHelp(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - CmdsHelp(CommandTable); - return PM3_SUCCESS; -} - -int CmdHFMFDes(const char *Cmd) { - // flush - clearCommandBuffer(); - //g_debugMode=2; - return CmdsParse(CommandTable, Cmd); -} From 090223d35a7d38cb89aea870e0b7089d246ccdf8 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 01:20:59 +0200 Subject: [PATCH 25/66] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f15617c0..f32ea1497 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Updates `hf mfdes` functions, improved logging and added new commands (@bkerler) - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) From cd35b60d13b24127397d4f29c546d22fbab5d76c Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 01:26:37 +0200 Subject: [PATCH 26/66] Minor typo --- client/cmdhfmfdes.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 3912bbe1f..3e21d60be 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -918,16 +918,16 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionHW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionHW[2]); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionHW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionHW[2]); PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x0x%02X"), package->versionSW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x0x%02X"), package->versionSW[2]); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionSW[2]); PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); From 430ca985d3f364d14b5611b12f068f7948195da2 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 13:52:50 +1000 Subject: [PATCH 27/66] Add settings Plot Windows, log level, emoji, hints --- client/proxguiqt.cpp | 8 +- client/proxmark3.c | 10 +- client/settings.c | 232 ++++++++++++++++++++++++++----------------- client/settings.h | 20 +--- client/ui.h | 7 +- 5 files changed, 164 insertions(+), 113 deletions(-) diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index dc67953e6..caf977ba3 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -26,6 +26,7 @@ #include #include "proxgui.h" #include +#include "ui.h" extern "C" { #include "util_darwin.h" @@ -168,7 +169,12 @@ void ProxWidget::vchange_dthr_down(int v) { } ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { this->master = master; - resize(800, 400); + + // Set the initail postion and size from settings + if (session.settings_loaded) + setGeometry (session.window_plot_xpos,session.window_plot_ypos,session.window_plot_wsize,session.window_plot_hsize); + else + resize(800, 400); // Setup the controller widget controlWidget = new QWidget(); diff --git a/client/proxmark3.c b/client/proxmark3.c index 0438f81ad..1a731a57a 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -582,10 +582,14 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); - // Settings Load and Test - // settings_load (); + // Load Settings and assign + // This will allow the command line to override the settings.json values + settings_load (); + // quick patch for debug level + g_debugMode = session.logging_level; + // settings_save (); - // printf ("Ver : %s\n",mySettings.version); + // End Settings for (int i = 1; i < argc; i++) { diff --git a/client/settings.c b/client/settings.c index 79fa00fd1..c173ac8fa 100644 --- a/client/settings.c +++ b/client/settings.c @@ -39,55 +39,78 @@ // Settings Functions //----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// Notes +// To add a new setting +// Add the new setting to the session_arg_t; in ui.h +// Add the default value for the setting in the settings_load page below +// Update the settings_load_callback to load your setting into the stucture +// Update the settings_save_callback to enusre your setting gets saved (not used yet) +// Include "settingdata.h" (if needed) in the source file where you wish to use the setting +// use the setting as needed : mySettings. +// Should use if (mySettings.loaded) { use settings } +//----------------------------------------------------------------------------- + #include "settings.h" #include "comms.h" #include "emv/emvjson.h" +#include +/* +typedef struct { + bool stdinOnTTY; + bool stdoutOnTTY; + bool supports_colors; + emojiMode_t emoji_mode; + bool pm3_present; + bool help_dump_mode; + bool show_hints; +} session_arg_t; + +extern session_arg_t session +*/ // Load all settings into memory (struct) -int settings_load (void) { +int settings_load (void) +{ + + // Set all defaults +// mySettings.os_windows_usecolor = false; +// mySettings.os_windows_useansicolor = false; + session.logging_level = NORMAL; + session.window_plot_xpos = 10; + session.window_plot_ypos = 30; + session.window_plot_hsize = 400; + session.window_plot_wsize = 800; +// mySettings.window_xpos = 10; +// mySettings.window_ypos = 210; +// mySettings.window_hsize = 300; +// mySettings.window_wsize = 500; +// mySettings.show_emoji = ALIAS; + session.emoji_mode = ALIAS; + session.show_hints = false; + // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - // clear all settings - memset (&mySettings,0x00,sizeof(mySettings)); if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { - printf ("==> Settings Loaded\n"); - mySettings.loaded = true; + session.settings_loaded = true; } - - - // Test results - /* - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis - bool use_hints - */ - printf (" Settings Version : [%s]\n", mySettings.version); - printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); - printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); - printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); - printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); - printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); - printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); - printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); - printf (" use hints (bool) : [%d]\n", mySettings.use_hints); + else // Save default/create settings.json file + settings_save (); + return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save(void) { +int settings_save (void) +{ // Note sure if backup has value ? char backupFilename[500]; - snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -95,7 +118,7 @@ int settings_save(void) { return PM3_ESOFT; } } - + if (fileExists (settingsFilename)) { if (rename (settingsFilename,backupFilename) != 0) { PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",settingsFilename,backupFilename); @@ -105,90 +128,119 @@ int settings_save(void) { uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - + if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); - + return PM3_SUCCESS; } -void settings_save_callback(json_t *root) { - - printf ("==> Save Settings\n"); - //JsonSaveStr(root, "FileType", "settings"); - //JsonSaveStr (root,"Test1.Test2","test settings"); - /* - "version": "1.0 Nov 2019", - "os.windows.usecolor": true, - "os.windows.useAnsiColor": true, - "window.xpos": 10, - "window.ypos": 10, - "window.hsize": 300, - "window.wsize": 600 - */ - JsonSaveStr (root,"FileType","settings"); - JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); - JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); - JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); - JsonSaveInt (root,"window.xpos", mySettings.window_xpos); - JsonSaveInt (root,"window.ypos", mySettings.window_ypos); - JsonSaveInt (root,"window.hsize", mySettings.window_hsize); - JsonSaveInt (root,"window.wsize", mySettings.window_wsize); - JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); - JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); +void settings_save_callback (json_t *root) +{ + JsonSaveStr (root,"FileType","settings"); +// JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); +// JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); + // Log level, convert to text + // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); + switch (session.logging_level) + { + case NORMAL: JsonSaveStr (root,"logging.level","normal"); break; + case SUCCESS: JsonSaveStr (root,"logging.level","success"); break; + case INFO: JsonSaveStr (root,"logging.level","info"); break; + case FAILED: JsonSaveStr (root,"logging.level","failed"); break; + case WARNING: JsonSaveStr (root,"logging.level","warning"); break; + case ERR: JsonSaveStr (root,"logging.level","err"); break; + case DEBUG: JsonSaveStr (root,"logging.level","debug"); break; + case INPLACE: JsonSaveStr (root,"logging.level","inplace"); break; + case HINT: JsonSaveStr (root,"logging.level","hint"); break; + default: + JsonSaveStr (root,"logging.level","NORMAL"); + } + + // Plot window + JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); + JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); + JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); + JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); +// JsonSaveInt (root,"window.xpos",mySettings.window_xpos); +// JsonSaveInt (root,"window.ypos",mySettings.window_ypos); +// JsonSaveInt (root,"window.hsize",mySettings.window_hsize); +// JsonSaveInt (root,"window.wsize",mySettings.window_wsize); + + // Emoji + switch (session.emoji_mode) + { + case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; + case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; + case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; + case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; + default: + JsonSaveStr (root,"show.emoji","ALIAS"); + } + JsonSaveBoolean (root,"show.hints",session.show_hints); } -void settings_load_callback(json_t *root) { - +void settings_load_callback (json_t *root) +{ json_error_t up_error = {0}; - int b1; + bool b1; int i1; const char *s1; - - if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) - strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); - else - strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); - + + // Left for example of a string json read +// if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) +// strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); +/* // os.windows... if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useColor",&b1) == 0) mySettings.os_windows_usecolor = b1; - else // default - mySettings.os_windows_useansicolor = false; - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useAnsiColor",&b1) == 0) mySettings.os_windows_useansicolor = b1; - else // default - mySettings.os_windows_useansicolor = false; +*/ + // Logging Level +// typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; + if (json_unpack_ex(root,&up_error, 0, "{s:s}","logging.level",&s1) == 0) { + if (strncasecmp (s1,"NORMAL",7) == 0) session.logging_level = NORMAL; + if (strncasecmp (s1,"SUCCESS",8) == 0) session.logging_level = SUCCESS; + if (strncasecmp (s1,"INFO",4) == 0) session.logging_level = INFO; + if (strncasecmp (s1,"FAILED",6) == 0) session.logging_level = FAILED; + if (strncasecmp (s1,"WARNING",7) == 0) session.logging_level = WARNING; + if (strncasecmp (s1,"ERR",3) == 0) session.logging_level = ERR; + if (strncasecmp (s1,"DEBUG",5) == 0) session.logging_level = DEBUG; + if (strncasecmp (s1,"INPLACE",7) == 0) session.logging_level = INPLACE; + if (strncasecmp (s1,"HINT",7) == 0) session.logging_level = HINT; + } + // window plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) + session.window_plot_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) + session.window_plot_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) + session.window_plot_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) + session.window_plot_wsize = i1; +/* // window... if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.xpos",&i1) == 0) mySettings.window_xpos = i1; - else // default - mySettings.window_xpos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.ypos",&i1) == 0) mySettings.window_ypos = i1; - else // default - mySettings.window_ypos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.hsize",&i1) == 0) mySettings.window_hsize = i1; - else // default - mySettings.window_hsize = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.wsize",&i1) == 0) mySettings.window_wsize = i1; - else // default - mySettings.window_wsize = 0; - - // Use EMOJIS - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) - mySettings.use_emojis = b1; - else // default - mySettings.use_emojis = false; - - // Use Hints - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) - mySettings.use_hints = b1; - else // default - mySettings.use_hints = false; + +*/ + // show options + // typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","show.emoji",&s1) == 0) { + if (strncasecmp (s1,"ALIAS",5) == 0) session.emoji_mode = ALIAS; + if (strncasecmp (s1,"EMOJI",5) == 0) session.emoji_mode = EMOJI; + if (strncasecmp (s1,"ALTTEXT",7) == 0) session.emoji_mode = ALTTEXT; + if (strncasecmp (s1,"ERASE",5) == 0) session.emoji_mode = ERASE; + } + if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) + session.show_hints = b1; } diff --git a/client/settings.h b/client/settings.h index 4bf8b2a5e..c404a82e2 100644 --- a/client/settings.h +++ b/client/settings.h @@ -8,29 +8,13 @@ //----------------------------------------------------------------------------- // Settings Functions //----------------------------------------------------------------------------- -#ifndef settings_h -#define settings_h +#ifndef SETTINGS_H_ +#define SETTINGS_H_ #include "fileutils.h" #define settingsFilename "settings.json" -typedef struct { - bool loaded; - char version[20]; - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis; - bool use_hints; -} settings_t; - -// Settings struct so as to be available to other modules by including settings.h -settings_t mySettings; - int settings_load (void); int settings_save (void); diff --git a/client/ui.h b/client/ui.h index 5bb814b81..2ab675c07 100644 --- a/client/ui.h +++ b/client/ui.h @@ -21,6 +21,7 @@ typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLA typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; typedef struct { + bool settings_loaded; bool stdinOnTTY; bool stdoutOnTTY; bool supports_colors; @@ -28,8 +29,12 @@ typedef struct { bool pm3_present; bool help_dump_mode; bool show_hints; + int window_plot_xpos; + int window_plot_ypos; + int window_plot_hsize; + int window_plot_wsize; + logLevel_t logging_level; } session_arg_t; - extern session_arg_t session; #ifndef M_PI From 054282556722eaec4cdd9311144a1307cb3b39fd Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 13:58:57 +1000 Subject: [PATCH 28/66] Revert "Add settings" This reverts commit 430ca985d3f364d14b5611b12f068f7948195da2. --- client/proxguiqt.cpp | 8 +- client/proxmark3.c | 10 +- client/settings.c | 232 +++++++++++++++++-------------------------- client/settings.h | 20 +++- client/ui.h | 7 +- 5 files changed, 113 insertions(+), 164 deletions(-) diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index caf977ba3..dc67953e6 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -26,7 +26,6 @@ #include #include "proxgui.h" #include -#include "ui.h" extern "C" { #include "util_darwin.h" @@ -169,12 +168,7 @@ void ProxWidget::vchange_dthr_down(int v) { } ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { this->master = master; - - // Set the initail postion and size from settings - if (session.settings_loaded) - setGeometry (session.window_plot_xpos,session.window_plot_ypos,session.window_plot_wsize,session.window_plot_hsize); - else - resize(800, 400); + resize(800, 400); // Setup the controller widget controlWidget = new QWidget(); diff --git a/client/proxmark3.c b/client/proxmark3.c index 1a731a57a..0438f81ad 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -582,14 +582,10 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); - // Load Settings and assign - // This will allow the command line to override the settings.json values - settings_load (); - // quick patch for debug level - g_debugMode = session.logging_level; - + // Settings Load and Test + // settings_load (); // settings_save (); - + // printf ("Ver : %s\n",mySettings.version); // End Settings for (int i = 1; i < argc; i++) { diff --git a/client/settings.c b/client/settings.c index c173ac8fa..79fa00fd1 100644 --- a/client/settings.c +++ b/client/settings.c @@ -39,78 +39,55 @@ // Settings Functions //----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -// Notes -// To add a new setting -// Add the new setting to the session_arg_t; in ui.h -// Add the default value for the setting in the settings_load page below -// Update the settings_load_callback to load your setting into the stucture -// Update the settings_save_callback to enusre your setting gets saved (not used yet) -// Include "settingdata.h" (if needed) in the source file where you wish to use the setting -// use the setting as needed : mySettings. -// Should use if (mySettings.loaded) { use settings } -//----------------------------------------------------------------------------- - #include "settings.h" #include "comms.h" #include "emv/emvjson.h" -#include -/* -typedef struct { - bool stdinOnTTY; - bool stdoutOnTTY; - bool supports_colors; - emojiMode_t emoji_mode; - bool pm3_present; - bool help_dump_mode; - bool show_hints; -} session_arg_t; - -extern session_arg_t session -*/ // Load all settings into memory (struct) -int settings_load (void) -{ - - // Set all defaults -// mySettings.os_windows_usecolor = false; -// mySettings.os_windows_useansicolor = false; - session.logging_level = NORMAL; - session.window_plot_xpos = 10; - session.window_plot_ypos = 30; - session.window_plot_hsize = 400; - session.window_plot_wsize = 800; -// mySettings.window_xpos = 10; -// mySettings.window_ypos = 210; -// mySettings.window_hsize = 300; -// mySettings.window_wsize = 500; -// mySettings.show_emoji = ALIAS; - session.emoji_mode = ALIAS; - session.show_hints = false; - +int settings_load (void) { // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; size_t dummyDL = 0x00; + // clear all settings + memset (&mySettings,0x00,sizeof(mySettings)); if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { - session.settings_loaded = true; + printf ("==> Settings Loaded\n"); + mySettings.loaded = true; } - else // Save default/create settings.json file - settings_save (); - + + + // Test results + /* + bool os_windows_usecolor; + bool os_windows_useansicolor; + int window_xpos; + int window_ypos; + int window_hsize; + int window_wsize; + bool use_emojis + bool use_hints + */ + printf (" Settings Version : [%s]\n", mySettings.version); + printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); + printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); + printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); + printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); + printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); + printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); + printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); + printf (" use hints (bool) : [%d]\n", mySettings.use_hints); return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save (void) -{ +int settings_save(void) { // Note sure if backup has value ? char backupFilename[500]; - snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -118,7 +95,7 @@ int settings_save (void) return PM3_ESOFT; } } - + if (fileExists (settingsFilename)) { if (rename (settingsFilename,backupFilename) != 0) { PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",settingsFilename,backupFilename); @@ -128,119 +105,90 @@ int settings_save (void) uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - + if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); - + return PM3_SUCCESS; } -void settings_save_callback (json_t *root) -{ - JsonSaveStr (root,"FileType","settings"); -// JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); -// JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); - // Log level, convert to text - // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); - switch (session.logging_level) - { - case NORMAL: JsonSaveStr (root,"logging.level","normal"); break; - case SUCCESS: JsonSaveStr (root,"logging.level","success"); break; - case INFO: JsonSaveStr (root,"logging.level","info"); break; - case FAILED: JsonSaveStr (root,"logging.level","failed"); break; - case WARNING: JsonSaveStr (root,"logging.level","warning"); break; - case ERR: JsonSaveStr (root,"logging.level","err"); break; - case DEBUG: JsonSaveStr (root,"logging.level","debug"); break; - case INPLACE: JsonSaveStr (root,"logging.level","inplace"); break; - case HINT: JsonSaveStr (root,"logging.level","hint"); break; - default: - JsonSaveStr (root,"logging.level","NORMAL"); - } - - // Plot window - JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); - JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); - JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); - JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); -// JsonSaveInt (root,"window.xpos",mySettings.window_xpos); -// JsonSaveInt (root,"window.ypos",mySettings.window_ypos); -// JsonSaveInt (root,"window.hsize",mySettings.window_hsize); -// JsonSaveInt (root,"window.wsize",mySettings.window_wsize); - - // Emoji - switch (session.emoji_mode) - { - case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; - case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; - case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; - case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; - default: - JsonSaveStr (root,"show.emoji","ALIAS"); - } - JsonSaveBoolean (root,"show.hints",session.show_hints); +void settings_save_callback(json_t *root) { + + printf ("==> Save Settings\n"); + //JsonSaveStr(root, "FileType", "settings"); + //JsonSaveStr (root,"Test1.Test2","test settings"); + /* + "version": "1.0 Nov 2019", + "os.windows.usecolor": true, + "os.windows.useAnsiColor": true, + "window.xpos": 10, + "window.ypos": 10, + "window.hsize": 300, + "window.wsize": 600 + */ + JsonSaveStr (root,"FileType","settings"); + JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); + JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); + JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); + JsonSaveInt (root,"window.xpos", mySettings.window_xpos); + JsonSaveInt (root,"window.ypos", mySettings.window_ypos); + JsonSaveInt (root,"window.hsize", mySettings.window_hsize); + JsonSaveInt (root,"window.wsize", mySettings.window_wsize); + JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); + JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); } -void settings_load_callback (json_t *root) -{ +void settings_load_callback(json_t *root) { + json_error_t up_error = {0}; - bool b1; + int b1; int i1; const char *s1; - - // Left for example of a string json read -// if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) -// strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); -/* + + if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) + strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); + else + strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); + // os.windows... if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useColor",&b1) == 0) mySettings.os_windows_usecolor = b1; + else // default + mySettings.os_windows_useansicolor = false; + if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useAnsiColor",&b1) == 0) mySettings.os_windows_useansicolor = b1; -*/ - // Logging Level -// typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; - if (json_unpack_ex(root,&up_error, 0, "{s:s}","logging.level",&s1) == 0) { - if (strncasecmp (s1,"NORMAL",7) == 0) session.logging_level = NORMAL; - if (strncasecmp (s1,"SUCCESS",8) == 0) session.logging_level = SUCCESS; - if (strncasecmp (s1,"INFO",4) == 0) session.logging_level = INFO; - if (strncasecmp (s1,"FAILED",6) == 0) session.logging_level = FAILED; - if (strncasecmp (s1,"WARNING",7) == 0) session.logging_level = WARNING; - if (strncasecmp (s1,"ERR",3) == 0) session.logging_level = ERR; - if (strncasecmp (s1,"DEBUG",5) == 0) session.logging_level = DEBUG; - if (strncasecmp (s1,"INPLACE",7) == 0) session.logging_level = INPLACE; - if (strncasecmp (s1,"HINT",7) == 0) session.logging_level = HINT; - } + else // default + mySettings.os_windows_useansicolor = false; - // window plot - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) - session.window_plot_xpos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) - session.window_plot_ypos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) - session.window_plot_hsize = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) - session.window_plot_wsize = i1; -/* // window... if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.xpos",&i1) == 0) mySettings.window_xpos = i1; + else // default + mySettings.window_xpos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.ypos",&i1) == 0) mySettings.window_ypos = i1; + else // default + mySettings.window_ypos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.hsize",&i1) == 0) mySettings.window_hsize = i1; + else // default + mySettings.window_hsize = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.wsize",&i1) == 0) mySettings.window_wsize = i1; - -*/ - // show options - // typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","show.emoji",&s1) == 0) { - if (strncasecmp (s1,"ALIAS",5) == 0) session.emoji_mode = ALIAS; - if (strncasecmp (s1,"EMOJI",5) == 0) session.emoji_mode = EMOJI; - if (strncasecmp (s1,"ALTTEXT",7) == 0) session.emoji_mode = ALTTEXT; - if (strncasecmp (s1,"ERASE",5) == 0) session.emoji_mode = ERASE; - } - if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) - session.show_hints = b1; + else // default + mySettings.window_wsize = 0; + + // Use EMOJIS + if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) + mySettings.use_emojis = b1; + else // default + mySettings.use_emojis = false; + + // Use Hints + if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) + mySettings.use_hints = b1; + else // default + mySettings.use_hints = false; } diff --git a/client/settings.h b/client/settings.h index c404a82e2..4bf8b2a5e 100644 --- a/client/settings.h +++ b/client/settings.h @@ -8,13 +8,29 @@ //----------------------------------------------------------------------------- // Settings Functions //----------------------------------------------------------------------------- -#ifndef SETTINGS_H_ -#define SETTINGS_H_ +#ifndef settings_h +#define settings_h #include "fileutils.h" #define settingsFilename "settings.json" +typedef struct { + bool loaded; + char version[20]; + bool os_windows_usecolor; + bool os_windows_useansicolor; + int window_xpos; + int window_ypos; + int window_hsize; + int window_wsize; + bool use_emojis; + bool use_hints; +} settings_t; + +// Settings struct so as to be available to other modules by including settings.h +settings_t mySettings; + int settings_load (void); int settings_save (void); diff --git a/client/ui.h b/client/ui.h index 2ab675c07..5bb814b81 100644 --- a/client/ui.h +++ b/client/ui.h @@ -21,7 +21,6 @@ typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLA typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; typedef struct { - bool settings_loaded; bool stdinOnTTY; bool stdoutOnTTY; bool supports_colors; @@ -29,12 +28,8 @@ typedef struct { bool pm3_present; bool help_dump_mode; bool show_hints; - int window_plot_xpos; - int window_plot_ypos; - int window_plot_hsize; - int window_plot_wsize; - logLevel_t logging_level; } session_arg_t; + extern session_arg_t session; #ifndef M_PI From 978f57b505da2fb9087b4b80d98f92d8eae1fdcd Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 13:59:56 +1000 Subject: [PATCH 29/66] Revert "Merge pull request #32 from RfidResearchGroup/master" This reverts commit 40d2a3c072d181f5558cdc5364a30de3a8d9b610, reversing changes made to 15d584e060a9c08deba56a0408ca3167f566766f. --- CHANGELOG.md | 7 +- armsrc/desfire.h | 1 - armsrc/epa.c | 31 +- armsrc/felica.c | 4 +- armsrc/hitagS.c | 6 +- armsrc/legicrf.c | 6 +- armsrc/lfops.c | 2 +- armsrc/mifaredesfire.c | 24 +- client/cmdhf14a.c | 160 ++--- client/cmdhflegic.c | 19 +- client/cmdhflist.c | 238 ++++---- client/cmdhfmfdes.c | 551 +++++++----------- client/cmdhfmfdes.h | 40 +- client/cmdhfmfp.c | 276 ++------- client/emv/apduinfo.c | 12 +- client/emv/emvcore.c | 4 - client/emv/emvcore.h | 1 - client/luascripts/legic.lua | 159 +++-- client/mifare/mifare4.c | 40 -- client/mifare/mifare4.h | 3 - client/settings.c | 68 +-- client/settings.h | 2 - .../Troubleshooting.md | 2 +- include/pm3_cmd.h | 5 - include/protocols.h | 84 ++- 25 files changed, 666 insertions(+), 1079 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f15617c0..946b7c541 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,13 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] - - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) - - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) - - Fix Mifare Desfire select appid handling (@bkerler) - - Improved `hf 14a info` - card detection handling (@bkerler) - Updated helptext layout in all luascripts (@iceman1001) - - Change `hf mfdes info` - output and logging (@bkerler) + - Change `hf mfdes info` - output and logging (@brkeler) - Updated texts in legic commands (@ikarus23) - Fix timing bug inside 40x5 (@mwalker33) - Refactored all Hitag2 attacks (@doegox) diff --git a/armsrc/desfire.h b/armsrc/desfire.h index e753106e7..5fa7e8d48 100644 --- a/armsrc/desfire.h +++ b/armsrc/desfire.h @@ -150,7 +150,6 @@ enum DESFIRE_CMD { GET_FREE_MEMORY = 0x6e, GET_FILE_IDS = 0x6f, GET_FILE_SETTINGS = 0xf5, - GET_DF_NAMES = 0x6d, CHANGE_FILE_SETTINGS = 0x5f, CREATE_STD_DATA_FILE = 0xcd, CREATE_BACKUP_DATA_FILE = 0xcb, diff --git a/armsrc/epa.c b/armsrc/epa.c index 3a44502ba..f535b89a3 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -263,7 +263,7 @@ static void EPA_PACE_Collect_Nonce_Abort(uint8_t step, int func_return) { EPA_Finish(); // send the USB packet - reply_mix(CMD_ACK, step, func_return, 0, 0, 0); + reply_old(CMD_ACK, step, func_return, 0, 0, 0); } //----------------------------------------------------------------------------- @@ -280,8 +280,12 @@ void EPA_PACE_Collect_Nonce(PacketCommandNG *c) { * d: * Encrypted nonce */ + + // return value of a function + int func_return = 0; + // set up communication - int func_return = EPA_Setup(); + func_return = EPA_Setup(); if (func_return != 0) { EPA_PACE_Collect_Nonce_Abort(1, func_return); return; @@ -331,7 +335,7 @@ void EPA_PACE_Collect_Nonce(PacketCommandNG *c) { EPA_Finish(); // save received information - reply_mix(CMD_ACK, 0, func_return, 0, nonce, func_return); + reply_old(CMD_ACK, 0, func_return, 0, nonce, func_return); } //----------------------------------------------------------------------------- @@ -443,7 +447,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { if (c->oldarg[0] != 0) { // make sure it's not too big if (c->oldarg[2] > apdus_replay[c->oldarg[0] - 1].len) { - reply_mix(CMD_ACK, 1, 0, 0, NULL, 0); + reply_old(CMD_ACK, 1, 0, 0, NULL, 0); } memcpy(apdus_replay[c->oldarg[0] - 1].data + c->oldarg[1], c->data.asBytes, @@ -454,7 +458,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { } else { apdu_lengths_replay[c->oldarg[0] - 1] += c->oldarg[2]; } - reply_mix(CMD_ACK, 0, 0, 0, NULL, 0); + reply_old(CMD_ACK, 0, 0, 0, NULL, 0); return; } @@ -465,7 +469,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { func_return = EPA_Setup(); if (func_return != 0) { EPA_Finish(); - reply_mix(CMD_ACK, 2, func_return, 0, NULL, 0); + reply_old(CMD_ACK, 2, func_return, 0, NULL, 0); return; } @@ -488,12 +492,12 @@ void EPA_PACE_Replay(PacketCommandNG *c) { || response_apdu[func_return - 4] != 0x90 || response_apdu[func_return - 3] != 0x00)) { EPA_Finish(); - reply_mix(CMD_ACK, 3 + i, func_return, 0, timings, 20); + reply_old(CMD_ACK, 3 + i, func_return, 0, timings, 20); return; } } EPA_Finish(); - reply_mix(CMD_ACK, 0, 0, 0, timings, 20); + reply_old(CMD_ACK, 0, 0, 0, timings, 20); return; } @@ -502,13 +506,14 @@ void EPA_PACE_Replay(PacketCommandNG *c) { // Returns 0 on success or a non-zero error code on failure //----------------------------------------------------------------------------- int EPA_Setup() { + uint8_t uid[10]; + iso14a_card_select_t card_a_info; // first, look for type A cards // power up the field iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - iso14a_card_select_t card_a_info; - int return_code = iso14443a_select_card(NULL, &card_a_info, NULL, true, 0, false); - + // select the card + int return_code = iso14443a_select_card(uid, &card_a_info, NULL, true, 0, false); if (return_code == 1) { uint8_t pps_response[3]; uint8_t pps_response_par[1]; @@ -523,14 +528,12 @@ int EPA_Setup() { return 0; } - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - // if we're here, there is no type A card, so we look for type B // power up the field iso14443b_setup(); iso14b_card_select_t card_b_info; + // select the card return_code = iso14443b_select_card(&card_b_info); - if (return_code == 0) { Dbprintf("ISO 14443 Type B"); iso_type = 'b'; diff --git a/armsrc/felica.c b/armsrc/felica.c index 2cb23b48c..b1e0253a2 100644 --- a/armsrc/felica.c +++ b/armsrc/felica.c @@ -621,7 +621,7 @@ void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) { set_tracelen(BigBuf_max_traceLen()); Dbprintf("Felica sniffing done, tracelen: %i, use hf list felica for annotations", BigBuf_get_traceLen()); - reply_mix(CMD_ACK, 1, numbts, 0, 0, 0); + reply_old(CMD_ACK, 1, numbts, 0, 0, 0); LED_D_OFF(); } @@ -812,5 +812,5 @@ void felica_dump_lite_s() { //setting tracelen - important! it was set by buffer overflow before set_tracelen(cnt); - reply_mix(CMD_ACK, isOK, cnt, 0, 0, 0); + reply_old(CMD_ACK, isOK, cnt, 0, 0, 0); } diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index 4268e82e5..78009496e 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -1407,7 +1407,7 @@ void ReadHitagS(hitag_function htf, hitag_data *htd) { set_tracing(false); lf_finalize(); - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); } /* @@ -1624,7 +1624,7 @@ void WritePageHitagS(hitag_function htf, hitag_data *htd, int page) { lf_finalize(); - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); } /* @@ -1860,5 +1860,5 @@ void check_challenges(bool file_given, uint8_t *data) { set_tracing(false); lf_finalize(); - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); } diff --git a/armsrc/legicrf.c b/armsrc/legicrf.c index b411efcaf..35b638298 100644 --- a/armsrc/legicrf.c +++ b/armsrc/legicrf.c @@ -438,7 +438,7 @@ void LegicRfInfo(void) { } // OK - reply_mix(CMD_ACK, 1, 0, 0, (uint8_t *)&card, sizeof(legic_card_select_t)); + reply_old(CMD_ACK, 1, 0, 0, (uint8_t *)&card, sizeof(legic_card_select_t)); OUT: switch_off(); @@ -513,7 +513,7 @@ void LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv) { } // OK - reply_mix(CMD_ACK, 1, len, 0, 0, 0); + reply_old(CMD_ACK, 1, len, 0, legic_mem, len); OUT: switch_off(); @@ -552,7 +552,7 @@ void LegicRfWriter(uint16_t offset, uint16_t len, uint8_t iv, uint8_t *data) { } // OK - reply_mix(CMD_ACK, 1, len, 0, 0, 0); + reply_old(CMD_ACK, 1, len, 0, legic_mem, len); OUT: switch_off(); diff --git a/armsrc/lfops.c b/armsrc/lfops.c index a5104d98e..65f9e8422 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -2040,7 +2040,7 @@ void T55xx_ChkPwds(uint8_t flags) { if (isok != sizeof(counter)) goto OUT; - pwdCount = (uint16_t)(counter[1] << 8 | counter[0]); + pwdCount = counter[1] << 8 | counter[0]; if (pwdCount == 0 || pwdCount == 0xFFFF) goto OUT; diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index b2f45d117..5b8ed289e 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -204,7 +204,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t decRndB[16] = {0x00}; uint8_t both[32] = {0x00}; - //InitDesfireCard(); + InitDesfireCard(); LED_A_ON(); LED_B_OFF(); @@ -455,12 +455,8 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_init(&ctx); cmd[0] = AUTHENTICATE_AES; - cmd[1] = 0x0; - cmd[2] = 0x0; - cmd[3] = 0x1; - cmd[4] = arg2; //keynumber - cmd[5] = 0x0; - len = DesfireAPDU(cmd, 6, resp); + cmd[1] = 0x00; //keynumber + len = DesfireAPDU(cmd, 2, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -469,7 +465,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - memcpy(encRndB, resp + 1, 16); + memcpy(encRndB, resp + 3, 16); // dekryptera tagnonce. if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { @@ -495,13 +491,9 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, both, encBoth); cmd[0] = ADDITIONAL_FRAME; - cmd[1] = 0x00; - cmd[2] = 0x00; - cmd[3] = 0x20; - memcpy(cmd + 4, encBoth, 32); - cmd[36]=0x0; + memcpy(cmd + 1, encBoth, 32); - len = DesfireAPDU(cmd, 37, resp); // 4 + 32 + 1 == 37 + len = DesfireAPDU(cmd, 33, resp); // 1 + 32 == 33 if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -510,7 +502,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if ((resp[1+16] == 0x91)&&(resp[1+16+1] == 0x00)) { + if (resp[2] == 0x00) { // Create AES Session key struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; @@ -609,6 +601,6 @@ void OnSuccess() { } void OnError(uint8_t reason) { - reply_mix(CMD_ACK, 0, reason, 0, 0, 0); + reply_old(CMD_ACK, 0, reason, 0, 0, 0); OnSuccess(); } diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 2e5fcb69e..f737ff485 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -193,7 +193,7 @@ static int usage_hf_14a_sim(void) { PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344")); PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344556677")); // PrintAndLogEx(NORMAL, " hf 14a sim t 1 u 11223445566778899AA\n"); - return PM3_SUCCESS; + return 0; } static int usage_hf_14a_sniff(void) { PrintAndLogEx(NORMAL, "It get data from the field and saves it into command buffer."); @@ -203,7 +203,7 @@ static int usage_hf_14a_sniff(void) { PrintAndLogEx(NORMAL, "r - triggered by first 7-bit request from reader (REQ,WUP,...)"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sniff c r")); - return PM3_SUCCESS; + return 0; } static int usage_hf_14a_raw(void) { PrintAndLogEx(NORMAL, "Usage: hf 14a raw [-h] [-r] [-c] [-p] [-a] [-T] [-t] [-b] <0A 0B 0C ... hex>"); @@ -217,7 +217,7 @@ static int usage_hf_14a_raw(void) { PrintAndLogEx(NORMAL, " -t timeout in ms"); PrintAndLogEx(NORMAL, " -T use Topaz protocol to send command"); PrintAndLogEx(NORMAL, " -3 ISO14443-3 select only (skip RATS)"); - return PM3_SUCCESS; + return 0; } static int usage_hf_14a_reader(void) { PrintAndLogEx(NORMAL, "Usage: hf 14a reader [k|s|x] [3]"); @@ -225,7 +225,7 @@ static int usage_hf_14a_reader(void) { PrintAndLogEx(NORMAL, " s silent (no messages)"); PrintAndLogEx(NORMAL, " x just drop the signal field"); PrintAndLogEx(NORMAL, " 3 ISO14443-3 select only (skip RATS)"); - return PM3_SUCCESS; + return 0; } static int CmdHF14AList(const char *Cmd) { @@ -580,7 +580,7 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav if (resp.oldarg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision // get ATS uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 - SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0, rats, sizeof(rats)); + SendCommandOLD(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0, rats, 2); if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { if (!silentMode) PrintAndLogEx(ERR, "Proxmark3 connection timeout."); return 1; @@ -674,7 +674,7 @@ static int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { if (resp.oldarg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision // get ATS uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 - SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, sizeof(rats), 0, rats, sizeof(rats)); + SendCommandOLD(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, sizeof(rats), 0, rats, sizeof(rats)); if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { PrintAndLogEx(ERR, "Proxmark3 connection timeout."); return 1; @@ -1237,7 +1237,7 @@ static command_t CommandTable[] = { static int CmdHelp(const char *Cmd) { (void)Cmd; // Cmd is not used so far CmdsHelp(CommandTable); - return PM3_SUCCESS; + return 0; } int CmdHF14A(const char *Cmd) { @@ -1246,92 +1246,89 @@ int CmdHF14A(const char *Cmd) { } static void printTag(char *tag) { - PrintAndLogEx(SUCCESS, "POSSIBLE TYPE:" _YELLOW_(" %s"), tag); + PrintAndLogEx(SUCCESS, _YELLOW_(" %s"), tag); } typedef enum { - MTNONE = 0, - MTCLASSIC = 1, - MTMINI = 2, - MTDESFIRE = 4, - MTPLUS = 8, - MTULTRALIGHT = 16, - MTOTHER = 32 -} nxp_mifare_type_t; + mtNone = 0, + mtClassic = 1, + mtMini = 2, + mtDESFire = 4, + mtPlus = 8, + mtUltralight = 16, + mtOther = 32 +} nxp_mifare_type; // According to NXP AN10833 Rev 3.6 MIFARE Type Identification, Table 6 int detect_nxp_card(uint8_t sak, uint16_t atqa) { - int type = MTNONE; + int type = mtNone; if (sak == 0x00) { - printTag("NTAG 20x / 21x / 21x TT / I2C plus"); - printTag("MIFARE Ultralight / C / EV1 / Nano"); - type = MTULTRALIGHT; + printTag("MIFARE Ultralight C / Ultralight CL2"); + type = mtUltralight; } if (sak == 0x01) { printTag("TNP3xxx (Activision Game Appliance)"); - type = MTCLASSIC; + type = mtOther; } if ((sak & 0x04) == 0x04) { - printTag("Any MIFARE CL1 / NTAG424DNA"); - type |= MTDESFIRE; + printTag("Any MIFARE CL1"); + type |= mtDESFire; } if ((sak & 0x08) == 0x08) { printTag("MIFARE Classic 1K / Classic 1K CL2"); printTag("MIFARE Plus 2K / Plus EV1 2K"); printTag("MIFARE Plus CL2 2K / Plus CL2 EV1 2K"); - type |= MTCLASSIC; - type |= MTPLUS; + type |= mtClassic; + type |= mtPlus; } if ((sak & 0x09) == 0x09) { printTag("MIFARE Mini 0.3K / Mini CL2 0.3K"); - type |= MTMINI; + type |= mtMini; } if ((sak & 0x10) == 0x10) { printTag("MIFARE Plus 2K / Plus CL2 2K"); - type |= MTPLUS; + type |= mtPlus; } if ((sak & 0x11) == 0x11) { printTag("MIFARE Plus 4K / Plus CL2 4K"); - type |= MTPLUS; + type |= mtPlus; } if ((sak & 0x18) == 0x18) { if (atqa == 0x0042) { printTag("MIFARE Plus 4K / Plus EV1 4K"); printTag("MIFARE Plus CL2 4K / Plus CL2 EV1 4K"); - type |= MTPLUS; + type |= mtPlus; } else { printTag("MIFARE Classic 4K / Classic 4K CL2"); - type |= MTCLASSIC; + type |= mtClassic; } } if ((sak & 0x20) == 0x20) { if (atqa == 0x0344) { printTag("MIFARE DESFire EV1 2K/4K/8K / DESFire EV1 CL2 2K/4K/8K"); - printTag("MIFARE NTAG424DNA"); - type |= MTDESFIRE; - } else if (atqa == 0x0304) { - printTag("MIFARE NTAG424DNA (Random ID feature)"); - type |= MTDESFIRE; + type |= mtDESFire; } else { - printTag("MIFARE Plus 2K/4K / Plus EV1 2K/4K"); - printTag("MIFARE Plus CL2 2K/4K / Plus CL2 EV1 2K/4K"); - type |= MTPLUS; + printTag("MIFARE Plus 2K / Plus EV1 2K"); + printTag("MIFARE Plus 4K / Plus EV1 4K"); + printTag("MIFARE Plus CL2 2K / Plus CL2 EV1 4K"); + printTag("MIFARE Plus CL2 4K / Plus CL2 EV1 4K"); + type |= mtPlus; } } if ((sak & 0x24) == 0x24) { if (atqa == 0x0344) { printTag("MIFARE DESFire CL1 / DESFire EV1 CL1"); - type |= MTDESFIRE; + type |= mtDESFire; } } if ((sak & 0x28) == 0x28) { if (atqa == 0x0344) { printTag("MIFARE DESFire CL1 / DESFire EV1 CL1"); - type |= MTDESFIRE; + type |= mtDESFire; } } return type; @@ -1345,6 +1342,16 @@ typedef struct { const uidname uidmap[] = { // UID0, UID1, TEXT + {0x02, 0x00, "SR176"}, + {0x02, 0x03, "SRIX4K"}, + {0x02, 0x0C, "SRT512"}, + {0x02, 0x0F, "SRI2K"}, + {0x02, 0x1B, "25TB512-AC"}, + {0x02, 0x3D, "SRIX4K"}, + {0x02, 0x3F, "25TB02K"}, + {0x02, 0x4D, "SRIX512"}, + {0x02, 0x6D, "SRI512"}, + {0x02, 0x7D, "SRI4K"}, {0x02, 0x84, "M24SR64-Y"}, {0x02, 0xA3, "25TA02KB-P"}, {0x02, 0xC4, "25TA64K"}, @@ -1415,33 +1422,42 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { bool isMifareDESFire = false; bool isMifarePlus = false; bool isMifareUltralight = false; - int nxptype = MTNONE; + int nxptype = mtNone; // Double & triple sized UID, can be mapped to a manufacturer. if (card.uidlen <= 4) { nxptype = detect_nxp_card(card.sak, ((card.atqa[1] << 8) + card.atqa[0])); - - isMifareClassic = ((nxptype & MTCLASSIC) == MTCLASSIC); - isMifareDESFire = ((nxptype & MTDESFIRE) == MTDESFIRE); - isMifarePlus = ((nxptype & MTPLUS) == MTPLUS); - isMifareUltralight = ((nxptype & MTULTRALIGHT) == MTULTRALIGHT); - - if ((nxptype & MTOTHER) == MTOTHER) - isMifareClassic = true; + if ((nxptype & mtClassic) == mtClassic) isMifareClassic = true; + else isMifareClassic = false; + if ((nxptype & mtDESFire) == mtDESFire) { + isMifareDESFire = true; + } else { + isMifareDESFire = false; + } + if ((nxptype & mtPlus) == mtPlus) isMifarePlus = true; + else isMifarePlus = false; + if ((nxptype & mtUltralight) == mtUltralight) isMifareUltralight = true; + else isMifareUltralight = false; + if ((nxptype & mtOther) == mtOther) isMifareClassic = true; } if (card.uidlen > 4) { - PrintAndLogEx(SUCCESS, "MANUFACTURER: " _YELLOW_("%s"), getTagInfo(card.uid[0])); + PrintAndLogEx(SUCCESS, "MANUFACTURER: " _YELLOW_("%s"), getTagInfo(card.uid[0])); + + PrintAndLogEx(SUCCESS, "Possible Type:"); switch (card.uid[0]) { case 0x04: // NXP nxptype = detect_nxp_card(card.sak, ((card.atqa[1] << 8) + card.atqa[0])); - - isMifareClassic = ((nxptype & MTCLASSIC) == MTCLASSIC); - isMifareDESFire = ((nxptype & MTDESFIRE) == MTDESFIRE); - isMifarePlus = ((nxptype & MTPLUS) == MTPLUS); - isMifareUltralight = ((nxptype & MTULTRALIGHT) == MTULTRALIGHT); - - if ((nxptype & MTOTHER) == MTOTHER) - isMifareClassic = true; - + if ((nxptype & mtClassic) == mtClassic) isMifareClassic = true; + else isMifareClassic = false; + if ((nxptype & mtDESFire) == mtDESFire) { + isMifareDESFire = true; + } else { + isMifareDESFire = false; + } + if ((nxptype & mtPlus) == mtPlus) isMifarePlus = true; + else isMifarePlus = false; + if ((nxptype & mtUltralight) == mtUltralight) isMifareUltralight = true; + else isMifareUltralight = false; + if ((nxptype & mtOther) == mtOther) isMifareClassic = true; break; case 0x05: // Infineon if ((card.uid[1] & 0xF0) == 0x10) { @@ -1462,7 +1478,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { default: getTagLabel(card.uid[0], card.uid[1]); switch (card.sak) { - case 0x00: { + case 0x00: isMifareClassic = false; // ******** is card of the MFU type (UL/ULC/NTAG/ etc etc) @@ -1491,30 +1507,23 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { return select_status; } break; - } - case 0x0A: { + case 0x0A: printTag("FM11RF005SH (Shanghai Metro)"); break; - } - case 0x20: { + case 0x20: printTag("JCOP 31/41"); break; - } - case 0x28: { + case 0x28: printTag("JCOP31 or JCOP41 v2.3.1"); break; - } - case 0x38: { + case 0x38: printTag("Nokia 6212 or 6131"); break; - } - case 0x98: { + case 0x98: printTag("Gemplus MPCOS"); break; - } - default: { + default: break; - } } break; } @@ -1756,7 +1765,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes info`")); } - if (isMifareClassic || isMifareUltralight) { + if (((card.sak & 0x08) == 0x08) || ((card.sak & 0x18) == 0x18)) { detect_classic_magic(); if (isMifareClassic) { @@ -1766,7 +1775,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { else if (res == 0) PrintAndLogEx(SUCCESS, "Prng detection: " _YELLOW_("hard")); else - PrintAndLogEx(FAILED, "Prng detection: " _RED_("fail")); + PrintAndLogEx(FAILED, "prng detection: " _RED_("fail")); if (do_nack_test) detect_classic_nackbug(false); @@ -1780,6 +1789,5 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { } } - DropField(); return select_status; } diff --git a/client/cmdhflegic.c b/client/cmdhflegic.c index 5c007f9f9..c6de1379d 100644 --- a/client/cmdhflegic.c +++ b/client/cmdhflegic.c @@ -658,16 +658,6 @@ static int CmdLegicWrbl(const char *Cmd) { } } } - - // OUT-OF-BOUNDS checks - // UID 4+1 bytes can't be written to. - if (offset < 5) { - if (data) - free(data); - PrintAndLogEx(WARNING, "Out-of-bounds, bytes 0-1-2-3-4 can't be written to. Offset = %d", offset); - return PM3_EOUTOFBOUND; - } - //Validations if (errors || cmdp == 0) { if (data) @@ -684,7 +674,14 @@ static int CmdLegicWrbl(const char *Cmd) { legic_print_type(card.cardsize, 0); - if (len + offset > card.cardsize) { + // OUT-OF-BOUNDS checks + // UID 4+1 bytes can't be written to. + if (offset < 5) { + PrintAndLogEx(WARNING, "Out-of-bounds, bytes 0-1-2-3-4 can't be written to. Offset = %d", offset); + return PM3_EOUTOFBOUND; + } + + if (len + offset >= card.cardsize) { PrintAndLogEx(WARNING, "Out-of-bounds, Cardsize = %d, [offset+len = %d ]", card.cardsize, len + offset); return PM3_EOUTOFBOUND; } diff --git a/client/cmdhflist.c b/client/cmdhflist.c index 871cd68a3..b35e4d622 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -674,8 +674,7 @@ void annotateIso7816(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { // it's basically a ISO14443a tag, so try annotation from there - if (applyIso14443a(exp, size, cmd, cmdsize) == 0) { - + if (!applyIso14443a(exp, size, cmd, cmdsize)) { // S-block 11xxx010 if ((cmd[0] & 0xC0) && (cmdsize == 3)) { switch ((cmd[0] & 0x30)) { @@ -699,132 +698,123 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { } // I-block 000xCN1x else if ((cmd[0] & 0xC0) == 0x00) { - // PCB [CID] [NAD] [INF] CRC CRC int pos = 1; if ((cmd[0] & 0x08) == 0x08) // cid byte following - pos++; - + pos = pos + 1; if ((cmd[0] & 0x04) == 0x04) // nad byte following - pos++; - - for (uint8_t i = 0; i < 2; i++, pos++) { - - switch (cmd[pos]) { - case MFDES_CREATE_APPLICATION: - snprintf(exp, size, "CREATE APPLICATION"); - break; - case MFDES_DELETE_APPLICATION: - snprintf(exp, size, "DELETE APPLICATION"); - break; - case MFDES_GET_APPLICATION_IDS: - snprintf(exp, size, "GET APPLICATION IDS"); - break; - case MFDES_SELECT_APPLICATION: - snprintf(exp, size, "SELECT APPLICATION"); - break; - case MFDES_FORMAT_PICC: - snprintf(exp, size, "FORMAT PICC"); - break; - case MFDES_GET_VERSION: - snprintf(exp, size, "GET VERSION"); - break; - case MFDES_READ_DATA: - snprintf(exp, size, "READ DATA"); - break; - case MFDES_WRITE_DATA: - snprintf(exp, size, "WRITE DATA"); - break; - case MFDES_GET_VALUE: - snprintf(exp, size, "GET VALUE"); - break; - case MFDES_CREDIT: - snprintf(exp, size, "CREDIT"); - break; - case MFDES_DEBIT: - snprintf(exp, size, "DEBIT"); - break; - case MFDES_LIMITED_CREDIT: - snprintf(exp, size, "LIMITED CREDIT"); - break; - case MFDES_WRITE_RECORD: - snprintf(exp, size, "WRITE RECORD"); - break; - case MFDES_READ_RECORDS: - snprintf(exp, size, "READ RECORDS"); - break; - case MFDES_CLEAR_RECORD_FILE: - snprintf(exp, size, "CLEAR RECORD FILE"); - break; - case MFDES_COMMIT_TRANSACTION: - snprintf(exp, size, "COMMIT TRANSACTION"); - break; - case MFDES_ABORT_TRANSACTION: - snprintf(exp, size, "ABORT TRANSACTION"); - break; - case MFDES_GET_FREE_MEMORY: - snprintf(exp, size, "GET FREE MEMORY"); - break; - case MFDES_GET_FILE_IDS: - snprintf(exp, size, "GET FILE IDS"); - break; - case MFDES_GET_DF_NAMES: - snprintf(exp, size, "GET DF NAMES"); - break; - case MFDES_GET_ISOFILE_IDS: - snprintf(exp, size, "GET ISOFILE IDS"); - break; - case MFDES_GET_FILE_SETTINGS: - snprintf(exp, size, "GET FILE SETTINGS"); - break; - case MFDES_CHANGE_FILE_SETTINGS: - snprintf(exp, size, "CHANGE FILE SETTINGS"); - break; - case MFDES_CREATE_STD_DATA_FILE: - snprintf(exp, size, "CREATE STD DATA FILE"); - break; - case MFDES_CREATE_BACKUP_DATA_FILE: - snprintf(exp, size, "CREATE BACKUP DATA FILE"); - break; - case MFDES_CREATE_VALUE_FILE: - snprintf(exp, size, "CREATE VALUE FILE"); - break; - case MFDES_CREATE_LINEAR_RECORD_FILE: - snprintf(exp, size, "CREATE LINEAR RECORD FILE"); - break; - case MFDES_CREATE_CYCLIC_RECORD_FILE: - snprintf(exp, size, "CREATE CYCLIC RECORD FILE"); - break; - case MFDES_DELETE_FILE: - snprintf(exp, size, "DELETE FILE"); - break; - case MFDES_AUTHENTICATE: - snprintf(exp, size, "AUTH NATIVE (keyNo %d)", cmd[pos + 1]); - break; // AUTHENTICATE_NATIVE - case MFDES_AUTHENTICATE_ISO: - snprintf(exp, size, "AUTH ISO (keyNo %d)", cmd[pos + 1]); - break; // AUTHENTICATE_STANDARD - case MFDES_AUTHENTICATE_AES: - snprintf(exp, size, "AUTH AES (keyNo %d)", cmd[pos + 1]); - break; - case MFDES_CHANGE_KEY_SETTINGS: - snprintf(exp, size, "CHANGE KEY SETTINGS"); - break; - case MFDES_GET_KEY_SETTINGS: - snprintf(exp, size, "GET KEY SETTINGS"); - break; - case MFDES_CHANGE_KEY: - snprintf(exp, size, "CHANGE KEY"); - break; - case MFDES_GET_KEY_VERSION: - snprintf(exp, size, "GET KEY VERSION"); - break; - case MFDES_AUTHENTICATION_FRAME: - snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); - break; - default: - break; - } + pos = pos + 1; + switch (cmd[pos]) { + case MFDES_CREATE_APPLICATION: + snprintf(exp, size, "CREATE APPLICATION"); + break; + case MFDES_DELETE_APPLICATION: + snprintf(exp, size, "DELETE APPLICATION"); + break; + case MFDES_GET_APPLICATION_IDS: + snprintf(exp, size, "GET APPLICATION IDS"); + break; + case MFDES_SELECT_APPLICATION: + snprintf(exp, size, "SELECT APPLICATION"); + break; + case MFDES_FORMAT_PICC: + snprintf(exp, size, "FORMAT PICC"); + break; + case MFDES_GET_VERSION: + snprintf(exp, size, "GET VERSION"); + break; + case MFDES_READ_DATA: + snprintf(exp, size, "READ DATA"); + break; + case MFDES_WRITE_DATA: + snprintf(exp, size, "WRITE DATA"); + break; + case MFDES_GET_VALUE: + snprintf(exp, size, "GET VALUE"); + break; + case MFDES_CREDIT: + snprintf(exp, size, "CREDIT"); + break; + case MFDES_DEBIT: + snprintf(exp, size, "DEBIT"); + break; + case MFDES_LIMITED_CREDIT: + snprintf(exp, size, "LIMITED CREDIT"); + break; + case MFDES_WRITE_RECORD: + snprintf(exp, size, "WRITE RECORD"); + break; + case MFDES_READ_RECORDS: + snprintf(exp, size, "READ RECORDS"); + break; + case MFDES_CLEAR_RECORD_FILE: + snprintf(exp, size, "CLEAR RECORD FILE"); + break; + case MFDES_COMMIT_TRANSACTION: + snprintf(exp, size, "COMMIT TRANSACTION"); + break; + case MFDES_ABORT_TRANSACTION: + snprintf(exp, size, "ABORT TRANSACTION"); + break; + case MFDES_GET_FREE_MEMORY: + snprintf(exp, size, "GET FREE MEMORY"); + break; + case MFDES_GET_FILE_IDS: + snprintf(exp, size, "GET FILE IDS"); + break; + case MFDES_GET_ISOFILE_IDS: + snprintf(exp, size, "GET ISOFILE IDS"); + break; + case MFDES_GET_FILE_SETTINGS: + snprintf(exp, size, "GET FILE SETTINGS"); + break; + case MFDES_CHANGE_FILE_SETTINGS: + snprintf(exp, size, "CHANGE FILE SETTINGS"); + break; + case MFDES_CREATE_STD_DATA_FILE: + snprintf(exp, size, "CREATE STD DATA FILE"); + break; + case MFDES_CREATE_BACKUP_DATA_FILE: + snprintf(exp, size, "CREATE BACKUP DATA FILE"); + break; + case MFDES_CREATE_VALUE_FILE: + snprintf(exp, size, "CREATE VALUE FILE"); + break; + case MFDES_CREATE_LINEAR_RECORD_FILE: + snprintf(exp, size, "CREATE LINEAR RECORD FILE"); + break; + case MFDES_CREATE_CYCLIC_RECORD_FILE: + snprintf(exp, size, "CREATE CYCLIC RECORD FILE"); + break; + case MFDES_DELETE_FILE: + snprintf(exp, size, "DELETE FILE"); + break; + case MFDES_AUTHENTICATE: + snprintf(exp, size, "AUTH NATIVE (keyNo %d)", cmd[pos + 1]); + break; // AUTHENTICATE_NATIVE + case MFDES_AUTHENTICATE_ISO: + snprintf(exp, size, "AUTH ISO (keyNo %d)", cmd[pos + 1]); + break; // AUTHENTICATE_STANDARD + case MFDES_AUTHENTICATE_AES: + snprintf(exp, size, "AUTH AES (keyNo %d)", cmd[pos + 1]); + break; + case MFDES_CHANGE_KEY_SETTINGS: + snprintf(exp, size, "CHANGE KEY SETTINGS"); + break; + case MFDES_GET_KEY_SETTINGS: + snprintf(exp, size, "GET KEY SETTINGS"); + break; + case MFDES_CHANGE_KEY: + snprintf(exp, size, "CHANGE KEY"); + break; + case MFDES_GET_KEY_VERSION: + snprintf(exp, size, "GET KEY VERSION"); + break; + case MFDES_AUTHENTICATION_FRAME: + snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); + break; + default: + break; } } else { // anything else diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 931471961..1c5a0ee48 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -16,18 +16,11 @@ #include "cmdparser.h" // command_t #include "comms.h" #include "ui.h" -#include "cmdhw.h" #include "cmdhf14a.h" #include "mbedtls/des.h" #include "crypto/libpcrypto.h" #include "protocols.h" #include "mifare.h" // desfire raw command options -#include "cmdtrace.h" -#include "cliparser/cliparser.h" -#include "emv/apduinfo.h" // APDU manipulation / errorcodes -#include "emv/emvcore.h" // APDU logging -#include "util_posix.h" // msleep -#include "mifare/mifare4.h" // MIFARE Authenticate / MAC uint8_t key_zero_data[16] = { 0x00 }; uint8_t key_ones_data[16] = { 0x01 }; @@ -39,126 +32,36 @@ typedef enum { MF3ICD40, EV1, EV2, - EV3, LIGHT, } desfire_cardtype_t; -typedef struct { - uint8_t aid[3]; - uint8_t fid[2]; - uint8_t name[16]; -} dfname_t; static int CmdHelp(const char *Cmd); -/* - uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; - int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); - if (!res && datalen > 1 && data[0] == 0x09) { - SLmode = 0; - } +static int SendDesfireCmd(uint8_t *c, size_t len, int p0, int p1, int p2, PacketResponseNG *response, int timeout) { + PacketResponseNG resp; -*/ + if (response == NULL) + response = &resp; -int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { + clearCommandBuffer(); + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, p0, p1, p2, c, len); - *result_len = 0; - if (sw) *sw = 0; - - uint16_t isw = 0; - int res = 0; - - if (activate_field) { + if (!WaitForResponseTimeout(CMD_ACK, response, timeout)) { + PrintAndLogEx(WARNING, "[SendDesfireCmd] Timed-out: " _RED_("%s"), sprint_hex(c, len)); DropField(); - msleep(50); + return PM3_ETIMEOUT; } - // select? - uint8_t data[APDU_RES_LEN] = {0}; - - // COMPUTE APDU - int datalen = 0; - //if (APDUEncodeS(&apdu, false, IncludeLe ? 0x100 : 0x00, data, &datalen)) { - if (APDUEncodeS(&apdu, false, 0x100, data, &datalen)) { - PrintAndLogEx(ERR, "APDU encoding error."); - return PM3_EAPDU_ENCODEFAIL; + uint8_t isOK = response->data.asBytes[0] & 0xff; + if (!isOK) { + PrintAndLogEx(WARNING, "[SendDesfireCmd] Unsuccessful: " _RED_("%s"), sprint_hex(c, len)); + return PM3_ESOFT; } - - if (GetAPDULogging() || (g_debugMode > 1)) - PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen)); - - res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, result_len); - if (res) { - return res; - } - - if (GetAPDULogging() || (g_debugMode > 1)) - PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(result, *result_len)); - - if (*result_len < 2) { - return PM3_SUCCESS; - } - - *result_len -= 2; - isw = (result[*result_len] << 8) + result[*result_len + 1]; - if (sw) - *sw = isw; - - if (isw != 0x9000 && isw != MFDES_SUCCESS_FRAME_RESP && isw != MFDES_ADDITIONAL_FRAME_RESP) { - if (GetAPDULogging()) { - if (isw >> 8 == 0x61) { - PrintAndLogEx(ERR, "APDU chaining len:%02x -->", isw & 0xff); - } else { - PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); - return PM3_EAPDU_FAIL; - } - } - } - return PM3_SUCCESS; } - -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize) { - //SetAPDULogging(true); - *sw = 0; - uint8_t data[255 * 5] = {0x00}; - int resplen = 0; - int pos = 0; - int i = 1; - int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; - if (*sw != MFDES_ADDITIONAL_FRAME_RESP && *sw != MFDES_SUCCESS_FRAME_RESP) return PM3_ESOFT; - if (dest != NULL) { - memcpy(dest, data, resplen); - } - - pos += resplen; - if (*sw == MFDES_ADDITIONAL_FRAME_RESP) { - apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF - - res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; - if (dest != NULL) { - if (splitbysize) { - memcpy(&dest[i * splitbysize], data, resplen); - i += 1; - } else { - memcpy(&dest[pos], data, resplen); - } - } - pos += resplen; - } - if (splitbysize) *recv_len = i; - else { - *recv_len = pos; - } - //SetAPDULogging(false); - return PM3_SUCCESS; - -} - static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { if (major == 0x00) @@ -167,39 +70,59 @@ static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { return EV1; else if (major == 0x12 && minor == 0x00) return EV2; -// else if (major == 0x13 && minor == 0x00) -// return EV3; else if (major == 0x30 && minor == 0x00) return LIGHT; else return UNKNOWN; } +//ICEMAN: Turn on field method? //none static int test_desfire_authenticate() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + uint8_t c[] = {AUTHENTICATE, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x0A, KEY 0 + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); + PacketResponseNG resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + DropField(); + return PM3_ETIMEOUT; + } + if (resp.length == 13) + return PM3_SUCCESS; + return PM3_ESOFT; } - // none static int test_desfire_authenticate_iso() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + uint8_t c[] = {AUTHENTICATE_ISO, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x1A, KEY 0 + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); + PacketResponseNG resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + DropField(); + return PM3_ETIMEOUT; + } + if (resp.length >= 13) + return PM3_SUCCESS; + return PM3_ESOFT; } - //none static int test_desfire_authenticate_aes() { - uint8_t data[] = {0x00}; - sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 - int recv_len = 0; - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + /* Just left here for future use, from TI TRF7970A sloa213 document + const static u08_t CustomKey1[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + const static u08_t CustomKey2[16] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, + 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}; + const static u08_t CustomKey3[16] = {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, + 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}; + */ + uint8_t c[] = {AUTHENTICATE_AES, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0xAA, KEY 0 + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); + PacketResponseNG resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + DropField(); + return PM3_ETIMEOUT; + } + if (resp.length >= 13) + return PM3_SUCCESS; + return PM3_ESOFT; } // --- FREE MEM @@ -210,18 +133,20 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { - sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E - int recv_len = 0; - uint16_t sw = 0; - uint8_t fmem[4] = {0}; - - int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0); - if (res == PM3_SUCCESS) { - *free_mem = le24toh(fmem); - return res; + uint8_t c[] = {GET_FREE_MEMORY, 0x00, 0x00, 0x00}; // 0x6E + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, (INIT | DISCONNECT), sizeof(c), 0, c, sizeof(c)); + PacketResponseNG resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + return PM3_ETIMEOUT; } + + if (resp.length == 8) { + *free_mem = le24toh(resp.data.asBytes + 1); + return PM3_SUCCESS; + } + *free_mem = 0; - return res; + return PM3_ESOFT; } @@ -236,9 +161,9 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"NTAG424DNA, DESFire EV2", "048A9B380AF2EE1B98DC417FECC263F8449C7625CECE82D9B916C992DA209D68422B81EC20B65A66B5102A61596AF3379200599316A00A1410"}, {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, - {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, + {"NTAG424DNA,NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, - {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} + {"Mifare Plus", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; uint8_t i; @@ -263,41 +188,36 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); - PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); + PrintAndLogEx(INFO, " IC signature public key name: %s", nxp_desfire_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 32); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 48); PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); - PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); - PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); + PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex(signature, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 16, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 32, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 48, signature_len - 48)); + PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); return PM3_SUCCESS; } // init / disconnect static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C - int recv_len = 0; - uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0); - if (res == PM3_SUCCESS) { - if (recv_len != 56) { - *signature_len = 0; - DropField(); - return PM3_ESOFT; - } else { - *signature_len = recv_len; + uint8_t c[] = {MFDES_READSIG, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x3C + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, (INIT | DISCONNECT), sizeof(c), 0, c, sizeof(c)); + PacketResponseNG resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) + return PM3_ETIMEOUT; - } - DropField(); + if (resp.length == 61) { + memcpy(signature, resp.data.asBytes + 1, 56); + *signature_len = 56; return PM3_SUCCESS; + } else { + *signature_len = 0; + return PM3_ESOFT; } - DropField(); - return res; } @@ -335,21 +255,18 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 - int recv_len = 0; - uint16_t sw = 0; - uint8_t data[2] = {0}; - if (num_keys == NULL) return PM3_ESOFT; - if (key_settings == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); - if (sw == MFDES_EAUTH_RESP) { + PacketResponseNG resp; + uint8_t c[] = {MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00}; // 0x45 + int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); + if (ret != PM3_SUCCESS) return ret; + + if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0xae) { PrintAndLogEx(WARNING, _RED_("[get_desfire_keysettings] Authentication error")); return PM3_ESOFT; } - if (res != PM3_SUCCESS) return res; - - *key_settings = data[0]; - *num_keys = data[1]; +// PrintAndLogEx(INFO, "ICE: KEYSETTING resp :: %s", sprint_hex(resp.data.asBytes, resp.length)); + *key_settings = resp.data.asBytes[1]; + *num_keys = resp.data.asBytes[2]; return PM3_SUCCESS; } @@ -361,72 +278,83 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { // none static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 - int recv_len = 0; - uint16_t sw = 0; - if (num_versions == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); - if (sw == MFDES_ENO_SUCH_KEY_RESP) { - PrintAndLogEx(WARNING, _RED_("[get_desfire_keyversion] Key %d doesn't exist"), curr_key); + PacketResponseNG resp; + uint8_t c[] = {MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, curr_key, 0x00}; // 0x64 + int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); + if (ret != PM3_SUCCESS) return ret; + + if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0x40) { return PM3_ESOFT; } - return res; -} - -// init / disconnect -static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { - sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a - int recv_len = 0; - uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (app_ids_len == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0); - if (res != PM3_SUCCESS) return res; - *app_ids_len = (uint8_t)recv_len & 0xFF; - return res; -} - -static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { - sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d - int recv_len = 0; - uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (dfname_count == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t)); - if (res != PM3_SUCCESS) return res; - *dfname_count = recv_len; - return res; + *num_versions = resp.data.asBytes[1]; + return PM3_SUCCESS; } // init static int get_desfire_select_application(uint8_t *aid) { - sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a - int recv_len = 0; - uint16_t sw = 0; if (aid == NULL) return PM3_ESOFT; - return send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); + + uint8_t c[] = {SELECT_APPLICATION, 0x00, 0x00, 0x03, aid[0], aid[1], aid[2], 0x00}; // 0x5a + PacketResponseNG resp; + int ret = SendDesfireCmd(c, sizeof(c), INIT, sizeof(c), 0, &resp, 3000); + if (ret != PM3_SUCCESS) { + if (ret == PM3_ESOFT) { + PrintAndLogEx(WARNING, "[get_desfire_select_application] Can't select AID: " _RED_("%s"), sprint_hex(aid, 3)); + } + return ret; + } + + if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0x00) { + return PM3_SUCCESS; + } + + return PM3_ESOFT; } + +// init / disconnect +static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + + uint8_t c[] = {GET_APPLICATION_IDS, 0x00, 0x00, 0x00}; //0x6a + PacketResponseNG resp; + int ret = SendDesfireCmd(c, sizeof(c), INIT | CLEARTRACE | DISCONNECT, sizeof(c), 0, &resp, 1500); + if (ret != PM3_SUCCESS) return ret; + + *app_ids_len = resp.length - 5; + + // resp.length - 2crc, 2status, 1pcb... + memcpy(dest, resp.data.asBytes + 1, *app_ids_len); + + if (resp.data.asBytes[resp.length - 3] == MFDES_ADDITIONAL_FRAME) { + + c[0] = MFDES_ADDITIONAL_FRAME; //0xAF + ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); + if (ret != PM3_SUCCESS) return ret; + + memcpy(dest + *app_ids_len, resp.data.asBytes + 1, resp.length - 5); + + *app_ids_len += (resp.length - 5); + } + return PM3_SUCCESS; +} + + // none static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { - sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f - int recv_len = 0; - uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (file_ids_len == NULL) return PM3_ESOFT; - *file_ids_len = 0; - int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); - if (res != PM3_SUCCESS) return res; - *file_ids_len = recv_len; - return res; -} + uint8_t c[] = {MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00}; // 0x6f + PacketResponseNG resp; + int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); + if (ret != PM3_SUCCESS) return ret; -static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { - sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 - uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); + if (resp.data.asBytes[resp.length - 4] == 0x91 && resp.data.asBytes[resp.length - 3] == 0x00) { + *file_ids_len = resp.length - 5; + memcpy(dest, resp.data.asBytes + 1, *file_ids_len); + return PM3_SUCCESS; + } + + return PM3_ESOFT; } static int CmdHF14ADesInfo(const char *Cmd) { @@ -502,13 +430,11 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (major == 0 && minor == 6) PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); if (major == 1 && minor == 3) - PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); + PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1, Support extended APDU commands"); if (major == 1 && minor == 4) - PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); + PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1, N/A information about this version. report to iceman!"); if (major == 2 && minor == 0) - PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); -// if (major == 3 && minor == 0) -// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); + PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check"); if (major == 0 && minor == 2) PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); @@ -600,8 +526,6 @@ char *getVersionStr(uint8_t major, uint8_t minor) { sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); else if (major == 0x12 && minor == 0x00) sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); -// else if (major == 0x13 && minor == 0x00) -// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); else if (major == 0x30 && minor == 0x00) sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); else @@ -614,7 +538,9 @@ void getKeySettings(uint8_t *aid) { if (memcmp(aid, "\x00\x00\x00", 3) == 0) { // CARD MASTER KEY - //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + if (get_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't select AID")); DropField(); @@ -677,7 +603,9 @@ void getKeySettings(uint8_t *aid) { } else { // AID - APPLICATION MASTER KEYS - //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + if (get_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't select AID")); DropField(); @@ -723,25 +651,15 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { (void)Cmd; // Cmd is not used so far // uint8_t isOK = 0x00; - uint8_t aid[3] = {0}; + uint8_t aid[3]; uint8_t app_ids[78] = {0}; uint8_t app_ids_len = 0; uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; - dfname_t dfnames[255]; - uint8_t dfname_count = 0; - if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); - DropField(); - return PM3_ESOFT; - } - - if (get_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_("Can't get DF Names")); - DropField(); return PM3_ESOFT; } @@ -756,49 +674,18 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { aid[1] = app_ids[i + 1]; aid[2] = app_ids[i + 2]; - PrintAndLogEx(NORMAL, ""); - - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - // CARD MASTER KEY - PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - } else { - PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - } - - PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X %02X %02X"), aid[0], aid[1], aid[2]); - for (int m = 0; m < dfname_count; m++) { - if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { - PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X %02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[0], dfnames[m].fid[1], dfnames[m].name); - } - } + PrintAndLogEx(SUCCESS, " AID %d : " _GREEN_("%02X %02X %02X"), i, app_ids[i], app_ids[i + 1], app_ids[i + 2]); getKeySettings(aid); - - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } - // Get File IDs if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); for (int j = 0; j < file_ids_len; ++j) { PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); - - uint8_t filesettings[20] = {0}; - int fileset_len = 0; - int res = get_desfire_filesettings(j, filesettings, &fileset_len); - if (res == PM3_SUCCESS) { - PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); - } } } - - - /* // Get ISO File IDs { @@ -826,90 +713,70 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { DropField(); return PM3_SUCCESS; } +/* + uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; + int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); + + if (!res && datalen > 1 && data[0] == 0x09) { + SLmode = 0; + } + +*/ + + // MIAFRE DESFire Authentication // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { - clearCommandBuffer(); + // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 // 2 = 3DES 16 // 3 = 3K 3DES 24 // 4 = AES 16 - //SetAPDULogging(true); + uint8_t keylength = 8; + unsigned char key[24]; - CLIParserInit("hf mfdes auth", - "Authenticates Mifare DESFire using Key", - "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes auth -m 3 -t 4 -a 018380 -n 0 -k 404142434445464748494a4b4c4d4e4f\n" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), - arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), - arg_strx0("aA", "aid", "", "AID used for authentification"), - arg_int0("nN", "keyno", "Key number used for authentification", NULL), - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, true); - - uint8_t cmdAuthMode = arg_get_int_def(1, 0); - uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); - - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(3, aid, &aidlength); - - uint8_t cmdKeyNo = arg_get_int_def(4, 0); - - uint8_t key[24] = {0}; - int keylen = 0; - CLIGetHexWithReturn(5, key, &keylen); - CLIParserFree(); - - if ((keylen < 8) || (keylen > 24)) { - PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); - //SetAPDULogging(false); - return PM3_EINVARG; - } - - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - //SetAPDULogging(false); - return PM3_EINVARG; + if (strlen(Cmd) < 3) { + PrintAndLogEx(NORMAL, "Usage: hf mfdes auth <1|2|3> <1|2|3|4> "); + PrintAndLogEx(NORMAL, " Auth modes"); + PrintAndLogEx(NORMAL, " 1 = normal, 2 = iso, 3 = aes"); + PrintAndLogEx(NORMAL, " Crypto"); + PrintAndLogEx(NORMAL, " 1 = DES 2 = 3DES 3 = 3K3DES 4 = AES"); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, "Examples:"); + PrintAndLogEx(NORMAL, _YELLOW_(" hf mfdes auth 1 1 0 11223344")); + PrintAndLogEx(NORMAL, _YELLOW_(" hf mfdes auth 3 4 0 404142434445464748494a4b4c4d4e4f")); + return PM3_SUCCESS; } + uint8_t cmdAuthMode = param_get8(Cmd, 0); + uint8_t cmdAuthAlgo = param_get8(Cmd, 1); + uint8_t cmdKeyNo = param_get8(Cmd, 2); switch (cmdAuthMode) { case 1: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; case 2: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; case 3: if (cmdAuthAlgo != 4) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; default: - PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - //SetAPDULogging(false); + PrintAndLogEx(WARNING, "Wrong Auth mode"); return PM3_EINVARG; } @@ -933,37 +800,21 @@ static int CmdHF14ADesAuth(const char *Cmd) { break; } - // KEY - if (keylen != keylength) { + // key + if (param_gethex(Cmd, 3, key, keylength * 2)) { PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); return PM3_EINVARG; } - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } - - uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; - int res = get_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Get file ids error."); - DropField(); - return res; - } - - // algo, keylength, uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) memcpy(data + 1, key, keylength); + clearCommandBuffer(); SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); PacketResponseNG resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { PrintAndLogEx(WARNING, "Client command execute timeout"); - DropField(); return PM3_ETIMEOUT; } @@ -982,15 +833,9 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_SUCCESS; } -static int CmdHF14ADesList(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - return CmdTraceList("des"); -} - static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"info", CmdHF14ADesInfo, IfPm3Iso14443a, "Tag information"}, - {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index 4f6605cff..5c4dcb5e2 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -19,14 +19,50 @@ char *getProtocolStr(uint8_t id); char *getVersionStr(uint8_t major, uint8_t minor); void getKeySettings(uint8_t *aid); -// Ev1 card limits +#define CREATE_APPLICATION 0xca +#define DELETE_APPLICATION 0xda +#define GET_APPLICATION_IDS 0x6a +#define SELECT_APPLICATION 0x5a +#define FORMAT_PICC 0xfc +#define GET_VERSION 0x60 +#define READ_DATA 0xbd +#define WRITE_DATA 0x3d +#define GET_VALUE 0x6c +#define CREDIT 0x0c +#define DEBIT 0xdc +#define LIMITED_CREDIT 0x1c +#define WRITE_RECORD 0x3b +#define READ_RECORDS 0xbb +#define CLEAR_RECORD_FILE 0xeb +#define COMMIT_TRANSACTION 0xc7 +#define ABORT_TRANSACTION 0xa7 +#define GET_FREE_MEMORY 0x6e +#define GET_FILE_IDS 0x6f +#define GET_ISOFILE_IDS 0x61 +#define GET_FILE_SETTINGS 0xf5 +#define CHANGE_FILE_SETTINGS 0x5f +#define CREATE_STD_DATA_FILE 0xcd +#define CREATE_BACKUP_DATA_FILE 0xcb +#define CREATE_VALUE_FILE 0xcc +#define CREATE_LINEAR_RECORD_FILE 0xc1 +#define CREATE_CYCLIC_RECORD_FILE 0xc0 +#define DELETE_FILE 0xdf +#define AUTHENTICATE 0x0a // AUTHENTICATE_NATIVE +#define AUTHENTICATE_ISO 0x1a // AUTHENTICATE_STANDARD +#define AUTHENTICATE_AES 0xaa +#define CHANGE_KEY_SETTINGS 0x54 +#define GET_KEY_SETTINGS 0x45 +#define CHANGE_KEY 0xc4 +#define GET_KEY_VERSION 0x64 +#define AUTHENTICATION_FRAME 0xAF + #define MAX_NUM_KEYS 0x0F #define MAX_APPLICATION_COUNT 28 #define MAX_FILE_COUNT 32 #define MAX_FRAME_SIZE 60 +#define NOT_YET_AUTHENTICATED 255 #define FRAME_PAYLOAD_SIZE (MAX_FRAME_SIZE - 5) -#define NOT_YET_AUTHENTICATED 0xFF // status- and error codes | #define OPERATION_OK 0x00 // Successful operation diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index 71da93bcc..56963819c 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -10,9 +10,12 @@ //----------------------------------------------------------------------------- #include "cmdhfmfp.h" + #include + #include "cmdparser.h" // command_t #include "commonutil.h" // ARRAYLEN + #include "comms.h" #include "ui.h" #include "cmdhf14a.h" @@ -24,9 +27,6 @@ #include "mifare/mifaredefault.h" #include "util_posix.h" #include "fileutils.h" -#include "protocols.h" -#include "crypto/libpcrypto.h" - static const uint8_t DefaultKey[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; @@ -34,188 +34,21 @@ uint16_t CardAddresses[] = {0x9000, 0x9001, 0x9002, 0x9003, 0x9004, 0xA000, 0xA0 static int CmdHelp(const char *Cmd); -/* - The 7 MSBits (= n) code the storage size itself based on 2^n, - the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). - For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. -*/ -static char *getCardSizeStr(uint8_t fsize) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - uint16_t usize = 1 << ((fsize >> 1) + 1); - uint16_t lsize = 1 << (fsize >> 1); - - // is LSB set? - if (fsize & 1) - sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); - return buf; -} - -static char *getProtocolStr(uint8_t id) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); - return buf; -} - -static char *getVersionStr(uint8_t major, uint8_t minor) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (major == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); - else if (major == 0x01 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); - else if (major == 0x12 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); -// else if (major == 0x13 && minor == 0x00) -// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); - else if (major == 0x30 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); - - else if (major == 0x11 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("Plus EV1") ")", major, minor); - else - sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); - return buf; -} - -// --- GET SIGNATURE -static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature, int signature_len) { - - // ref: MIFARE Plus EV1 Originality Signature Validation - #define PUBLIC_PLUS_ECDA_KEYLEN 57 - const ecdsa_publickey_t nxp_plus_public_keys[] = { - {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} - }; - - uint8_t i; - int res; - bool is_valid = false; - - for (i = 0; i < ARRAYLEN(nxp_plus_public_keys); i++) { - - int dl = 0; - uint8_t key[PUBLIC_PLUS_ECDA_KEYLEN]; - param_gethex_to_eol(nxp_plus_public_keys[i].value, 0, key, PUBLIC_PLUS_ECDA_KEYLEN, &dl); - - res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP224R1, key, uid, uidlen, signature, signature_len, false); - is_valid = (res == 0); - if (is_valid) - break; - } - if (is_valid == false) { - PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); - return PM3_ESOFT; - } - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); - PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_plus_public_keys[i].desc); - PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_plus_public_keys[i].value); - PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 16); - PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 32); - PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 48); - PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); - PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); - PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); - return PM3_SUCCESS; -} - -static int get_plus_signature(uint8_t *signature, int *signature_len) { - - mfpSetVerboseMode(false); - - uint8_t data[59] = {0}; - int resplen = 0, retval = PM3_SUCCESS; - MFPGetSignature(true, false, data, sizeof(data), &resplen); - - if (resplen == 59) { - memcpy(signature, data + 1, 56); - *signature_len = 56; - } else { - *signature_len = 0; - retval = PM3_ESOFT; - } - mfpSetVerboseMode(false); - return retval; -} -// GET VERSION -static int plus_print_version(uint8_t *version) { - PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(version + 14, 7)); - PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(version + 21, 5)); - PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), version[7+7+7+5], version[7+7+7+5+1]); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); - PrintAndLogEx(INFO, " Version: %s", getVersionStr(version[3], version[4])); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); - PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[3], version[4]); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); - return PM3_SUCCESS; -} -static int get_plus_version(uint8_t *version, int *version_len) { - - int resplen = 0, retval = PM3_SUCCESS; - mfpSetVerboseMode(false); - MFPGetVersion(true, false, version, *version_len, &resplen); - mfpSetVerboseMode(false); - - *version_len = resplen; - if (resplen != 28) { - retval = PM3_ESOFT; - } - return retval; -} - static int CmdHFMFPInfo(const char *Cmd) { if (Cmd && strlen(Cmd) > 0) PrintAndLogEx(WARNING, "command don't have any parameters.\n"); PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); + PrintAndLogEx(INFO, "-- Mifare Plus Tag Information ------------------------------"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); - bool supportVersion = false; - bool supportSignature = false; + // info about 14a part + infoHF14A(false, false, false); - // version check - uint8_t version[30] = {0}; - int version_len = sizeof(version); - if (get_plus_version(version, &version_len) == PM3_SUCCESS) { - plus_print_version(version); - supportVersion = true; - } else { - // info about 14a part - infoHF14A(false, false, false); - } - // Mifare Plus info SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_CONNECT, 0, 0, NULL, 0); + PacketResponseNG resp; WaitForResponse(CMD_ACK, &resp); @@ -224,60 +57,55 @@ static int CmdHFMFPInfo(const char *Cmd) { uint64_t select_status = resp.oldarg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - // Signature originality check - uint8_t signature[56] = {0}; - int signature_len = sizeof(signature); - if (get_plus_signature(signature, &signature_len) == PM3_SUCCESS) { - plus_print_signature(card.uid, card.uidlen, signature, signature_len); - supportSignature = true; - } - if (select_status == 1 || select_status == 2) { - PrintAndLogEx(INFO, "--- " _CYAN_("Fingerprint")); - - if (supportVersion && supportSignature) { - PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); - } else { - PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); - } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(INFO, " Fingerprint"); // MIFARE Type Identification Procedure // https://www.nxp.com/docs/en/application-note/AN10833.pdf uint16_t ATQA = card.atqa[0] + (card.atqa[1] << 8); bool isPlus = false; - if (ATQA & 0x0004) { - PrintAndLogEx(INFO, " SIZE: " _GREEN_("2K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); + if (ATQA == 0x0004) { + PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 2K") " (4b UID)"); isPlus = true; } - if (ATQA & 0x0002) { - PrintAndLogEx(INFO, " SIZE: " _GREEN_("4K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); + if (ATQA == 0x0002) { + PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 4K") " (4b UID)"); + isPlus = true; + } + if (ATQA == 0x0044) { + PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 2K") " (7b UID)"); + isPlus = true; + } + if (ATQA == 0x0042) { + PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 4K") " (7b UID)"); isPlus = true; } - uint8_t SLmode = 0xFF; + uint8_t SLmode = 0xff; if (isPlus) { if (card.sak == 0x08) { - PrintAndLogEx(INFO, " SAK: " _GREEN_("2K 7b UID")); + PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 2K 7b UID")); if (select_status == 2) SLmode = 1; } if (card.sak == 0x18) { - PrintAndLogEx(INFO, " SAK: " _GREEN_("4K 7b UID")); + PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 4K 7b UID")); if (select_status == 2) SLmode = 1; } if (card.sak == 0x10) { - PrintAndLogEx(INFO, " SAK: " _GREEN_("2K")); + PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 2K")); if (select_status == 2) SLmode = 2; } if (card.sak == 0x11) { - PrintAndLogEx(INFO, " SAK: " _GREEN_("4K")); + PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 4K")); if (select_status == 2) SLmode = 2; } } if (card.sak == 0x20) { - PrintAndLogEx(INFO, " SAK: " _GREEN_("MIFARE Plus SL0/SL3") "or " _GREEN_("MIFARE DESFire")); + PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus SL0/SL3") "or " _GREEN_("Mifare DESFire")); if (card.ats_len > 0) { @@ -290,7 +118,7 @@ static int CmdHFMFPInfo(const char *Cmd) { int res = ExchangeRAW14a(cmd, sizeof(cmd), true, false, data, sizeof(data), &datalen, false); if (memcmp(data, "\x67\x00", 2) == 0) { - PrintAndLogEx(INFO, "\tMost likely a MIFARE DESFire tag"); + PrintAndLogEx(INFO, "\tMost likely a Mifare DESFire tag"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfdes info`")); DropField(); return PM3_SUCCESS; @@ -302,35 +130,33 @@ static int CmdHFMFPInfo(const char *Cmd) { } } - if (isPlus) { - // How do we detect SL0 / SL1 / SL2 / SL3 modes?!? - PrintAndLogEx(INFO, "--- " _CYAN_("Security Level (SL)")); - - if (SLmode != 0xFF ) - PrintAndLogEx(SUCCESS, " SL mode: " _YELLOW_("SL%d"), SLmode); - else - PrintAndLogEx(WARNING, " SL mode: " _YELLOW_("unknown")); - switch(SLmode) { - case 0: - PrintAndLogEx(INFO, " SL 0: initial delivery configuration, used for card personalization"); - break; - case 1: - PrintAndLogEx(INFO, " SL 1: backwards functional compatibility mode (with MIFARE Classic 1K / 4K) with an optional AES authentication"); - break; - case 2: - PrintAndLogEx(INFO, " SL 2: 3-Pass Authentication based on AES followed by MIFARE CRYPTO1 authentication, communication secured by MIFARE CRYPTO1"); - break; - case 3: - PrintAndLogEx(INFO, " SL 3: 3-Pass authentication based on AES, data manipulation commands secured by AES encryption and an AES based MACing method."); - break; - default: - break; - } + // How do we detect SL0 / SL1 / SL2 / SL3 modes?!? + PrintAndLogEx(INFO, "Security Level (SL)"); + switch(SLmode) { + case 0: + PrintAndLogEx(INFO, "SL 0: initial delivery configuration, used for card personalization"); + break; + case 1: + PrintAndLogEx(INFO, "SL 1: backwards functional compatibility mode (with MIFARE Classic 1K / 4K) with an optional AES authentication"); + break; + case 2: + PrintAndLogEx(INFO, "SL 2: 3-Pass Authentication based on AES followed by MIFARE CRYPTO1 authentication, communication secured by MIFARE CRYPTO1"); + break; + case 3: + PrintAndLogEx(INFO, "SL 3: 3-Pass authentication based on AES, data manipulation commands secured by AES encryption and an AES based MACing method."); + break; + default: + break; } + + if (SLmode != 0xFF) + PrintAndLogEx(SUCCESS, "\tMifare Plus SL mode: " _YELLOW_("SL%d"), SLmode); + else + PrintAndLogEx(WARNING, "\tMifare Plus SL mode: " _YELLOW_("unknown")); } else { PrintAndLogEx(INFO, "\tMifare Plus info not available."); } - PrintAndLogEx(NORMAL, ""); + DropField(); return PM3_SUCCESS; } diff --git a/client/emv/apduinfo.c b/client/emv/apduinfo.c index b64696628..35735fb47 100644 --- a/client/emv/apduinfo.c +++ b/client/emv/apduinfo.c @@ -503,17 +503,7 @@ void APDUPrint(APDUStruct apdu) { void APDUPrintEx(APDUStruct apdu, size_t maxdatalen) { PrintAndLogEx(INFO, "APDU: %scase=0x%02x cla=0x%02x ins=0x%02x p1=0x%02x p2=0x%02x Lc=0x%02x(%d) Le=0x%02x(%d)", - apdu.extended_apdu ? "[e]" : "", - apdu.case_type, - apdu.cla, - apdu.ins, - apdu.p1, - apdu.p2, - apdu.lc, - apdu.lc, - apdu.le, - apdu.le - ); + apdu.extended_apdu ? "[e]" : "", apdu.case_type, apdu.cla, apdu.ins, apdu.p1, apdu.p2, apdu.lc, apdu.lc, apdu.le, apdu.le); if (maxdatalen > 0) PrintAndLogEx(INFO, "data: %s%s", sprint_hex(apdu.data, MIN(apdu.lc, maxdatalen)), apdu.lc > maxdatalen ? "..." : ""); } diff --git a/client/emv/emvcore.c b/client/emv/emvcore.c index 852d801c7..fe5ff3a31 100644 --- a/client/emv/emvcore.c +++ b/client/emv/emvcore.c @@ -136,10 +136,6 @@ void SetAPDULogging(bool logging) { APDULogging = logging; } -bool GetAPDULogging(void) { - return APDULogging; -} - enum CardPSVendor GetCardPSVendor(uint8_t *AID, size_t AIDlen) { char buf[100] = {0}; if (AIDlen < 1) diff --git a/client/emv/emvcore.h b/client/emv/emvcore.h index 1c422e483..d5dccd037 100644 --- a/client/emv/emvcore.h +++ b/client/emv/emvcore.h @@ -57,7 +57,6 @@ struct tlvdb *GetPANFromTrack2(const struct tlv *track2); struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2); void SetAPDULogging(bool logging); -bool GetAPDULogging(void); // exchange int EMVExchange(EMVCommandChannel channel, bool LeaveFieldON, sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv); diff --git a/client/luascripts/legic.lua b/client/luascripts/legic.lua index 393cc9e52..7e0f8d3be 100644 --- a/client/luascripts/legic.lua +++ b/client/luascripts/legic.lua @@ -91,20 +91,14 @@ CRC1 = crc8 over addr 0x00..0x03+0x07..0x0E (special 'gantner crc8') CRC2 = MCD + MSB0..2+ addr 0x06 + addr 0x05 + addr 0x07 + Stamp (regular Master-Token-CRC) --]] ---[[ -Known issues; needs to be fixed: -* last byte in last segment is handled incorrectly when it is the last bytes on the card itself (MIM256: => byte 256) ---]] - example = "script run legic" -author = "Mosci, uhei" -version = "1.0.4" +author = "Mosci" +version = "1.0.3" desc = [[ This script helps you to read, create and modify Legic Prime Tags (MIM22, MIM256, MIM1024) -The virtual tag (and therefore the file to be saved) is always a MIM1024 tag. it's kinda interactive with following commands in three categories: Data I/O Segment Manipulation Token-Data @@ -114,8 +108,8 @@ it's kinda interactive with following commands in three categories: ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load bin File ck => check KGH - sf => save eml/bin File ds => dump Segments + lf => load File ck => check KGH + sf => save File ds => dump Segments xf => xor to File @@ -134,8 +128,8 @@ it's kinda interactive with following commands in three categories: without the need of changing anything - MCD,MSN,MCC will be read from the tag before and applied to the output. - lf: 'load file' - load a (xored) binary file (*.bin) from the local Filesystem into the 'virtual inTag' - sf: 'save file' - saves the 'virtual inTag' to the local Filesystem as eml and bin (xored with Tag-MCC) + lf: 'load file' - load a (xored) file from the local Filesystem into the 'virtual inTag' + sf: 'save file' - saves the 'virtual inTag' to the local Filesystem (xored with Tag-MCC) xf: 'xor file' - saves the 'virtual inTag' to the local Filesystem (xored with choosen MCC - use '00' for plain values) ct: 'copy tag' - copy the 'virtual Tag' to a second 'virtual TAG' - not usefull yet, but inernally needed @@ -248,16 +242,6 @@ function istable(t) return type(t) == 'table' end ---- --- To have two char string for a byte -local function padString(str) - if (#str == 1) then - return '0'..str - end - - return str -end - --- -- creates a 'deep copy' of a table (a=b only references) function deepCopy(object) @@ -403,15 +387,15 @@ end function bytesToTag(bytes, tag) if istable(tag) == false then return oops("tag is no table in: bytesToTag ("..type(tag)..")") end - tag.MCD =padString(bytes[1]); - tag.MSN0=padString(bytes[2]); - tag.MSN1=padString(bytes[3]); - tag.MSN2=padString(bytes[4]); - tag.MCC =padString(bytes[5]); - tag.DCFl=padString(bytes[6]); - tag.DCFh=padString(bytes[7]); - tag.raw =padString(bytes[8]); - tag.SSC =padString(bytes[9]); + tag.MCD =bytes[1]; + tag.MSN0=bytes[2]; + tag.MSN1=bytes[3]; + tag.MSN2=bytes[4]; + tag.MCC =bytes[5]; + tag.DCFl=bytes[6]; + tag.DCFh=bytes[7]; + tag.raw =bytes[8]; + tag.SSC =bytes[9]; tag.Type=getTokenType(tag.DCFl); tag.OLE=bbit("0x"..tag.DCFl,7,1) tag.WRP=("%d"):format(bbit("0x"..bytes[8],0,4)) @@ -516,26 +500,42 @@ function tagToBytes(tag) return bytes end +--- PM3 I/O --- +--- +-- read from pm3 into virtual-tag +function readFromPM3() + local tag, bytes, infile + infile="legic.temp" + -- core.console("hf legic reader") + -- core.console("hf legic esave "..infile) + core.console("hf legic dump o "..infile) + tag=readFile(infile..".bin") + return tag +end + +local function padString(str) + if (#str == 1) then + return '0'..str + end + + return str +end --- ---- PM3 I/O --- -- write virtual Tag to real Tag function writeToTag(tag) local bytes + local filename = 'MylegicClone.hex' local taglen = 22 - local writeDCF = false - if(utils.confirm(acred.."\nPlace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then + if(utils.confirm(acred.."\nplace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then return end - if(utils.confirm(acred.."\nShould the decremental field (DCF) be written?: "..acoff) == true) then - writeDCF = true - end -- get used bytes / tag-len if (istable(tag.SEG)) then if (istable(tag.Bck)) then for i=0, #tag.SEG do - taglen = taglen + tag.SEG[i] . len + taglen = taglen + tag.SEG[i] . len + 5 end end local uid_old = tag.MCD..tag.MSN0..tag.MSN1..tag.MSN2 @@ -571,32 +571,37 @@ function writeToTag(tag) bytes[22] = calcMtCrc(bytes) end if (bytes) then - bytes = xorBytes(bytes,tag.MCC) + print("write temp-file '"..filename.."'") + print(accyan) + writeFile(bytes, filename..".bin") + print(acoff) end end - -- write data to file if (taglen > 0) then WriteBytes = input(acyellow.."enter number of bytes to write?"..acoff, taglen) + -- load file into pm3-buffer + if (type(filename) ~= "string") then + filename = input(acyellow.."filename to load to pm3-buffer?"..acoff, "legic.temp") + end + + cmd = 'hf legic eload 2 '..filename + core.console(cmd) -- write pm3-buffer to Tag - for i=1, WriteBytes do - if (i > 7) then - cmd = ("hf legic wrbl o %02x d %s "):format(i-1, padString(bytes[i])) + for i=0, WriteBytes do + if (i > 6) then + cmd = ("hf legic write o %x d %s "):format(i, padString(bytes[i])) print(acgreen..cmd..acoff) core.console(cmd) core.clearCommandBuffer() - elseif (i == 7) then - if (writeDCF) then - -- write DCF in reverse order (requires 'mosci-patch') - cmd = ('hf legic wrbl o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) - print(acgreen..cmd..acoff) - core.console(cmd) - core.clearCommandBuffer() - else - print(acgreen.."skip byte 0x05-0x06 - DCF"..acoff) - end elseif (i == 6) then + -- write DCF in reverse order (requires 'mosci-patch') + cmd = ('hf legic write o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) + print(acgreen..cmd..acoff) + core.console(cmd) + core.clearCommandBuffer() + elseif (i == 5) then print(acgreen.."skip byte 0x05 - will be written next step"..acoff) else print(acgreen.."skip byte 0x00-0x04 - unwritable area"..acoff) @@ -636,12 +641,12 @@ end local function save_BIN(data, filename) local outfile local counter = 1 - local ext = ".bin" - local fn = filename..ext + local ext = filename:match("^.+(%..+)$") or '' + local fn = filename -- Make sure we don't overwrite a file while file_check(fn) do - fn = filename..ext:gsub(ext, "-"..tostring(counter)..ext) + fn = filename:gsub(ext, tostring(counter)..ext) counter = counter + 1 end @@ -659,27 +664,26 @@ end --- -- write bytes to file function writeFile(bytes, filename) - local emlext = ".eml" - if (filename ~= 'MyLegicClone') then - if (file_check(filename..emlext)) then - local answer = confirm("\nthe output-file "..filename..emlext.." already exists!\nthis will delete the previous content!\ncontinue?") + if (filename ~= 'MylegicClone.hex') then + if (file_check(filename)) then + local answer = confirm("\nthe output-file "..filename.." already exists!\nthis will delete the previous content!\ncontinue?") if not answer then return print("user abort") end end end local line local bcnt = 0 - local fho, err = io.open(filename..emlext, "w") + local fho, err = io.open(filename, "w") if err then - return oops("OOps ... failed to open output-file ".. filename..emlext) + return oops("OOps ... failed to open output-file ".. filename) end bytes = xorBytes(bytes, bytes[5]) for i = 1, #bytes do if (bcnt == 0) then - line = padString(bytes[i]) + line = bytes[i] elseif (bcnt <= 7) then - line = line.." "..padString(bytes[i]) + line = line.." "..bytes[i] end if (bcnt == 7) then -- write line to new file @@ -695,7 +699,7 @@ function writeFile(bytes, filename) -- save binary local fn_bin, fn_bin_num = save_BIN(bytes, filename) - print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..emlext..acoff) + print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..acoff) if fn_bin and fn_bin_num then print("\nwrote "..acyellow..fn_bin_num..acoff.." bytes to BINARY file "..acyellow..fn_bin..acoff) @@ -704,21 +708,6 @@ function writeFile(bytes, filename) return true end ---- --- read from pm3 into virtual-tag -function readFromPM3() - local tag, bytes, infile - --infile="legic.temp" - infile=os.tmpname() - core.console("hf legic dump f "..infile) - tag=readFile(infile..".bin") - os.remove(infile) - os.remove(infile..".bin") - os.remove(infile..".eml") - os.remove(infile..".json") - return tag -end - --- Map related --- --- -- make tagMap @@ -2276,8 +2265,8 @@ function modifyHelp() ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load bin File ck => check KGH - sf => save eml/bin File ds => dump Segments + lf => load File ck => check KGH + sf => save File ds => dump Segments xf => xor to File @@ -2363,10 +2352,10 @@ function modifyMode() -- save values of mainTAG to a file (xored with MCC of mainTAG) ["sf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) + outfile = input("enter filename:", "legic.temp") bytes = tagToBytes(inTAG) --bytes=xorBytes(bytes, inTAG.MCC) - if (bytes) then + if bytes then writeFile(bytes, outfile) end end @@ -2375,7 +2364,7 @@ function modifyMode() -- save values of mainTAG to a file (xored with 'specific' MCC) ["xf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) + outfile = input("enter filename:", "legic.temp") crc = input("enter new crc: ('00' for a plain dump)", inTAG.MCC) print("obfuscate with: "..crc) bytes=tagToBytes(inTAG) diff --git a/client/mifare/mifare4.c b/client/mifare/mifare4.c index 848528611..966a2027d 100644 --- a/client/mifare/mifare4.c +++ b/client/mifare/mifare4.c @@ -429,46 +429,6 @@ int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data return 0; } -int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { - uint8_t c[] = {0x3c, 0x00}; - return intExchangeRAW14aPlus(c, sizeof(c), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); -} - -int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { - uint8_t tmp[20] = {0}; - uint8_t c[] = {0x60}; - int res = intExchangeRAW14aPlus(c, sizeof(c), activateField, true, tmp, maxdataoutlen, dataoutlen); - if (res != 0) { - DropField(); - *dataoutlen = 0; - return res; - } - - memcpy(dataout, tmp + 1, (*dataoutlen - 3)); - - *dataoutlen = 0; - // MFDES_ADDITIONAL_FRAME - if (tmp[0] == 0xAF) { - c[0] = 0xAF; - res = intExchangeRAW14aPlus(c, sizeof(c), false, true, tmp, maxdataoutlen, dataoutlen); - if (res == 0) { - - memcpy(dataout + 7, tmp + 1, (*dataoutlen - 3)); - - // MFDES_ADDITIONAL_FRAME - res = intExchangeRAW14aPlus(c, sizeof(c), false, false, tmp, maxdataoutlen, dataoutlen); - if (res == 0) { - if (tmp[0] == 0x90) { - memcpy(dataout + 7 + 7, tmp + 1, (*dataoutlen - 3)); - *dataoutlen = 28; - } - } - } - } - DropField(); - return res; -} - // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards), // plus evtl. 8 sectors with 16 blocks each (4k cards) uint8_t mfNumBlocksPerSector(uint8_t sectorNo) { diff --git a/client/mifare/mifare4.h b/client/mifare/mifare4.h index 0c3e08458..cb2c8d652 100644 --- a/client/mifare/mifare4.h +++ b/client/mifare/mifare4.h @@ -59,9 +59,6 @@ int MFPReadBlock(mf4Session_t *session, bool plain, uint8_t blockNum, uint8_t bl int MFPWriteBlock(mf4Session_t *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac); int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose); -int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); -int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); - const char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data); uint8_t mfNumBlocksPerSector(uint8_t sectorNo); diff --git a/client/settings.c b/client/settings.c index 79fa00fd1..976121eed 100644 --- a/client/settings.c +++ b/client/settings.c @@ -44,7 +44,8 @@ #include "emv/emvjson.h" // Load all settings into memory (struct) -int settings_load (void) { +int settings_load (void) +{ // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; @@ -67,27 +68,25 @@ int settings_load (void) { int window_ypos; int window_hsize; int window_wsize; - bool use_emojis - bool use_hints */ - printf (" Settings Version : [%s]\n", mySettings.version); - printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); - printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); - printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); - printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); - printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); - printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); - printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); - printf (" use hints (bool) : [%d]\n", mySettings.use_hints); + printf (" Settings Version : [%s]\n",mySettings.version); + printf (" os_windows_usecolor (bool) : [%d]\n",mySettings.os_windows_usecolor); + printf (" os_windows_useAnsicolor (bool) : [%d]\n",mySettings.os_windows_useansicolor); + printf (" window_xpos (int) : [%d]\n",mySettings.window_xpos); + printf (" window_ypos (int) : [%d]\n",mySettings.window_ypos); + printf (" window_hsize (int) : [%d]\n",mySettings.window_hsize); + printf (" window_wsize (int) : [%d]\n",mySettings.window_wsize); + return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save(void) { +int settings_save (void) +{ // Note sure if backup has value ? char backupFilename[500]; - snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -106,14 +105,18 @@ int settings_save(void) { uint8_t dummyData = 0x00; size_t dummyDL = 0x00; + // int saveFileJSON(const char *preferredName, JSONFileType ftype, uint8_t *data, size_t datalen); + if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); return PM3_SUCCESS; } -void settings_save_callback(json_t *root) { - +void settings_save_callback (json_t *root) +{ + // extern settings_t mySettings; + printf ("==> Save Settings\n"); //JsonSaveStr(root, "FileType", "settings"); //JsonSaveStr (root,"Test1.Test2","test settings"); @@ -128,24 +131,23 @@ void settings_save_callback(json_t *root) { */ JsonSaveStr (root,"FileType","settings"); JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); - JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); - JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); - JsonSaveInt (root,"window.xpos", mySettings.window_xpos); - JsonSaveInt (root,"window.ypos", mySettings.window_ypos); - JsonSaveInt (root,"window.hsize", mySettings.window_hsize); - JsonSaveInt (root,"window.wsize", mySettings.window_wsize); - JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); - JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); + JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); + JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); + JsonSaveInt (root,"window.xpos",mySettings.window_xpos); + JsonSaveInt (root,"window.ypos",mySettings.window_ypos); + JsonSaveInt (root,"window.hsize",mySettings.window_hsize); + JsonSaveInt (root,"window.wsize",mySettings.window_wsize); } -void settings_load_callback(json_t *root) { - +void settings_load_callback (json_t *root) +{ +// extern settings_t mySettings; json_error_t up_error = {0}; int b1; int i1; const char *s1; - if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) + if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); else strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); @@ -178,17 +180,5 @@ void settings_load_callback(json_t *root) { mySettings.window_wsize = i1; else // default mySettings.window_wsize = 0; - - // Use EMOJIS - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) - mySettings.use_emojis = b1; - else // default - mySettings.use_emojis = false; - - // Use Hints - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) - mySettings.use_hints = b1; - else // default - mySettings.use_hints = false; } diff --git a/client/settings.h b/client/settings.h index 4bf8b2a5e..799af7caa 100644 --- a/client/settings.h +++ b/client/settings.h @@ -24,8 +24,6 @@ typedef struct { int window_ypos; int window_hsize; int window_wsize; - bool use_emojis; - bool use_hints; } settings_t; // Settings struct so as to be available to other modules by including settings.h diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index 3fba71e1c..e727180bf 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -18,7 +18,7 @@ Always use the latest repository commits from *master* branch. There are always * [File not found](#file-not-found) * [Pixmap / pixbuf warnings](#pixmap--pixbuf-warnings) * [Usb cable](#usb-cable) - * [WSL 2 explorer.exe . doesnt work](#WSL-2) + * [WSL 2 explorer.exe . doesnt work](WSL-2) ## `pm3` or `pm3-flash*` doesn't see my Proxmark diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 6ce271aab..d97fae6ed 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -618,11 +618,6 @@ typedef struct { #define PM3_EOUTOFBOUND -17 // exchange with card error client/pm3: error when cant get answer from card or got an incorrect answer #define PM3_ECARDEXCHANGE -18 - -// Failed to create APDU, -#define PM3_EAPDU_ENCODEFAIL -19 -// APDU responded with a failure code -#define PM3_EAPDU_FAIL -20 // No data pm3: no data available, no host frame available (not really an error) #define PM3_ENODATA -98 // Quit program client: reserved, order to quit the program diff --git a/include/protocols.h b/include/protocols.h index 03953fcc6..89038a789 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -349,62 +349,44 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // 6x xx = ERROR // MIFARE DESFire command set: - - +#define MFDES_CREATE_APPLICATION 0xca +#define MFDES_DELETE_APPLICATION 0xda +#define MFDES_GET_APPLICATION_IDS 0x6a +#define MFDES_SELECT_APPLICATION 0x5a +#define MFDES_FORMAT_PICC 0xfc #define MFDES_GET_VERSION 0x60 - -#define MFDES_AUTHENTICATE 0x0A // AUTHENTICATE_NATIVE -#define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD -#define MFDES_AUTHENTICATE_AES 0xAA - -#define MFDES_CREDIT 0x0C -#define MFDES_LIMITED_CREDIT 0x1C -#define MFDES_DEBIT 0xDC - -#define MFDES_WRITE_RECORD 0x3B -#define MFDES_READSIG 0x3C -#define MFDES_WRITE_DATA 0x3D - -#define MFDES_GET_KEY_SETTINGS 0x45 -#define MFDES_CHANGE_KEY_SETTINGS 0x54 -#define MFDES_SELECT_APPLICATION 0x5A -#define MFDES_CHANGE_FILE_SETTINGS 0x5F +#define MFDES_READ_DATA 0xbd +#define MFDES_WRITE_DATA 0x3d +#define MFDES_GET_VALUE 0x6c +#define MFDES_CREDIT 0x0c +#define MFDES_DEBIT 0xdc +#define MFDES_LIMITED_CREDIT 0x1c +#define MFDES_WRITE_RECORD 0x3b +#define MFDES_READ_RECORDS 0xbb +#define MFDES_CLEAR_RECORD_FILE 0xeb +#define MFDES_COMMIT_TRANSACTION 0xc7 +#define MFDES_ABORT_TRANSACTION 0xa7 +#define MFDES_GET_FREE_MEMORY 0x6e +#define MFDES_GET_FILE_IDS 0x6f #define MFDES_GET_ISOFILE_IDS 0x61 +#define MFDES_GET_FILE_SETTINGS 0xf5 +#define MFDES_CHANGE_FILE_SETTINGS 0x5f +#define MFDES_CREATE_STD_DATA_FILE 0xcd +#define MFDES_CREATE_BACKUP_DATA_FILE 0xcb +#define MFDES_CREATE_VALUE_FILE 0xcc +#define MFDES_CREATE_LINEAR_RECORD_FILE 0xc1 +#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xc0 +#define MFDES_DELETE_FILE 0xdf +#define MFDES_AUTHENTICATE 0x0a // AUTHENTICATE_NATIVE +#define MFDES_AUTHENTICATE_ISO 0x1a // AUTHENTICATE_STANDARD +#define MFDES_AUTHENTICATE_AES 0xaa +#define MFDES_CHANGE_KEY_SETTINGS 0x54 +#define MFDES_GET_KEY_SETTINGS 0x45 +#define MFDES_CHANGE_KEY 0xc4 #define MFDES_GET_KEY_VERSION 0x64 -#define MFDES_GET_APPLICATION_IDS 0x6A -#define MFDES_GET_VALUE 0x6C -#define MFDES_GET_FREE_MEMORY 0x6E -#define MFDES_GET_DF_NAMES 0x6D -#define MFDES_GET_FILE_IDS 0x6F - - -#define MFDES_ABORT_TRANSACTION 0xA7 #define MFDES_AUTHENTICATION_FRAME 0xAF #define MFDES_ADDITIONAL_FRAME 0xAF -#define MFDES_ADDITIONAL_FRAME_RESP 0x91AF -#define MFDES_SUCCESS_FRAME_RESP 0x9100 -#define MFDES_EAUTH_RESP 0x91AE -#define MFDES_ENO_SUCH_KEY_RESP 0x9140 - -#define MFDES_READ_RECORDS 0xBB -#define MFDES_READ_DATA 0xBD - -#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 -#define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 -#define MFDES_CHANGE_KEY 0xC4 -#define MFDES_COMMIT_TRANSACTION 0xC7 -#define MFDES_CREATE_APPLICATION 0xCA -#define MFDES_CREATE_BACKUP_DATA_FILE 0xCB -#define MFDES_CREATE_VALUE_FILE 0xCC -#define MFDES_CREATE_STD_DATA_FILE 0xCD - -#define MFDES_CLEAR_RECORD_FILE 0xEB - -#define MFDES_DELETE_APPLICATION 0xDA -#define MFDES_DELETE_FILE 0xDF - -#define MFDES_GET_FILE_SETTINGS 0xF5 -#define MFDES_FORMAT_PICC 0xFC +#define MFDES_READSIG 0x3C // LEGIC Commands #define LEGIC_MIM_22 0x0D From 070636f196c40982e70fec42f2a55948de1be9d8 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 14:36:29 +1000 Subject: [PATCH 30/66] Fix Sync --- CHANGELOG.md | 7 +- armsrc/desfire.h | 1 + armsrc/epa.c | 31 +- armsrc/felica.c | 4 +- armsrc/hitagS.c | 6 +- armsrc/legicrf.c | 6 +- armsrc/lfops.c | 2 +- armsrc/mifaredesfire.c | 24 +- client/cmdhf14a.c | 160 +++-- client/cmdhflegic.c | 19 +- client/cmdhflist.c | 238 ++++---- client/cmdhfmfdes.c | 549 +++++++++++------- client/cmdhfmfdes.h | 40 +- client/cmdhfmfp.c | 276 +++++++-- client/emv/apduinfo.c | 12 +- client/emv/emvcore.c | 4 + client/emv/emvcore.h | 1 + client/luascripts/legic.lua | 161 ++--- client/mifare/mifare4.c | 40 ++ client/mifare/mifare4.h | 3 + client/settings.c | 68 ++- client/settings.h | 2 + .../Troubleshooting.md | 2 +- include/pm3_cmd.h | 5 + include/protocols.h | 84 +-- 25 files changed, 1079 insertions(+), 666 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 946b7c541..0f15617c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,13 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) + - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) + - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) + - Fix Mifare Desfire select appid handling (@bkerler) + - Improved `hf 14a info` - card detection handling (@bkerler) - Updated helptext layout in all luascripts (@iceman1001) - - Change `hf mfdes info` - output and logging (@brkeler) + - Change `hf mfdes info` - output and logging (@bkerler) - Updated texts in legic commands (@ikarus23) - Fix timing bug inside 40x5 (@mwalker33) - Refactored all Hitag2 attacks (@doegox) diff --git a/armsrc/desfire.h b/armsrc/desfire.h index 5fa7e8d48..e753106e7 100644 --- a/armsrc/desfire.h +++ b/armsrc/desfire.h @@ -150,6 +150,7 @@ enum DESFIRE_CMD { GET_FREE_MEMORY = 0x6e, GET_FILE_IDS = 0x6f, GET_FILE_SETTINGS = 0xf5, + GET_DF_NAMES = 0x6d, CHANGE_FILE_SETTINGS = 0x5f, CREATE_STD_DATA_FILE = 0xcd, CREATE_BACKUP_DATA_FILE = 0xcb, diff --git a/armsrc/epa.c b/armsrc/epa.c index f535b89a3..3a44502ba 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -263,7 +263,7 @@ static void EPA_PACE_Collect_Nonce_Abort(uint8_t step, int func_return) { EPA_Finish(); // send the USB packet - reply_old(CMD_ACK, step, func_return, 0, 0, 0); + reply_mix(CMD_ACK, step, func_return, 0, 0, 0); } //----------------------------------------------------------------------------- @@ -280,12 +280,8 @@ void EPA_PACE_Collect_Nonce(PacketCommandNG *c) { * d: * Encrypted nonce */ - - // return value of a function - int func_return = 0; - // set up communication - func_return = EPA_Setup(); + int func_return = EPA_Setup(); if (func_return != 0) { EPA_PACE_Collect_Nonce_Abort(1, func_return); return; @@ -335,7 +331,7 @@ void EPA_PACE_Collect_Nonce(PacketCommandNG *c) { EPA_Finish(); // save received information - reply_old(CMD_ACK, 0, func_return, 0, nonce, func_return); + reply_mix(CMD_ACK, 0, func_return, 0, nonce, func_return); } //----------------------------------------------------------------------------- @@ -447,7 +443,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { if (c->oldarg[0] != 0) { // make sure it's not too big if (c->oldarg[2] > apdus_replay[c->oldarg[0] - 1].len) { - reply_old(CMD_ACK, 1, 0, 0, NULL, 0); + reply_mix(CMD_ACK, 1, 0, 0, NULL, 0); } memcpy(apdus_replay[c->oldarg[0] - 1].data + c->oldarg[1], c->data.asBytes, @@ -458,7 +454,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { } else { apdu_lengths_replay[c->oldarg[0] - 1] += c->oldarg[2]; } - reply_old(CMD_ACK, 0, 0, 0, NULL, 0); + reply_mix(CMD_ACK, 0, 0, 0, NULL, 0); return; } @@ -469,7 +465,7 @@ void EPA_PACE_Replay(PacketCommandNG *c) { func_return = EPA_Setup(); if (func_return != 0) { EPA_Finish(); - reply_old(CMD_ACK, 2, func_return, 0, NULL, 0); + reply_mix(CMD_ACK, 2, func_return, 0, NULL, 0); return; } @@ -492,12 +488,12 @@ void EPA_PACE_Replay(PacketCommandNG *c) { || response_apdu[func_return - 4] != 0x90 || response_apdu[func_return - 3] != 0x00)) { EPA_Finish(); - reply_old(CMD_ACK, 3 + i, func_return, 0, timings, 20); + reply_mix(CMD_ACK, 3 + i, func_return, 0, timings, 20); return; } } EPA_Finish(); - reply_old(CMD_ACK, 0, 0, 0, timings, 20); + reply_mix(CMD_ACK, 0, 0, 0, timings, 20); return; } @@ -506,14 +502,13 @@ void EPA_PACE_Replay(PacketCommandNG *c) { // Returns 0 on success or a non-zero error code on failure //----------------------------------------------------------------------------- int EPA_Setup() { - uint8_t uid[10]; - iso14a_card_select_t card_a_info; // first, look for type A cards // power up the field iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - // select the card - int return_code = iso14443a_select_card(uid, &card_a_info, NULL, true, 0, false); + iso14a_card_select_t card_a_info; + int return_code = iso14443a_select_card(NULL, &card_a_info, NULL, true, 0, false); + if (return_code == 1) { uint8_t pps_response[3]; uint8_t pps_response_par[1]; @@ -528,12 +523,14 @@ int EPA_Setup() { return 0; } + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + // if we're here, there is no type A card, so we look for type B // power up the field iso14443b_setup(); iso14b_card_select_t card_b_info; - // select the card return_code = iso14443b_select_card(&card_b_info); + if (return_code == 0) { Dbprintf("ISO 14443 Type B"); iso_type = 'b'; diff --git a/armsrc/felica.c b/armsrc/felica.c index b1e0253a2..2cb23b48c 100644 --- a/armsrc/felica.c +++ b/armsrc/felica.c @@ -621,7 +621,7 @@ void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) { set_tracelen(BigBuf_max_traceLen()); Dbprintf("Felica sniffing done, tracelen: %i, use hf list felica for annotations", BigBuf_get_traceLen()); - reply_old(CMD_ACK, 1, numbts, 0, 0, 0); + reply_mix(CMD_ACK, 1, numbts, 0, 0, 0); LED_D_OFF(); } @@ -812,5 +812,5 @@ void felica_dump_lite_s() { //setting tracelen - important! it was set by buffer overflow before set_tracelen(cnt); - reply_old(CMD_ACK, isOK, cnt, 0, 0, 0); + reply_mix(CMD_ACK, isOK, cnt, 0, 0, 0); } diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index 78009496e..4268e82e5 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -1407,7 +1407,7 @@ void ReadHitagS(hitag_function htf, hitag_data *htd) { set_tracing(false); lf_finalize(); - reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); } /* @@ -1624,7 +1624,7 @@ void WritePageHitagS(hitag_function htf, hitag_data *htd, int page) { lf_finalize(); - reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); } /* @@ -1860,5 +1860,5 @@ void check_challenges(bool file_given, uint8_t *data) { set_tracing(false); lf_finalize(); - reply_old(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); } diff --git a/armsrc/legicrf.c b/armsrc/legicrf.c index 35b638298..b411efcaf 100644 --- a/armsrc/legicrf.c +++ b/armsrc/legicrf.c @@ -438,7 +438,7 @@ void LegicRfInfo(void) { } // OK - reply_old(CMD_ACK, 1, 0, 0, (uint8_t *)&card, sizeof(legic_card_select_t)); + reply_mix(CMD_ACK, 1, 0, 0, (uint8_t *)&card, sizeof(legic_card_select_t)); OUT: switch_off(); @@ -513,7 +513,7 @@ void LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv) { } // OK - reply_old(CMD_ACK, 1, len, 0, legic_mem, len); + reply_mix(CMD_ACK, 1, len, 0, 0, 0); OUT: switch_off(); @@ -552,7 +552,7 @@ void LegicRfWriter(uint16_t offset, uint16_t len, uint8_t iv, uint8_t *data) { } // OK - reply_old(CMD_ACK, 1, len, 0, legic_mem, len); + reply_mix(CMD_ACK, 1, len, 0, 0, 0); OUT: switch_off(); diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 65f9e8422..a5104d98e 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -2040,7 +2040,7 @@ void T55xx_ChkPwds(uint8_t flags) { if (isok != sizeof(counter)) goto OUT; - pwdCount = counter[1] << 8 | counter[0]; + pwdCount = (uint16_t)(counter[1] << 8 | counter[0]); if (pwdCount == 0 || pwdCount == 0xFFFF) goto OUT; diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 5b8ed289e..b2f45d117 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -204,7 +204,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t decRndB[16] = {0x00}; uint8_t both[32] = {0x00}; - InitDesfireCard(); + //InitDesfireCard(); LED_A_ON(); LED_B_OFF(); @@ -455,8 +455,12 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_init(&ctx); cmd[0] = AUTHENTICATE_AES; - cmd[1] = 0x00; //keynumber - len = DesfireAPDU(cmd, 2, resp); + cmd[1] = 0x0; + cmd[2] = 0x0; + cmd[3] = 0x1; + cmd[4] = arg2; //keynumber + cmd[5] = 0x0; + len = DesfireAPDU(cmd, 6, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -465,7 +469,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - memcpy(encRndB, resp + 3, 16); + memcpy(encRndB, resp + 1, 16); // dekryptera tagnonce. if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { @@ -491,9 +495,13 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, both, encBoth); cmd[0] = ADDITIONAL_FRAME; - memcpy(cmd + 1, encBoth, 32); + cmd[1] = 0x00; + cmd[2] = 0x00; + cmd[3] = 0x20; + memcpy(cmd + 4, encBoth, 32); + cmd[36]=0x0; - len = DesfireAPDU(cmd, 33, resp); // 1 + 32 == 33 + len = DesfireAPDU(cmd, 37, resp); // 4 + 32 + 1 == 37 if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -502,7 +510,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[2] == 0x00) { + if ((resp[1+16] == 0x91)&&(resp[1+16+1] == 0x00)) { // Create AES Session key struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; @@ -601,6 +609,6 @@ void OnSuccess() { } void OnError(uint8_t reason) { - reply_old(CMD_ACK, 0, reason, 0, 0, 0); + reply_mix(CMD_ACK, 0, reason, 0, 0, 0); OnSuccess(); } diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index f737ff485..2e5fcb69e 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -193,7 +193,7 @@ static int usage_hf_14a_sim(void) { PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344")); PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sim t 1 u 11223344556677")); // PrintAndLogEx(NORMAL, " hf 14a sim t 1 u 11223445566778899AA\n"); - return 0; + return PM3_SUCCESS; } static int usage_hf_14a_sniff(void) { PrintAndLogEx(NORMAL, "It get data from the field and saves it into command buffer."); @@ -203,7 +203,7 @@ static int usage_hf_14a_sniff(void) { PrintAndLogEx(NORMAL, "r - triggered by first 7-bit request from reader (REQ,WUP,...)"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, _YELLOW_(" hf 14a sniff c r")); - return 0; + return PM3_SUCCESS; } static int usage_hf_14a_raw(void) { PrintAndLogEx(NORMAL, "Usage: hf 14a raw [-h] [-r] [-c] [-p] [-a] [-T] [-t] [-b] <0A 0B 0C ... hex>"); @@ -217,7 +217,7 @@ static int usage_hf_14a_raw(void) { PrintAndLogEx(NORMAL, " -t timeout in ms"); PrintAndLogEx(NORMAL, " -T use Topaz protocol to send command"); PrintAndLogEx(NORMAL, " -3 ISO14443-3 select only (skip RATS)"); - return 0; + return PM3_SUCCESS; } static int usage_hf_14a_reader(void) { PrintAndLogEx(NORMAL, "Usage: hf 14a reader [k|s|x] [3]"); @@ -225,7 +225,7 @@ static int usage_hf_14a_reader(void) { PrintAndLogEx(NORMAL, " s silent (no messages)"); PrintAndLogEx(NORMAL, " x just drop the signal field"); PrintAndLogEx(NORMAL, " 3 ISO14443-3 select only (skip RATS)"); - return 0; + return PM3_SUCCESS; } static int CmdHF14AList(const char *Cmd) { @@ -580,7 +580,7 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav if (resp.oldarg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision // get ATS uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 - SendCommandOLD(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0, rats, 2); + SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0, rats, sizeof(rats)); if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { if (!silentMode) PrintAndLogEx(ERR, "Proxmark3 connection timeout."); return 1; @@ -674,7 +674,7 @@ static int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { if (resp.oldarg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision // get ATS uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 - SendCommandOLD(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, sizeof(rats), 0, rats, sizeof(rats)); + SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, sizeof(rats), 0, rats, sizeof(rats)); if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { PrintAndLogEx(ERR, "Proxmark3 connection timeout."); return 1; @@ -1237,7 +1237,7 @@ static command_t CommandTable[] = { static int CmdHelp(const char *Cmd) { (void)Cmd; // Cmd is not used so far CmdsHelp(CommandTable); - return 0; + return PM3_SUCCESS; } int CmdHF14A(const char *Cmd) { @@ -1246,89 +1246,92 @@ int CmdHF14A(const char *Cmd) { } static void printTag(char *tag) { - PrintAndLogEx(SUCCESS, _YELLOW_(" %s"), tag); + PrintAndLogEx(SUCCESS, "POSSIBLE TYPE:" _YELLOW_(" %s"), tag); } typedef enum { - mtNone = 0, - mtClassic = 1, - mtMini = 2, - mtDESFire = 4, - mtPlus = 8, - mtUltralight = 16, - mtOther = 32 -} nxp_mifare_type; + MTNONE = 0, + MTCLASSIC = 1, + MTMINI = 2, + MTDESFIRE = 4, + MTPLUS = 8, + MTULTRALIGHT = 16, + MTOTHER = 32 +} nxp_mifare_type_t; // According to NXP AN10833 Rev 3.6 MIFARE Type Identification, Table 6 int detect_nxp_card(uint8_t sak, uint16_t atqa) { - int type = mtNone; + int type = MTNONE; if (sak == 0x00) { - printTag("MIFARE Ultralight C / Ultralight CL2"); - type = mtUltralight; + printTag("NTAG 20x / 21x / 21x TT / I2C plus"); + printTag("MIFARE Ultralight / C / EV1 / Nano"); + type = MTULTRALIGHT; } if (sak == 0x01) { printTag("TNP3xxx (Activision Game Appliance)"); - type = mtOther; + type = MTCLASSIC; } if ((sak & 0x04) == 0x04) { - printTag("Any MIFARE CL1"); - type |= mtDESFire; + printTag("Any MIFARE CL1 / NTAG424DNA"); + type |= MTDESFIRE; } if ((sak & 0x08) == 0x08) { printTag("MIFARE Classic 1K / Classic 1K CL2"); printTag("MIFARE Plus 2K / Plus EV1 2K"); printTag("MIFARE Plus CL2 2K / Plus CL2 EV1 2K"); - type |= mtClassic; - type |= mtPlus; + type |= MTCLASSIC; + type |= MTPLUS; } if ((sak & 0x09) == 0x09) { printTag("MIFARE Mini 0.3K / Mini CL2 0.3K"); - type |= mtMini; + type |= MTMINI; } if ((sak & 0x10) == 0x10) { printTag("MIFARE Plus 2K / Plus CL2 2K"); - type |= mtPlus; + type |= MTPLUS; } if ((sak & 0x11) == 0x11) { printTag("MIFARE Plus 4K / Plus CL2 4K"); - type |= mtPlus; + type |= MTPLUS; } if ((sak & 0x18) == 0x18) { if (atqa == 0x0042) { printTag("MIFARE Plus 4K / Plus EV1 4K"); printTag("MIFARE Plus CL2 4K / Plus CL2 EV1 4K"); - type |= mtPlus; + type |= MTPLUS; } else { printTag("MIFARE Classic 4K / Classic 4K CL2"); - type |= mtClassic; + type |= MTCLASSIC; } } if ((sak & 0x20) == 0x20) { if (atqa == 0x0344) { printTag("MIFARE DESFire EV1 2K/4K/8K / DESFire EV1 CL2 2K/4K/8K"); - type |= mtDESFire; + printTag("MIFARE NTAG424DNA"); + type |= MTDESFIRE; + } else if (atqa == 0x0304) { + printTag("MIFARE NTAG424DNA (Random ID feature)"); + type |= MTDESFIRE; } else { - printTag("MIFARE Plus 2K / Plus EV1 2K"); - printTag("MIFARE Plus 4K / Plus EV1 4K"); - printTag("MIFARE Plus CL2 2K / Plus CL2 EV1 4K"); - printTag("MIFARE Plus CL2 4K / Plus CL2 EV1 4K"); - type |= mtPlus; + printTag("MIFARE Plus 2K/4K / Plus EV1 2K/4K"); + printTag("MIFARE Plus CL2 2K/4K / Plus CL2 EV1 2K/4K"); + type |= MTPLUS; } } if ((sak & 0x24) == 0x24) { if (atqa == 0x0344) { printTag("MIFARE DESFire CL1 / DESFire EV1 CL1"); - type |= mtDESFire; + type |= MTDESFIRE; } } if ((sak & 0x28) == 0x28) { if (atqa == 0x0344) { printTag("MIFARE DESFire CL1 / DESFire EV1 CL1"); - type |= mtDESFire; + type |= MTDESFIRE; } } return type; @@ -1342,16 +1345,6 @@ typedef struct { const uidname uidmap[] = { // UID0, UID1, TEXT - {0x02, 0x00, "SR176"}, - {0x02, 0x03, "SRIX4K"}, - {0x02, 0x0C, "SRT512"}, - {0x02, 0x0F, "SRI2K"}, - {0x02, 0x1B, "25TB512-AC"}, - {0x02, 0x3D, "SRIX4K"}, - {0x02, 0x3F, "25TB02K"}, - {0x02, 0x4D, "SRIX512"}, - {0x02, 0x6D, "SRI512"}, - {0x02, 0x7D, "SRI4K"}, {0x02, 0x84, "M24SR64-Y"}, {0x02, 0xA3, "25TA02KB-P"}, {0x02, 0xC4, "25TA64K"}, @@ -1422,42 +1415,33 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { bool isMifareDESFire = false; bool isMifarePlus = false; bool isMifareUltralight = false; - int nxptype = mtNone; + int nxptype = MTNONE; // Double & triple sized UID, can be mapped to a manufacturer. if (card.uidlen <= 4) { nxptype = detect_nxp_card(card.sak, ((card.atqa[1] << 8) + card.atqa[0])); - if ((nxptype & mtClassic) == mtClassic) isMifareClassic = true; - else isMifareClassic = false; - if ((nxptype & mtDESFire) == mtDESFire) { - isMifareDESFire = true; - } else { - isMifareDESFire = false; - } - if ((nxptype & mtPlus) == mtPlus) isMifarePlus = true; - else isMifarePlus = false; - if ((nxptype & mtUltralight) == mtUltralight) isMifareUltralight = true; - else isMifareUltralight = false; - if ((nxptype & mtOther) == mtOther) isMifareClassic = true; + + isMifareClassic = ((nxptype & MTCLASSIC) == MTCLASSIC); + isMifareDESFire = ((nxptype & MTDESFIRE) == MTDESFIRE); + isMifarePlus = ((nxptype & MTPLUS) == MTPLUS); + isMifareUltralight = ((nxptype & MTULTRALIGHT) == MTULTRALIGHT); + + if ((nxptype & MTOTHER) == MTOTHER) + isMifareClassic = true; } if (card.uidlen > 4) { - PrintAndLogEx(SUCCESS, "MANUFACTURER: " _YELLOW_("%s"), getTagInfo(card.uid[0])); - - PrintAndLogEx(SUCCESS, "Possible Type:"); + PrintAndLogEx(SUCCESS, "MANUFACTURER: " _YELLOW_("%s"), getTagInfo(card.uid[0])); switch (card.uid[0]) { case 0x04: // NXP nxptype = detect_nxp_card(card.sak, ((card.atqa[1] << 8) + card.atqa[0])); - if ((nxptype & mtClassic) == mtClassic) isMifareClassic = true; - else isMifareClassic = false; - if ((nxptype & mtDESFire) == mtDESFire) { - isMifareDESFire = true; - } else { - isMifareDESFire = false; - } - if ((nxptype & mtPlus) == mtPlus) isMifarePlus = true; - else isMifarePlus = false; - if ((nxptype & mtUltralight) == mtUltralight) isMifareUltralight = true; - else isMifareUltralight = false; - if ((nxptype & mtOther) == mtOther) isMifareClassic = true; + + isMifareClassic = ((nxptype & MTCLASSIC) == MTCLASSIC); + isMifareDESFire = ((nxptype & MTDESFIRE) == MTDESFIRE); + isMifarePlus = ((nxptype & MTPLUS) == MTPLUS); + isMifareUltralight = ((nxptype & MTULTRALIGHT) == MTULTRALIGHT); + + if ((nxptype & MTOTHER) == MTOTHER) + isMifareClassic = true; + break; case 0x05: // Infineon if ((card.uid[1] & 0xF0) == 0x10) { @@ -1478,7 +1462,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { default: getTagLabel(card.uid[0], card.uid[1]); switch (card.sak) { - case 0x00: + case 0x00: { isMifareClassic = false; // ******** is card of the MFU type (UL/ULC/NTAG/ etc etc) @@ -1507,23 +1491,30 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { return select_status; } break; - case 0x0A: + } + case 0x0A: { printTag("FM11RF005SH (Shanghai Metro)"); break; - case 0x20: + } + case 0x20: { printTag("JCOP 31/41"); break; - case 0x28: + } + case 0x28: { printTag("JCOP31 or JCOP41 v2.3.1"); break; - case 0x38: + } + case 0x38: { printTag("Nokia 6212 or 6131"); break; - case 0x98: + } + case 0x98: { printTag("Gemplus MPCOS"); break; - default: + } + default: { break; + } } break; } @@ -1765,7 +1756,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes info`")); } - if (((card.sak & 0x08) == 0x08) || ((card.sak & 0x18) == 0x18)) { + if (isMifareClassic || isMifareUltralight) { detect_classic_magic(); if (isMifareClassic) { @@ -1775,7 +1766,7 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { else if (res == 0) PrintAndLogEx(SUCCESS, "Prng detection: " _YELLOW_("hard")); else - PrintAndLogEx(FAILED, "prng detection: " _RED_("fail")); + PrintAndLogEx(FAILED, "Prng detection: " _RED_("fail")); if (do_nack_test) detect_classic_nackbug(false); @@ -1789,5 +1780,6 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { } } + DropField(); return select_status; } diff --git a/client/cmdhflegic.c b/client/cmdhflegic.c index c6de1379d..5c007f9f9 100644 --- a/client/cmdhflegic.c +++ b/client/cmdhflegic.c @@ -658,6 +658,16 @@ static int CmdLegicWrbl(const char *Cmd) { } } } + + // OUT-OF-BOUNDS checks + // UID 4+1 bytes can't be written to. + if (offset < 5) { + if (data) + free(data); + PrintAndLogEx(WARNING, "Out-of-bounds, bytes 0-1-2-3-4 can't be written to. Offset = %d", offset); + return PM3_EOUTOFBOUND; + } + //Validations if (errors || cmdp == 0) { if (data) @@ -674,14 +684,7 @@ static int CmdLegicWrbl(const char *Cmd) { legic_print_type(card.cardsize, 0); - // OUT-OF-BOUNDS checks - // UID 4+1 bytes can't be written to. - if (offset < 5) { - PrintAndLogEx(WARNING, "Out-of-bounds, bytes 0-1-2-3-4 can't be written to. Offset = %d", offset); - return PM3_EOUTOFBOUND; - } - - if (len + offset >= card.cardsize) { + if (len + offset > card.cardsize) { PrintAndLogEx(WARNING, "Out-of-bounds, Cardsize = %d, [offset+len = %d ]", card.cardsize, len + offset); return PM3_EOUTOFBOUND; } diff --git a/client/cmdhflist.c b/client/cmdhflist.c index b35e4d622..871cd68a3 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -674,7 +674,8 @@ void annotateIso7816(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { // it's basically a ISO14443a tag, so try annotation from there - if (!applyIso14443a(exp, size, cmd, cmdsize)) { + if (applyIso14443a(exp, size, cmd, cmdsize) == 0) { + // S-block 11xxx010 if ((cmd[0] & 0xC0) && (cmdsize == 3)) { switch ((cmd[0] & 0x30)) { @@ -698,123 +699,132 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { } // I-block 000xCN1x else if ((cmd[0] & 0xC0) == 0x00) { + // PCB [CID] [NAD] [INF] CRC CRC int pos = 1; if ((cmd[0] & 0x08) == 0x08) // cid byte following - pos = pos + 1; + pos++; + if ((cmd[0] & 0x04) == 0x04) // nad byte following - pos = pos + 1; - switch (cmd[pos]) { - case MFDES_CREATE_APPLICATION: - snprintf(exp, size, "CREATE APPLICATION"); - break; - case MFDES_DELETE_APPLICATION: - snprintf(exp, size, "DELETE APPLICATION"); - break; - case MFDES_GET_APPLICATION_IDS: - snprintf(exp, size, "GET APPLICATION IDS"); - break; - case MFDES_SELECT_APPLICATION: - snprintf(exp, size, "SELECT APPLICATION"); - break; - case MFDES_FORMAT_PICC: - snprintf(exp, size, "FORMAT PICC"); - break; - case MFDES_GET_VERSION: - snprintf(exp, size, "GET VERSION"); - break; - case MFDES_READ_DATA: - snprintf(exp, size, "READ DATA"); - break; - case MFDES_WRITE_DATA: - snprintf(exp, size, "WRITE DATA"); - break; - case MFDES_GET_VALUE: - snprintf(exp, size, "GET VALUE"); - break; - case MFDES_CREDIT: - snprintf(exp, size, "CREDIT"); - break; - case MFDES_DEBIT: - snprintf(exp, size, "DEBIT"); - break; - case MFDES_LIMITED_CREDIT: - snprintf(exp, size, "LIMITED CREDIT"); - break; - case MFDES_WRITE_RECORD: - snprintf(exp, size, "WRITE RECORD"); - break; - case MFDES_READ_RECORDS: - snprintf(exp, size, "READ RECORDS"); - break; - case MFDES_CLEAR_RECORD_FILE: - snprintf(exp, size, "CLEAR RECORD FILE"); - break; - case MFDES_COMMIT_TRANSACTION: - snprintf(exp, size, "COMMIT TRANSACTION"); - break; - case MFDES_ABORT_TRANSACTION: - snprintf(exp, size, "ABORT TRANSACTION"); - break; - case MFDES_GET_FREE_MEMORY: - snprintf(exp, size, "GET FREE MEMORY"); - break; - case MFDES_GET_FILE_IDS: - snprintf(exp, size, "GET FILE IDS"); - break; - case MFDES_GET_ISOFILE_IDS: - snprintf(exp, size, "GET ISOFILE IDS"); - break; - case MFDES_GET_FILE_SETTINGS: - snprintf(exp, size, "GET FILE SETTINGS"); - break; - case MFDES_CHANGE_FILE_SETTINGS: - snprintf(exp, size, "CHANGE FILE SETTINGS"); - break; - case MFDES_CREATE_STD_DATA_FILE: - snprintf(exp, size, "CREATE STD DATA FILE"); - break; - case MFDES_CREATE_BACKUP_DATA_FILE: - snprintf(exp, size, "CREATE BACKUP DATA FILE"); - break; - case MFDES_CREATE_VALUE_FILE: - snprintf(exp, size, "CREATE VALUE FILE"); - break; - case MFDES_CREATE_LINEAR_RECORD_FILE: - snprintf(exp, size, "CREATE LINEAR RECORD FILE"); - break; - case MFDES_CREATE_CYCLIC_RECORD_FILE: - snprintf(exp, size, "CREATE CYCLIC RECORD FILE"); - break; - case MFDES_DELETE_FILE: - snprintf(exp, size, "DELETE FILE"); - break; - case MFDES_AUTHENTICATE: - snprintf(exp, size, "AUTH NATIVE (keyNo %d)", cmd[pos + 1]); - break; // AUTHENTICATE_NATIVE - case MFDES_AUTHENTICATE_ISO: - snprintf(exp, size, "AUTH ISO (keyNo %d)", cmd[pos + 1]); - break; // AUTHENTICATE_STANDARD - case MFDES_AUTHENTICATE_AES: - snprintf(exp, size, "AUTH AES (keyNo %d)", cmd[pos + 1]); - break; - case MFDES_CHANGE_KEY_SETTINGS: - snprintf(exp, size, "CHANGE KEY SETTINGS"); - break; - case MFDES_GET_KEY_SETTINGS: - snprintf(exp, size, "GET KEY SETTINGS"); - break; - case MFDES_CHANGE_KEY: - snprintf(exp, size, "CHANGE KEY"); - break; - case MFDES_GET_KEY_VERSION: - snprintf(exp, size, "GET KEY VERSION"); - break; - case MFDES_AUTHENTICATION_FRAME: - snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); - break; - default: - break; + pos++; + + for (uint8_t i = 0; i < 2; i++, pos++) { + + switch (cmd[pos]) { + case MFDES_CREATE_APPLICATION: + snprintf(exp, size, "CREATE APPLICATION"); + break; + case MFDES_DELETE_APPLICATION: + snprintf(exp, size, "DELETE APPLICATION"); + break; + case MFDES_GET_APPLICATION_IDS: + snprintf(exp, size, "GET APPLICATION IDS"); + break; + case MFDES_SELECT_APPLICATION: + snprintf(exp, size, "SELECT APPLICATION"); + break; + case MFDES_FORMAT_PICC: + snprintf(exp, size, "FORMAT PICC"); + break; + case MFDES_GET_VERSION: + snprintf(exp, size, "GET VERSION"); + break; + case MFDES_READ_DATA: + snprintf(exp, size, "READ DATA"); + break; + case MFDES_WRITE_DATA: + snprintf(exp, size, "WRITE DATA"); + break; + case MFDES_GET_VALUE: + snprintf(exp, size, "GET VALUE"); + break; + case MFDES_CREDIT: + snprintf(exp, size, "CREDIT"); + break; + case MFDES_DEBIT: + snprintf(exp, size, "DEBIT"); + break; + case MFDES_LIMITED_CREDIT: + snprintf(exp, size, "LIMITED CREDIT"); + break; + case MFDES_WRITE_RECORD: + snprintf(exp, size, "WRITE RECORD"); + break; + case MFDES_READ_RECORDS: + snprintf(exp, size, "READ RECORDS"); + break; + case MFDES_CLEAR_RECORD_FILE: + snprintf(exp, size, "CLEAR RECORD FILE"); + break; + case MFDES_COMMIT_TRANSACTION: + snprintf(exp, size, "COMMIT TRANSACTION"); + break; + case MFDES_ABORT_TRANSACTION: + snprintf(exp, size, "ABORT TRANSACTION"); + break; + case MFDES_GET_FREE_MEMORY: + snprintf(exp, size, "GET FREE MEMORY"); + break; + case MFDES_GET_FILE_IDS: + snprintf(exp, size, "GET FILE IDS"); + break; + case MFDES_GET_DF_NAMES: + snprintf(exp, size, "GET DF NAMES"); + break; + case MFDES_GET_ISOFILE_IDS: + snprintf(exp, size, "GET ISOFILE IDS"); + break; + case MFDES_GET_FILE_SETTINGS: + snprintf(exp, size, "GET FILE SETTINGS"); + break; + case MFDES_CHANGE_FILE_SETTINGS: + snprintf(exp, size, "CHANGE FILE SETTINGS"); + break; + case MFDES_CREATE_STD_DATA_FILE: + snprintf(exp, size, "CREATE STD DATA FILE"); + break; + case MFDES_CREATE_BACKUP_DATA_FILE: + snprintf(exp, size, "CREATE BACKUP DATA FILE"); + break; + case MFDES_CREATE_VALUE_FILE: + snprintf(exp, size, "CREATE VALUE FILE"); + break; + case MFDES_CREATE_LINEAR_RECORD_FILE: + snprintf(exp, size, "CREATE LINEAR RECORD FILE"); + break; + case MFDES_CREATE_CYCLIC_RECORD_FILE: + snprintf(exp, size, "CREATE CYCLIC RECORD FILE"); + break; + case MFDES_DELETE_FILE: + snprintf(exp, size, "DELETE FILE"); + break; + case MFDES_AUTHENTICATE: + snprintf(exp, size, "AUTH NATIVE (keyNo %d)", cmd[pos + 1]); + break; // AUTHENTICATE_NATIVE + case MFDES_AUTHENTICATE_ISO: + snprintf(exp, size, "AUTH ISO (keyNo %d)", cmd[pos + 1]); + break; // AUTHENTICATE_STANDARD + case MFDES_AUTHENTICATE_AES: + snprintf(exp, size, "AUTH AES (keyNo %d)", cmd[pos + 1]); + break; + case MFDES_CHANGE_KEY_SETTINGS: + snprintf(exp, size, "CHANGE KEY SETTINGS"); + break; + case MFDES_GET_KEY_SETTINGS: + snprintf(exp, size, "GET KEY SETTINGS"); + break; + case MFDES_CHANGE_KEY: + snprintf(exp, size, "CHANGE KEY"); + break; + case MFDES_GET_KEY_VERSION: + snprintf(exp, size, "GET KEY VERSION"); + break; + case MFDES_AUTHENTICATION_FRAME: + snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); + break; + default: + break; + } } } else { // anything else diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 1c5a0ee48..931471961 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -16,11 +16,18 @@ #include "cmdparser.h" // command_t #include "comms.h" #include "ui.h" +#include "cmdhw.h" #include "cmdhf14a.h" #include "mbedtls/des.h" #include "crypto/libpcrypto.h" #include "protocols.h" #include "mifare.h" // desfire raw command options +#include "cmdtrace.h" +#include "cliparser/cliparser.h" +#include "emv/apduinfo.h" // APDU manipulation / errorcodes +#include "emv/emvcore.h" // APDU logging +#include "util_posix.h" // msleep +#include "mifare/mifare4.h" // MIFARE Authenticate / MAC uint8_t key_zero_data[16] = { 0x00 }; uint8_t key_ones_data[16] = { 0x01 }; @@ -32,36 +39,126 @@ typedef enum { MF3ICD40, EV1, EV2, + EV3, LIGHT, } desfire_cardtype_t; +typedef struct { + uint8_t aid[3]; + uint8_t fid[2]; + uint8_t name[16]; +} dfname_t; static int CmdHelp(const char *Cmd); +/* + uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; + int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); -static int SendDesfireCmd(uint8_t *c, size_t len, int p0, int p1, int p2, PacketResponseNG *response, int timeout) { - PacketResponseNG resp; + if (!res && datalen > 1 && data[0] == 0x09) { + SLmode = 0; + } - if (response == NULL) - response = &resp; +*/ - clearCommandBuffer(); - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, p0, p1, p2, c, len); +int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { - if (!WaitForResponseTimeout(CMD_ACK, response, timeout)) { - PrintAndLogEx(WARNING, "[SendDesfireCmd] Timed-out: " _RED_("%s"), sprint_hex(c, len)); + *result_len = 0; + if (sw) *sw = 0; + + uint16_t isw = 0; + int res = 0; + + if (activate_field) { DropField(); - return PM3_ETIMEOUT; + msleep(50); } - uint8_t isOK = response->data.asBytes[0] & 0xff; - if (!isOK) { - PrintAndLogEx(WARNING, "[SendDesfireCmd] Unsuccessful: " _RED_("%s"), sprint_hex(c, len)); - return PM3_ESOFT; + // select? + uint8_t data[APDU_RES_LEN] = {0}; + + // COMPUTE APDU + int datalen = 0; + //if (APDUEncodeS(&apdu, false, IncludeLe ? 0x100 : 0x00, data, &datalen)) { + if (APDUEncodeS(&apdu, false, 0x100, data, &datalen)) { + PrintAndLogEx(ERR, "APDU encoding error."); + return PM3_EAPDU_ENCODEFAIL; } + + if (GetAPDULogging() || (g_debugMode > 1)) + PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen)); + + res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, result_len); + if (res) { + return res; + } + + if (GetAPDULogging() || (g_debugMode > 1)) + PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(result, *result_len)); + + if (*result_len < 2) { + return PM3_SUCCESS; + } + + *result_len -= 2; + isw = (result[*result_len] << 8) + result[*result_len + 1]; + if (sw) + *sw = isw; + + if (isw != 0x9000 && isw != MFDES_SUCCESS_FRAME_RESP && isw != MFDES_ADDITIONAL_FRAME_RESP) { + if (GetAPDULogging()) { + if (isw >> 8 == 0x61) { + PrintAndLogEx(ERR, "APDU chaining len:%02x -->", isw & 0xff); + } else { + PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); + return PM3_EAPDU_FAIL; + } + } + } + return PM3_SUCCESS; } + +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize) { + //SetAPDULogging(true); + *sw = 0; + uint8_t data[255 * 5] = {0x00}; + int resplen = 0; + int pos = 0; + int i = 1; + int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); + if (res != PM3_SUCCESS) return res; + if (*sw != MFDES_ADDITIONAL_FRAME_RESP && *sw != MFDES_SUCCESS_FRAME_RESP) return PM3_ESOFT; + if (dest != NULL) { + memcpy(dest, data, resplen); + } + + pos += resplen; + if (*sw == MFDES_ADDITIONAL_FRAME_RESP) { + apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF + + res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); + if (res != PM3_SUCCESS) return res; + if (dest != NULL) { + if (splitbysize) { + memcpy(&dest[i * splitbysize], data, resplen); + i += 1; + } else { + memcpy(&dest[pos], data, resplen); + } + } + pos += resplen; + } + if (splitbysize) *recv_len = i; + else { + *recv_len = pos; + } + //SetAPDULogging(false); + return PM3_SUCCESS; + +} + static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { if (major == 0x00) @@ -70,59 +167,39 @@ static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { return EV1; else if (major == 0x12 && minor == 0x00) return EV2; +// else if (major == 0x13 && minor == 0x00) +// return EV3; else if (major == 0x30 && minor == 0x00) return LIGHT; else return UNKNOWN; } -//ICEMAN: Turn on field method? //none static int test_desfire_authenticate() { - uint8_t c[] = {AUTHENTICATE, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x0A, KEY 0 - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); - PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { - DropField(); - return PM3_ETIMEOUT; - } - if (resp.length == 13) - return PM3_SUCCESS; - return PM3_ESOFT; + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } + // none static int test_desfire_authenticate_iso() { - uint8_t c[] = {AUTHENTICATE_ISO, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x1A, KEY 0 - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); - PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { - DropField(); - return PM3_ETIMEOUT; - } - if (resp.length >= 13) - return PM3_SUCCESS; - return PM3_ESOFT; + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } + //none static int test_desfire_authenticate_aes() { - /* Just left here for future use, from TI TRF7970A sloa213 document - const static u08_t CustomKey1[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - const static u08_t CustomKey2[16] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, - 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}; - const static u08_t CustomKey3[16] = {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, - 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}; - */ - uint8_t c[] = {AUTHENTICATE_AES, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0xAA, KEY 0 - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(c), 0, c, sizeof(c)); - PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { - DropField(); - return PM3_ETIMEOUT; - } - if (resp.length >= 13) - return PM3_SUCCESS; - return PM3_ESOFT; + uint8_t data[] = {0x00}; + sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 + int recv_len = 0; + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); } // --- FREE MEM @@ -133,20 +210,18 @@ static int desfire_print_freemem(uint32_t free_mem) { // init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { - uint8_t c[] = {GET_FREE_MEMORY, 0x00, 0x00, 0x00}; // 0x6E - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, (INIT | DISCONNECT), sizeof(c), 0, c, sizeof(c)); - PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - return PM3_ETIMEOUT; - } + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E + int recv_len = 0; + uint16_t sw = 0; + uint8_t fmem[4] = {0}; - if (resp.length == 8) { - *free_mem = le24toh(resp.data.asBytes + 1); - return PM3_SUCCESS; + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0); + if (res == PM3_SUCCESS) { + *free_mem = le24toh(fmem); + return res; } - *free_mem = 0; - return PM3_ESOFT; + return res; } @@ -161,9 +236,9 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"NTAG424DNA, DESFire EV2", "048A9B380AF2EE1B98DC417FECC263F8449C7625CECE82D9B916C992DA209D68422B81EC20B65A66B5102A61596AF3379200599316A00A1410"}, {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, - {"NTAG424DNA,NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, + {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, - {"Mifare Plus", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} + {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; uint8_t i; @@ -188,36 +263,41 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); - PrintAndLogEx(INFO, " IC signature public key name: %s", nxp_desfire_public_keys[i].desc); + PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 32); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 48); PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); - PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex(signature, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 16, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 32, 16)); - PrintAndLogEx(INFO, " : %s", sprint_hex(signature + 48, signature_len - 48)); - PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); + PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); + PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); return PM3_SUCCESS; } // init / disconnect static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - uint8_t c[] = {MFDES_READSIG, 0x00, 0x00, 0x01, 0x00, 0x00}; // 0x3C - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, (INIT | DISCONNECT), sizeof(c), 0, c, sizeof(c)); - PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) - return PM3_ETIMEOUT; + uint8_t c = 0x00; + sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0); + if (res == PM3_SUCCESS) { + if (recv_len != 56) { + *signature_len = 0; + DropField(); + return PM3_ESOFT; + } else { + *signature_len = recv_len; - if (resp.length == 61) { - memcpy(signature, resp.data.asBytes + 1, 56); - *signature_len = 56; + } + DropField(); return PM3_SUCCESS; - } else { - *signature_len = 0; - return PM3_ESOFT; } + DropField(); + return res; } @@ -255,18 +335,21 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { // none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - PacketResponseNG resp; - uint8_t c[] = {MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00}; // 0x45 - int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); - if (ret != PM3_SUCCESS) return ret; - - if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0xae) { + sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 + int recv_len = 0; + uint16_t sw = 0; + uint8_t data[2] = {0}; + if (num_keys == NULL) return PM3_ESOFT; + if (key_settings == NULL) return PM3_ESOFT; + int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); + if (sw == MFDES_EAUTH_RESP) { PrintAndLogEx(WARNING, _RED_("[get_desfire_keysettings] Authentication error")); return PM3_ESOFT; } -// PrintAndLogEx(INFO, "ICE: KEYSETTING resp :: %s", sprint_hex(resp.data.asBytes, resp.length)); - *key_settings = resp.data.asBytes[1]; - *num_keys = resp.data.asBytes[2]; + if (res != PM3_SUCCESS) return res; + + *key_settings = data[0]; + *num_keys = data[1]; return PM3_SUCCESS; } @@ -278,83 +361,72 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { // none static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - PacketResponseNG resp; - uint8_t c[] = {MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, curr_key, 0x00}; // 0x64 - int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); - if (ret != PM3_SUCCESS) return ret; - - if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0x40) { + sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 + int recv_len = 0; + uint16_t sw = 0; + if (num_versions == NULL) return PM3_ESOFT; + int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); + if (sw == MFDES_ENO_SUCH_KEY_RESP) { + PrintAndLogEx(WARNING, _RED_("[get_desfire_keyversion] Key %d doesn't exist"), curr_key); return PM3_ESOFT; } - - *num_versions = resp.data.asBytes[1]; - return PM3_SUCCESS; -} - - -// init -static int get_desfire_select_application(uint8_t *aid) { - if (aid == NULL) return PM3_ESOFT; - - uint8_t c[] = {SELECT_APPLICATION, 0x00, 0x00, 0x03, aid[0], aid[1], aid[2], 0x00}; // 0x5a - PacketResponseNG resp; - int ret = SendDesfireCmd(c, sizeof(c), INIT, sizeof(c), 0, &resp, 3000); - if (ret != PM3_SUCCESS) { - if (ret == PM3_ESOFT) { - PrintAndLogEx(WARNING, "[get_desfire_select_application] Can't select AID: " _RED_("%s"), sprint_hex(aid, 3)); - } - return ret; - } - - if (resp.data.asBytes[1] == 0x91 && resp.data.asBytes[2] == 0x00) { - return PM3_SUCCESS; - } - - return PM3_ESOFT; + return res; } // init / disconnect static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a + int recv_len = 0; + uint16_t sw = 0; + if (dest == NULL) return PM3_ESOFT; + if (app_ids_len == NULL) return PM3_ESOFT; + int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0); + if (res != PM3_SUCCESS) return res; + *app_ids_len = (uint8_t)recv_len & 0xFF; + return res; +} - uint8_t c[] = {GET_APPLICATION_IDS, 0x00, 0x00, 0x00}; //0x6a - PacketResponseNG resp; - int ret = SendDesfireCmd(c, sizeof(c), INIT | CLEARTRACE | DISCONNECT, sizeof(c), 0, &resp, 1500); - if (ret != PM3_SUCCESS) return ret; - - *app_ids_len = resp.length - 5; - - // resp.length - 2crc, 2status, 1pcb... - memcpy(dest, resp.data.asBytes + 1, *app_ids_len); - - if (resp.data.asBytes[resp.length - 3] == MFDES_ADDITIONAL_FRAME) { - - c[0] = MFDES_ADDITIONAL_FRAME; //0xAF - ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); - if (ret != PM3_SUCCESS) return ret; - - memcpy(dest + *app_ids_len, resp.data.asBytes + 1, resp.length - 5); - - *app_ids_len += (resp.length - 5); - } - return PM3_SUCCESS; +static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d + int recv_len = 0; + uint16_t sw = 0; + if (dest == NULL) return PM3_ESOFT; + if (dfname_count == NULL) return PM3_ESOFT; + int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t)); + if (res != PM3_SUCCESS) return res; + *dfname_count = recv_len; + return res; } +// init +static int get_desfire_select_application(uint8_t *aid) { + sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a + int recv_len = 0; + uint16_t sw = 0; + if (aid == NULL) return PM3_ESOFT; + return send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); +} + // none static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { - uint8_t c[] = {MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00}; // 0x6f - PacketResponseNG resp; - int ret = SendDesfireCmd(c, sizeof(c), NONE, sizeof(c), 0, &resp, 1500); - if (ret != PM3_SUCCESS) return ret; + sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f + int recv_len = 0; + uint16_t sw = 0; + if (dest == NULL) return PM3_ESOFT; + if (file_ids_len == NULL) return PM3_ESOFT; + *file_ids_len = 0; + int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); + if (res != PM3_SUCCESS) return res; + *file_ids_len = recv_len; + return res; +} - if (resp.data.asBytes[resp.length - 4] == 0x91 && resp.data.asBytes[resp.length - 3] == 0x00) { - *file_ids_len = resp.length - 5; - memcpy(dest, resp.data.asBytes + 1, *file_ids_len); - return PM3_SUCCESS; - } - - return PM3_ESOFT; +static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { + sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 + uint16_t sw = 0; + return send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); } static int CmdHF14ADesInfo(const char *Cmd) { @@ -430,11 +502,13 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (major == 0 && minor == 6) PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); if (major == 1 && minor == 3) - PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1, Support extended APDU commands"); + PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); if (major == 1 && minor == 4) - PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1, N/A information about this version. report to iceman!"); + PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); if (major == 2 && minor == 0) - PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check"); + PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); +// if (major == 3 && minor == 0) +// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); if (major == 0 && minor == 2) PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); @@ -526,6 +600,8 @@ char *getVersionStr(uint8_t major, uint8_t minor) { sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); else if (major == 0x12 && minor == 0x00) sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); +// else if (major == 0x13 && minor == 0x00) +// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); else if (major == 0x30 && minor == 0x00) sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); else @@ -538,9 +614,7 @@ void getKeySettings(uint8_t *aid) { if (memcmp(aid, "\x00\x00\x00", 3) == 0) { // CARD MASTER KEY - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - + //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); if (get_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't select AID")); DropField(); @@ -603,9 +677,7 @@ void getKeySettings(uint8_t *aid) { } else { // AID - APPLICATION MASTER KEYS - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - + //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); if (get_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't select AID")); DropField(); @@ -651,15 +723,25 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { (void)Cmd; // Cmd is not used so far // uint8_t isOK = 0x00; - uint8_t aid[3]; + uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; uint8_t app_ids_len = 0; uint8_t file_ids[33] = {0}; uint8_t file_ids_len = 0; + dfname_t dfnames[255]; + uint8_t dfname_count = 0; + if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); + DropField(); + return PM3_ESOFT; + } + + if (get_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_("Can't get DF Names")); + DropField(); return PM3_ESOFT; } @@ -674,18 +756,49 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { aid[1] = app_ids[i + 1]; aid[2] = app_ids[i + 2]; - PrintAndLogEx(SUCCESS, " AID %d : " _GREEN_("%02X %02X %02X"), i, app_ids[i], app_ids[i + 1], app_ids[i + 2]); + PrintAndLogEx(NORMAL, ""); + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + // CARD MASTER KEY + PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + } else { + PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + } + + PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X %02X %02X"), aid[0], aid[1], aid[2]); + for (int m = 0; m < dfname_count; m++) { + if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { + PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X %02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[0], dfnames[m].fid[1], dfnames[m].name); + } + } getKeySettings(aid); + + if (get_desfire_select_application(aid) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't select AID")); + DropField(); + return PM3_ESOFT; + } + // Get File IDs if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") "file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); for (int j = 0; j < file_ids_len; ++j) { PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); + + uint8_t filesettings[20] = {0}; + int fileset_len = 0; + int res = get_desfire_filesettings(j, filesettings, &fileset_len); + if (res == PM3_SUCCESS) { + PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + } } } + + + /* // Get ISO File IDs { @@ -713,70 +826,90 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { DropField(); return PM3_SUCCESS; } -/* - uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; - int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); - - if (!res && datalen > 1 && data[0] == 0x09) { - SLmode = 0; - } - -*/ - - // MIAFRE DESFire Authentication // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { - + clearCommandBuffer(); // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 // 2 = 3DES 16 // 3 = 3K 3DES 24 // 4 = AES 16 - + //SetAPDULogging(true); uint8_t keylength = 8; - unsigned char key[24]; - if (strlen(Cmd) < 3) { - PrintAndLogEx(NORMAL, "Usage: hf mfdes auth <1|2|3> <1|2|3|4> "); - PrintAndLogEx(NORMAL, " Auth modes"); - PrintAndLogEx(NORMAL, " 1 = normal, 2 = iso, 3 = aes"); - PrintAndLogEx(NORMAL, " Crypto"); - PrintAndLogEx(NORMAL, " 1 = DES 2 = 3DES 3 = 3K3DES 4 = AES"); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, _YELLOW_(" hf mfdes auth 1 1 0 11223344")); - PrintAndLogEx(NORMAL, _YELLOW_(" hf mfdes auth 3 4 0 404142434445464748494a4b4c4d4e4f")); - return PM3_SUCCESS; + CLIParserInit("hf mfdes auth", + "Authenticates Mifare DESFire using Key", + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes auth -m 3 -t 4 -a 018380 -n 0 -k 404142434445464748494a4b4c4d4e4f\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), + arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), + arg_strx0("aA", "aid", "", "AID used for authentification"), + arg_int0("nN", "keyno", "Key number used for authentification", NULL), + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + + uint8_t cmdAuthMode = arg_get_int_def(1, 0); + uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); + + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(3, aid, &aidlength); + + uint8_t cmdKeyNo = arg_get_int_def(4, 0); + + uint8_t key[24] = {0}; + int keylen = 0; + CLIGetHexWithReturn(5, key, &keylen); + CLIParserFree(); + + if ((keylen < 8) || (keylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + // AID + if (aidlength != 3) { + PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); + //SetAPDULogging(false); + return PM3_EINVARG; } - uint8_t cmdAuthMode = param_get8(Cmd, 0); - uint8_t cmdAuthAlgo = param_get8(Cmd, 1); - uint8_t cmdKeyNo = param_get8(Cmd, 2); switch (cmdAuthMode) { case 1: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); return PM3_EINVARG; } break; case 2: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); return PM3_EINVARG; } break; case 3: if (cmdAuthAlgo != 4) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + //SetAPDULogging(false); return PM3_EINVARG; } break; default: - PrintAndLogEx(WARNING, "Wrong Auth mode"); + PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); + //SetAPDULogging(false); return PM3_EINVARG; } @@ -800,21 +933,37 @@ static int CmdHF14ADesAuth(const char *Cmd) { break; } - // key - if (param_gethex(Cmd, 3, key, keylength * 2)) { + // KEY + if (keylen != keylength) { PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); return PM3_EINVARG; } + if (get_desfire_select_application(aid) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't select AID")); + DropField(); + return PM3_ESOFT; + } + + uint8_t file_ids[33] = {0}; + uint8_t file_ids_len = 0; + int res = get_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Get file ids error."); + DropField(); + return res; + } + + // algo, keylength, uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) memcpy(data + 1, key, keylength); - clearCommandBuffer(); SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); PacketResponseNG resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { PrintAndLogEx(WARNING, "Client command execute timeout"); + DropField(); return PM3_ETIMEOUT; } @@ -833,9 +982,15 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_SUCCESS; } +static int CmdHF14ADesList(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + return CmdTraceList("des"); +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"info", CmdHF14ADesInfo, IfPm3Iso14443a, "Tag information"}, + {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index 5c4dcb5e2..4f6605cff 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -19,50 +19,14 @@ char *getProtocolStr(uint8_t id); char *getVersionStr(uint8_t major, uint8_t minor); void getKeySettings(uint8_t *aid); -#define CREATE_APPLICATION 0xca -#define DELETE_APPLICATION 0xda -#define GET_APPLICATION_IDS 0x6a -#define SELECT_APPLICATION 0x5a -#define FORMAT_PICC 0xfc -#define GET_VERSION 0x60 -#define READ_DATA 0xbd -#define WRITE_DATA 0x3d -#define GET_VALUE 0x6c -#define CREDIT 0x0c -#define DEBIT 0xdc -#define LIMITED_CREDIT 0x1c -#define WRITE_RECORD 0x3b -#define READ_RECORDS 0xbb -#define CLEAR_RECORD_FILE 0xeb -#define COMMIT_TRANSACTION 0xc7 -#define ABORT_TRANSACTION 0xa7 -#define GET_FREE_MEMORY 0x6e -#define GET_FILE_IDS 0x6f -#define GET_ISOFILE_IDS 0x61 -#define GET_FILE_SETTINGS 0xf5 -#define CHANGE_FILE_SETTINGS 0x5f -#define CREATE_STD_DATA_FILE 0xcd -#define CREATE_BACKUP_DATA_FILE 0xcb -#define CREATE_VALUE_FILE 0xcc -#define CREATE_LINEAR_RECORD_FILE 0xc1 -#define CREATE_CYCLIC_RECORD_FILE 0xc0 -#define DELETE_FILE 0xdf -#define AUTHENTICATE 0x0a // AUTHENTICATE_NATIVE -#define AUTHENTICATE_ISO 0x1a // AUTHENTICATE_STANDARD -#define AUTHENTICATE_AES 0xaa -#define CHANGE_KEY_SETTINGS 0x54 -#define GET_KEY_SETTINGS 0x45 -#define CHANGE_KEY 0xc4 -#define GET_KEY_VERSION 0x64 -#define AUTHENTICATION_FRAME 0xAF - +// Ev1 card limits #define MAX_NUM_KEYS 0x0F #define MAX_APPLICATION_COUNT 28 #define MAX_FILE_COUNT 32 #define MAX_FRAME_SIZE 60 -#define NOT_YET_AUTHENTICATED 255 #define FRAME_PAYLOAD_SIZE (MAX_FRAME_SIZE - 5) +#define NOT_YET_AUTHENTICATED 0xFF // status- and error codes | #define OPERATION_OK 0x00 // Successful operation diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index 56963819c..71da93bcc 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -10,12 +10,9 @@ //----------------------------------------------------------------------------- #include "cmdhfmfp.h" - #include - #include "cmdparser.h" // command_t #include "commonutil.h" // ARRAYLEN - #include "comms.h" #include "ui.h" #include "cmdhf14a.h" @@ -27,6 +24,9 @@ #include "mifare/mifaredefault.h" #include "util_posix.h" #include "fileutils.h" +#include "protocols.h" +#include "crypto/libpcrypto.h" + static const uint8_t DefaultKey[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; @@ -34,21 +34,188 @@ uint16_t CardAddresses[] = {0x9000, 0x9001, 0x9002, 0x9003, 0x9004, 0xA000, 0xA0 static int CmdHelp(const char *Cmd); +/* + The 7 MSBits (= n) code the storage size itself based on 2^n, + the LSBit is set to '0' if the size is exactly 2^n + and set to '1' if the storage size is between 2^n and 2^(n+1). + For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. +*/ +static char *getCardSizeStr(uint8_t fsize) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + uint16_t usize = 1 << ((fsize >> 1) + 1); + uint16_t lsize = 1 << (fsize >> 1); + + // is LSB set? + if (fsize & 1) + sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); + return buf; +} + +static char *getProtocolStr(uint8_t id) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (id == 0x05) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + return buf; +} + +static char *getVersionStr(uint8_t major, uint8_t minor) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (major == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); + else if (major == 0x01 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); + else if (major == 0x12 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); +// else if (major == 0x13 && minor == 0x00) +// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); + else if (major == 0x30 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); + + else if (major == 0x11 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("Plus EV1") ")", major, minor); + else + sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); + return buf; +} + +// --- GET SIGNATURE +static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature, int signature_len) { + + // ref: MIFARE Plus EV1 Originality Signature Validation + #define PUBLIC_PLUS_ECDA_KEYLEN 57 + const ecdsa_publickey_t nxp_plus_public_keys[] = { + {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} + }; + + uint8_t i; + int res; + bool is_valid = false; + + for (i = 0; i < ARRAYLEN(nxp_plus_public_keys); i++) { + + int dl = 0; + uint8_t key[PUBLIC_PLUS_ECDA_KEYLEN]; + param_gethex_to_eol(nxp_plus_public_keys[i].value, 0, key, PUBLIC_PLUS_ECDA_KEYLEN, &dl); + + res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP224R1, key, uid, uidlen, signature, signature_len, false); + is_valid = (res == 0); + if (is_valid) + break; + } + if (is_valid == false) { + PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); + return PM3_ESOFT; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_plus_public_keys[i].desc); + PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_plus_public_keys[i].value); + PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 16); + PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 32); + PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 48); + PrintAndLogEx(INFO, " Elliptic curve parameters: NID_secp224r1"); + PrintAndLogEx(INFO, " TAG IC Signature: %s", sprint_hex_inrow(signature, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 16, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 32, 16)); + PrintAndLogEx(INFO, " : %s", sprint_hex_inrow(signature + 48, signature_len - 48)); + PrintAndLogEx(SUCCESS, " Signature verified: " _GREEN_("successful")); + return PM3_SUCCESS; +} + +static int get_plus_signature(uint8_t *signature, int *signature_len) { + + mfpSetVerboseMode(false); + + uint8_t data[59] = {0}; + int resplen = 0, retval = PM3_SUCCESS; + MFPGetSignature(true, false, data, sizeof(data), &resplen); + + if (resplen == 59) { + memcpy(signature, data + 1, 56); + *signature_len = 56; + } else { + *signature_len = 0; + retval = PM3_ESOFT; + } + mfpSetVerboseMode(false); + return retval; +} +// GET VERSION +static int plus_print_version(uint8_t *version) { + PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(version + 14, 7)); + PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(version + 21, 5)); + PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), version[7+7+7+5], version[7+7+7+5+1]); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); + PrintAndLogEx(INFO, " Version: %s", getVersionStr(version[3], version[4])); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); + PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[3], version[4]); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + return PM3_SUCCESS; +} +static int get_plus_version(uint8_t *version, int *version_len) { + + int resplen = 0, retval = PM3_SUCCESS; + mfpSetVerboseMode(false); + MFPGetVersion(true, false, version, *version_len, &resplen); + mfpSetVerboseMode(false); + + *version_len = resplen; + if (resplen != 28) { + retval = PM3_ESOFT; + } + return retval; +} + static int CmdHFMFPInfo(const char *Cmd) { if (Cmd && strlen(Cmd) > 0) PrintAndLogEx(WARNING, "command don't have any parameters.\n"); PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "-- Mifare Plus Tag Information ------------------------------"); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); - // info about 14a part - infoHF14A(false, false, false); + bool supportVersion = false; + bool supportSignature = false; + // version check + uint8_t version[30] = {0}; + int version_len = sizeof(version); + if (get_plus_version(version, &version_len) == PM3_SUCCESS) { + plus_print_version(version); + supportVersion = true; + } else { + // info about 14a part + infoHF14A(false, false, false); + } + // Mifare Plus info SendCommandMIX(CMD_HF_ISO14443A_READER, ISO14A_CONNECT, 0, 0, NULL, 0); - PacketResponseNG resp; WaitForResponse(CMD_ACK, &resp); @@ -57,55 +224,60 @@ static int CmdHFMFPInfo(const char *Cmd) { uint64_t select_status = resp.oldarg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision + // Signature originality check + uint8_t signature[56] = {0}; + int signature_len = sizeof(signature); + if (get_plus_signature(signature, &signature_len) == PM3_SUCCESS) { + plus_print_signature(card.uid, card.uidlen, signature, signature_len); + supportSignature = true; + } + if (select_status == 1 || select_status == 2) { - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(INFO, " Fingerprint"); + PrintAndLogEx(INFO, "--- " _CYAN_("Fingerprint")); + + if (supportVersion && supportSignature) { + PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); + } else { + PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); + } // MIFARE Type Identification Procedure // https://www.nxp.com/docs/en/application-note/AN10833.pdf uint16_t ATQA = card.atqa[0] + (card.atqa[1] << 8); bool isPlus = false; - if (ATQA == 0x0004) { - PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 2K") " (4b UID)"); + if (ATQA & 0x0004) { + PrintAndLogEx(INFO, " SIZE: " _GREEN_("2K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); isPlus = true; } - if (ATQA == 0x0002) { - PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 4K") " (4b UID)"); - isPlus = true; - } - if (ATQA == 0x0044) { - PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 2K") " (7b UID)"); - isPlus = true; - } - if (ATQA == 0x0042) { - PrintAndLogEx(INFO, " ATQA - " _GREEN_("Mifare Plus 4K") " (7b UID)"); + if (ATQA & 0x0002) { + PrintAndLogEx(INFO, " SIZE: " _GREEN_("4K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); isPlus = true; } - uint8_t SLmode = 0xff; + uint8_t SLmode = 0xFF; if (isPlus) { if (card.sak == 0x08) { - PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 2K 7b UID")); + PrintAndLogEx(INFO, " SAK: " _GREEN_("2K 7b UID")); if (select_status == 2) SLmode = 1; } if (card.sak == 0x18) { - PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 4K 7b UID")); + PrintAndLogEx(INFO, " SAK: " _GREEN_("4K 7b UID")); if (select_status == 2) SLmode = 1; } if (card.sak == 0x10) { - PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 2K")); + PrintAndLogEx(INFO, " SAK: " _GREEN_("2K")); if (select_status == 2) SLmode = 2; } if (card.sak == 0x11) { - PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus 4K")); + PrintAndLogEx(INFO, " SAK: " _GREEN_("4K")); if (select_status == 2) SLmode = 2; } } if (card.sak == 0x20) { - PrintAndLogEx(INFO, " SAK - " _GREEN_("Mifare Plus SL0/SL3") "or " _GREEN_("Mifare DESFire")); + PrintAndLogEx(INFO, " SAK: " _GREEN_("MIFARE Plus SL0/SL3") "or " _GREEN_("MIFARE DESFire")); if (card.ats_len > 0) { @@ -118,7 +290,7 @@ static int CmdHFMFPInfo(const char *Cmd) { int res = ExchangeRAW14a(cmd, sizeof(cmd), true, false, data, sizeof(data), &datalen, false); if (memcmp(data, "\x67\x00", 2) == 0) { - PrintAndLogEx(INFO, "\tMost likely a Mifare DESFire tag"); + PrintAndLogEx(INFO, "\tMost likely a MIFARE DESFire tag"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfdes info`")); DropField(); return PM3_SUCCESS; @@ -130,33 +302,35 @@ static int CmdHFMFPInfo(const char *Cmd) { } } - // How do we detect SL0 / SL1 / SL2 / SL3 modes?!? - PrintAndLogEx(INFO, "Security Level (SL)"); - switch(SLmode) { - case 0: - PrintAndLogEx(INFO, "SL 0: initial delivery configuration, used for card personalization"); - break; - case 1: - PrintAndLogEx(INFO, "SL 1: backwards functional compatibility mode (with MIFARE Classic 1K / 4K) with an optional AES authentication"); - break; - case 2: - PrintAndLogEx(INFO, "SL 2: 3-Pass Authentication based on AES followed by MIFARE CRYPTO1 authentication, communication secured by MIFARE CRYPTO1"); - break; - case 3: - PrintAndLogEx(INFO, "SL 3: 3-Pass authentication based on AES, data manipulation commands secured by AES encryption and an AES based MACing method."); - break; - default: - break; - } + if (isPlus) { + // How do we detect SL0 / SL1 / SL2 / SL3 modes?!? + PrintAndLogEx(INFO, "--- " _CYAN_("Security Level (SL)")); - if (SLmode != 0xFF) - PrintAndLogEx(SUCCESS, "\tMifare Plus SL mode: " _YELLOW_("SL%d"), SLmode); - else - PrintAndLogEx(WARNING, "\tMifare Plus SL mode: " _YELLOW_("unknown")); + if (SLmode != 0xFF ) + PrintAndLogEx(SUCCESS, " SL mode: " _YELLOW_("SL%d"), SLmode); + else + PrintAndLogEx(WARNING, " SL mode: " _YELLOW_("unknown")); + switch(SLmode) { + case 0: + PrintAndLogEx(INFO, " SL 0: initial delivery configuration, used for card personalization"); + break; + case 1: + PrintAndLogEx(INFO, " SL 1: backwards functional compatibility mode (with MIFARE Classic 1K / 4K) with an optional AES authentication"); + break; + case 2: + PrintAndLogEx(INFO, " SL 2: 3-Pass Authentication based on AES followed by MIFARE CRYPTO1 authentication, communication secured by MIFARE CRYPTO1"); + break; + case 3: + PrintAndLogEx(INFO, " SL 3: 3-Pass authentication based on AES, data manipulation commands secured by AES encryption and an AES based MACing method."); + break; + default: + break; + } + } } else { PrintAndLogEx(INFO, "\tMifare Plus info not available."); } - + PrintAndLogEx(NORMAL, ""); DropField(); return PM3_SUCCESS; } diff --git a/client/emv/apduinfo.c b/client/emv/apduinfo.c index 35735fb47..b64696628 100644 --- a/client/emv/apduinfo.c +++ b/client/emv/apduinfo.c @@ -503,7 +503,17 @@ void APDUPrint(APDUStruct apdu) { void APDUPrintEx(APDUStruct apdu, size_t maxdatalen) { PrintAndLogEx(INFO, "APDU: %scase=0x%02x cla=0x%02x ins=0x%02x p1=0x%02x p2=0x%02x Lc=0x%02x(%d) Le=0x%02x(%d)", - apdu.extended_apdu ? "[e]" : "", apdu.case_type, apdu.cla, apdu.ins, apdu.p1, apdu.p2, apdu.lc, apdu.lc, apdu.le, apdu.le); + apdu.extended_apdu ? "[e]" : "", + apdu.case_type, + apdu.cla, + apdu.ins, + apdu.p1, + apdu.p2, + apdu.lc, + apdu.lc, + apdu.le, + apdu.le + ); if (maxdatalen > 0) PrintAndLogEx(INFO, "data: %s%s", sprint_hex(apdu.data, MIN(apdu.lc, maxdatalen)), apdu.lc > maxdatalen ? "..." : ""); } diff --git a/client/emv/emvcore.c b/client/emv/emvcore.c index fe5ff3a31..852d801c7 100644 --- a/client/emv/emvcore.c +++ b/client/emv/emvcore.c @@ -136,6 +136,10 @@ void SetAPDULogging(bool logging) { APDULogging = logging; } +bool GetAPDULogging(void) { + return APDULogging; +} + enum CardPSVendor GetCardPSVendor(uint8_t *AID, size_t AIDlen) { char buf[100] = {0}; if (AIDlen < 1) diff --git a/client/emv/emvcore.h b/client/emv/emvcore.h index d5dccd037..1c422e483 100644 --- a/client/emv/emvcore.h +++ b/client/emv/emvcore.h @@ -57,6 +57,7 @@ struct tlvdb *GetPANFromTrack2(const struct tlv *track2); struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2); void SetAPDULogging(bool logging); +bool GetAPDULogging(void); // exchange int EMVExchange(EMVCommandChannel channel, bool LeaveFieldON, sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw, struct tlvdb *tlv); diff --git a/client/luascripts/legic.lua b/client/luascripts/legic.lua index 7e0f8d3be..393cc9e52 100644 --- a/client/luascripts/legic.lua +++ b/client/luascripts/legic.lua @@ -91,14 +91,20 @@ CRC1 = crc8 over addr 0x00..0x03+0x07..0x0E (special 'gantner crc8') CRC2 = MCD + MSB0..2+ addr 0x06 + addr 0x05 + addr 0x07 + Stamp (regular Master-Token-CRC) --]] +--[[ +Known issues; needs to be fixed: +* last byte in last segment is handled incorrectly when it is the last bytes on the card itself (MIM256: => byte 256) +--]] + example = "script run legic" -author = "Mosci" -version = "1.0.3" +author = "Mosci, uhei" +version = "1.0.4" desc = [[ This script helps you to read, create and modify Legic Prime Tags (MIM22, MIM256, MIM1024) +The virtual tag (and therefore the file to be saved) is always a MIM1024 tag. it's kinda interactive with following commands in three categories: Data I/O Segment Manipulation Token-Data @@ -108,8 +114,8 @@ it's kinda interactive with following commands in three categories: ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -128,8 +134,8 @@ it's kinda interactive with following commands in three categories: without the need of changing anything - MCD,MSN,MCC will be read from the tag before and applied to the output. - lf: 'load file' - load a (xored) file from the local Filesystem into the 'virtual inTag' - sf: 'save file' - saves the 'virtual inTag' to the local Filesystem (xored with Tag-MCC) + lf: 'load file' - load a (xored) binary file (*.bin) from the local Filesystem into the 'virtual inTag' + sf: 'save file' - saves the 'virtual inTag' to the local Filesystem as eml and bin (xored with Tag-MCC) xf: 'xor file' - saves the 'virtual inTag' to the local Filesystem (xored with choosen MCC - use '00' for plain values) ct: 'copy tag' - copy the 'virtual Tag' to a second 'virtual TAG' - not usefull yet, but inernally needed @@ -242,6 +248,16 @@ function istable(t) return type(t) == 'table' end +--- +-- To have two char string for a byte +local function padString(str) + if (#str == 1) then + return '0'..str + end + + return str +end + --- -- creates a 'deep copy' of a table (a=b only references) function deepCopy(object) @@ -387,15 +403,15 @@ end function bytesToTag(bytes, tag) if istable(tag) == false then return oops("tag is no table in: bytesToTag ("..type(tag)..")") end - tag.MCD =bytes[1]; - tag.MSN0=bytes[2]; - tag.MSN1=bytes[3]; - tag.MSN2=bytes[4]; - tag.MCC =bytes[5]; - tag.DCFl=bytes[6]; - tag.DCFh=bytes[7]; - tag.raw =bytes[8]; - tag.SSC =bytes[9]; + tag.MCD =padString(bytes[1]); + tag.MSN0=padString(bytes[2]); + tag.MSN1=padString(bytes[3]); + tag.MSN2=padString(bytes[4]); + tag.MCC =padString(bytes[5]); + tag.DCFl=padString(bytes[6]); + tag.DCFh=padString(bytes[7]); + tag.raw =padString(bytes[8]); + tag.SSC =padString(bytes[9]); tag.Type=getTokenType(tag.DCFl); tag.OLE=bbit("0x"..tag.DCFl,7,1) tag.WRP=("%d"):format(bbit("0x"..bytes[8],0,4)) @@ -500,42 +516,26 @@ function tagToBytes(tag) return bytes end + +--- --- PM3 I/O --- ---- --- read from pm3 into virtual-tag -function readFromPM3() - local tag, bytes, infile - infile="legic.temp" - -- core.console("hf legic reader") - -- core.console("hf legic esave "..infile) - core.console("hf legic dump o "..infile) - tag=readFile(infile..".bin") - return tag -end - -local function padString(str) - if (#str == 1) then - return '0'..str - end - - return str -end - ---- -- write virtual Tag to real Tag function writeToTag(tag) local bytes - local filename = 'MylegicClone.hex' local taglen = 22 - if(utils.confirm(acred.."\nplace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then + local writeDCF = false + if(utils.confirm(acred.."\nPlace the (empty) Tag onto the PM3\nand confirm writing to this Tag: "..acoff) == false) then return end + if(utils.confirm(acred.."\nShould the decremental field (DCF) be written?: "..acoff) == true) then + writeDCF = true + end -- get used bytes / tag-len if (istable(tag.SEG)) then if (istable(tag.Bck)) then for i=0, #tag.SEG do - taglen = taglen + tag.SEG[i] . len + 5 + taglen = taglen + tag.SEG[i] . len end end local uid_old = tag.MCD..tag.MSN0..tag.MSN1..tag.MSN2 @@ -571,37 +571,32 @@ function writeToTag(tag) bytes[22] = calcMtCrc(bytes) end if (bytes) then - print("write temp-file '"..filename.."'") - print(accyan) - writeFile(bytes, filename..".bin") - print(acoff) + bytes = xorBytes(bytes,tag.MCC) end end + -- write data to file if (taglen > 0) then WriteBytes = input(acyellow.."enter number of bytes to write?"..acoff, taglen) - -- load file into pm3-buffer - if (type(filename) ~= "string") then - filename = input(acyellow.."filename to load to pm3-buffer?"..acoff, "legic.temp") - end - - cmd = 'hf legic eload 2 '..filename - core.console(cmd) -- write pm3-buffer to Tag - for i=0, WriteBytes do - if (i > 6) then - cmd = ("hf legic write o %x d %s "):format(i, padString(bytes[i])) + for i=1, WriteBytes do + if (i > 7) then + cmd = ("hf legic wrbl o %02x d %s "):format(i-1, padString(bytes[i])) print(acgreen..cmd..acoff) core.console(cmd) core.clearCommandBuffer() + elseif (i == 7) then + if (writeDCF) then + -- write DCF in reverse order (requires 'mosci-patch') + cmd = ('hf legic wrbl o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) + print(acgreen..cmd..acoff) + core.console(cmd) + core.clearCommandBuffer() + else + print(acgreen.."skip byte 0x05-0x06 - DCF"..acoff) + end elseif (i == 6) then - -- write DCF in reverse order (requires 'mosci-patch') - cmd = ('hf legic write o 05 d %s%s'):format(padString(bytes[i-1]), padString(bytes[i])) - print(acgreen..cmd..acoff) - core.console(cmd) - core.clearCommandBuffer() - elseif (i == 5) then print(acgreen.."skip byte 0x05 - will be written next step"..acoff) else print(acgreen.."skip byte 0x00-0x04 - unwritable area"..acoff) @@ -641,12 +636,12 @@ end local function save_BIN(data, filename) local outfile local counter = 1 - local ext = filename:match("^.+(%..+)$") or '' - local fn = filename + local ext = ".bin" + local fn = filename..ext -- Make sure we don't overwrite a file while file_check(fn) do - fn = filename:gsub(ext, tostring(counter)..ext) + fn = filename..ext:gsub(ext, "-"..tostring(counter)..ext) counter = counter + 1 end @@ -664,26 +659,27 @@ end --- -- write bytes to file function writeFile(bytes, filename) - if (filename ~= 'MylegicClone.hex') then - if (file_check(filename)) then - local answer = confirm("\nthe output-file "..filename.." already exists!\nthis will delete the previous content!\ncontinue?") + local emlext = ".eml" + if (filename ~= 'MyLegicClone') then + if (file_check(filename..emlext)) then + local answer = confirm("\nthe output-file "..filename..emlext.." already exists!\nthis will delete the previous content!\ncontinue?") if not answer then return print("user abort") end end end local line local bcnt = 0 - local fho, err = io.open(filename, "w") + local fho, err = io.open(filename..emlext, "w") if err then - return oops("OOps ... failed to open output-file ".. filename) + return oops("OOps ... failed to open output-file ".. filename..emlext) end bytes = xorBytes(bytes, bytes[5]) for i = 1, #bytes do if (bcnt == 0) then - line = bytes[i] + line = padString(bytes[i]) elseif (bcnt <= 7) then - line = line.." "..bytes[i] + line = line.." "..padString(bytes[i]) end if (bcnt == 7) then -- write line to new file @@ -699,7 +695,7 @@ function writeFile(bytes, filename) -- save binary local fn_bin, fn_bin_num = save_BIN(bytes, filename) - print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..acoff) + print("\nwrote "..acyellow..(#bytes * 3)..acoff.." bytes to " ..acyellow..filename..emlext..acoff) if fn_bin and fn_bin_num then print("\nwrote "..acyellow..fn_bin_num..acoff.." bytes to BINARY file "..acyellow..fn_bin..acoff) @@ -708,6 +704,21 @@ function writeFile(bytes, filename) return true end +--- +-- read from pm3 into virtual-tag +function readFromPM3() + local tag, bytes, infile + --infile="legic.temp" + infile=os.tmpname() + core.console("hf legic dump f "..infile) + tag=readFile(infile..".bin") + os.remove(infile) + os.remove(infile..".bin") + os.remove(infile..".eml") + os.remove(infile..".json") + return tag +end + --- Map related --- --- -- make tagMap @@ -2265,8 +2276,8 @@ function modifyHelp() ed => edit Segment Data tk => toggle KGH-Flag File I/O rs => remove Segment ----------------- cc => check Segment-CRC - lf => load File ck => check KGH - sf => save File ds => dump Segments + lf => load bin File ck => check KGH + sf => save eml/bin File ds => dump Segments xf => xor to File @@ -2352,10 +2363,10 @@ function modifyMode() -- save values of mainTAG to a file (xored with MCC of mainTAG) ["sf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) bytes = tagToBytes(inTAG) --bytes=xorBytes(bytes, inTAG.MCC) - if bytes then + if (bytes) then writeFile(bytes, outfile) end end @@ -2364,7 +2375,7 @@ function modifyMode() -- save values of mainTAG to a file (xored with 'specific' MCC) ["xf"] = function(x) if istable(inTAG) then - outfile = input("enter filename:", "legic.temp") + outfile = input("enter filename:", "hf-legic-"..inTAG.MCD..inTAG.MSN0..inTAG.MSN1..inTAG.MSN2) crc = input("enter new crc: ('00' for a plain dump)", inTAG.MCC) print("obfuscate with: "..crc) bytes=tagToBytes(inTAG) diff --git a/client/mifare/mifare4.c b/client/mifare/mifare4.c index 966a2027d..848528611 100644 --- a/client/mifare/mifare4.c +++ b/client/mifare/mifare4.c @@ -429,6 +429,46 @@ int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data return 0; } +int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { + uint8_t c[] = {0x3c, 0x00}; + return intExchangeRAW14aPlus(c, sizeof(c), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); +} + +int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { + uint8_t tmp[20] = {0}; + uint8_t c[] = {0x60}; + int res = intExchangeRAW14aPlus(c, sizeof(c), activateField, true, tmp, maxdataoutlen, dataoutlen); + if (res != 0) { + DropField(); + *dataoutlen = 0; + return res; + } + + memcpy(dataout, tmp + 1, (*dataoutlen - 3)); + + *dataoutlen = 0; + // MFDES_ADDITIONAL_FRAME + if (tmp[0] == 0xAF) { + c[0] = 0xAF; + res = intExchangeRAW14aPlus(c, sizeof(c), false, true, tmp, maxdataoutlen, dataoutlen); + if (res == 0) { + + memcpy(dataout + 7, tmp + 1, (*dataoutlen - 3)); + + // MFDES_ADDITIONAL_FRAME + res = intExchangeRAW14aPlus(c, sizeof(c), false, false, tmp, maxdataoutlen, dataoutlen); + if (res == 0) { + if (tmp[0] == 0x90) { + memcpy(dataout + 7 + 7, tmp + 1, (*dataoutlen - 3)); + *dataoutlen = 28; + } + } + } + } + DropField(); + return res; +} + // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards), // plus evtl. 8 sectors with 16 blocks each (4k cards) uint8_t mfNumBlocksPerSector(uint8_t sectorNo) { diff --git a/client/mifare/mifare4.h b/client/mifare/mifare4.h index cb2c8d652..0c3e08458 100644 --- a/client/mifare/mifare4.h +++ b/client/mifare/mifare4.h @@ -59,6 +59,9 @@ int MFPReadBlock(mf4Session_t *session, bool plain, uint8_t blockNum, uint8_t bl int MFPWriteBlock(mf4Session_t *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac); int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose); +int MFPGetSignature(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); +int MFPGetVersion(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); + const char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data); uint8_t mfNumBlocksPerSector(uint8_t sectorNo); diff --git a/client/settings.c b/client/settings.c index 976121eed..79fa00fd1 100644 --- a/client/settings.c +++ b/client/settings.c @@ -44,8 +44,7 @@ #include "emv/emvjson.h" // Load all settings into memory (struct) -int settings_load (void) -{ +int settings_load (void) { // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; @@ -68,25 +67,27 @@ int settings_load (void) int window_ypos; int window_hsize; int window_wsize; + bool use_emojis + bool use_hints */ - printf (" Settings Version : [%s]\n",mySettings.version); - printf (" os_windows_usecolor (bool) : [%d]\n",mySettings.os_windows_usecolor); - printf (" os_windows_useAnsicolor (bool) : [%d]\n",mySettings.os_windows_useansicolor); - printf (" window_xpos (int) : [%d]\n",mySettings.window_xpos); - printf (" window_ypos (int) : [%d]\n",mySettings.window_ypos); - printf (" window_hsize (int) : [%d]\n",mySettings.window_hsize); - printf (" window_wsize (int) : [%d]\n",mySettings.window_wsize); - + printf (" Settings Version : [%s]\n", mySettings.version); + printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); + printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); + printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); + printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); + printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); + printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); + printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); + printf (" use hints (bool) : [%d]\n", mySettings.use_hints); return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save (void) -{ +int settings_save(void) { // Note sure if backup has value ? char backupFilename[500]; - snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -105,18 +106,14 @@ int settings_save (void) uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - // int saveFileJSON(const char *preferredName, JSONFileType ftype, uint8_t *data, size_t datalen); - if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); return PM3_SUCCESS; } -void settings_save_callback (json_t *root) -{ - // extern settings_t mySettings; - +void settings_save_callback(json_t *root) { + printf ("==> Save Settings\n"); //JsonSaveStr(root, "FileType", "settings"); //JsonSaveStr (root,"Test1.Test2","test settings"); @@ -131,23 +128,24 @@ void settings_save_callback (json_t *root) */ JsonSaveStr (root,"FileType","settings"); JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); - JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); - JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); - JsonSaveInt (root,"window.xpos",mySettings.window_xpos); - JsonSaveInt (root,"window.ypos",mySettings.window_ypos); - JsonSaveInt (root,"window.hsize",mySettings.window_hsize); - JsonSaveInt (root,"window.wsize",mySettings.window_wsize); + JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); + JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); + JsonSaveInt (root,"window.xpos", mySettings.window_xpos); + JsonSaveInt (root,"window.ypos", mySettings.window_ypos); + JsonSaveInt (root,"window.hsize", mySettings.window_hsize); + JsonSaveInt (root,"window.wsize", mySettings.window_wsize); + JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); + JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); } -void settings_load_callback (json_t *root) -{ -// extern settings_t mySettings; +void settings_load_callback(json_t *root) { + json_error_t up_error = {0}; int b1; int i1; const char *s1; - if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) + if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); else strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); @@ -180,5 +178,17 @@ void settings_load_callback (json_t *root) mySettings.window_wsize = i1; else // default mySettings.window_wsize = 0; + + // Use EMOJIS + if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) + mySettings.use_emojis = b1; + else // default + mySettings.use_emojis = false; + + // Use Hints + if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) + mySettings.use_hints = b1; + else // default + mySettings.use_hints = false; } diff --git a/client/settings.h b/client/settings.h index 799af7caa..4bf8b2a5e 100644 --- a/client/settings.h +++ b/client/settings.h @@ -24,6 +24,8 @@ typedef struct { int window_ypos; int window_hsize; int window_wsize; + bool use_emojis; + bool use_hints; } settings_t; // Settings struct so as to be available to other modules by including settings.h diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index e727180bf..3fba71e1c 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -18,7 +18,7 @@ Always use the latest repository commits from *master* branch. There are always * [File not found](#file-not-found) * [Pixmap / pixbuf warnings](#pixmap--pixbuf-warnings) * [Usb cable](#usb-cable) - * [WSL 2 explorer.exe . doesnt work](WSL-2) + * [WSL 2 explorer.exe . doesnt work](#WSL-2) ## `pm3` or `pm3-flash*` doesn't see my Proxmark diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index d97fae6ed..6ce271aab 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -618,6 +618,11 @@ typedef struct { #define PM3_EOUTOFBOUND -17 // exchange with card error client/pm3: error when cant get answer from card or got an incorrect answer #define PM3_ECARDEXCHANGE -18 + +// Failed to create APDU, +#define PM3_EAPDU_ENCODEFAIL -19 +// APDU responded with a failure code +#define PM3_EAPDU_FAIL -20 // No data pm3: no data available, no host frame available (not really an error) #define PM3_ENODATA -98 // Quit program client: reserved, order to quit the program diff --git a/include/protocols.h b/include/protocols.h index 89038a789..03953fcc6 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -349,44 +349,62 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // 6x xx = ERROR // MIFARE DESFire command set: -#define MFDES_CREATE_APPLICATION 0xca -#define MFDES_DELETE_APPLICATION 0xda -#define MFDES_GET_APPLICATION_IDS 0x6a -#define MFDES_SELECT_APPLICATION 0x5a -#define MFDES_FORMAT_PICC 0xfc + + #define MFDES_GET_VERSION 0x60 -#define MFDES_READ_DATA 0xbd -#define MFDES_WRITE_DATA 0x3d -#define MFDES_GET_VALUE 0x6c -#define MFDES_CREDIT 0x0c -#define MFDES_DEBIT 0xdc -#define MFDES_LIMITED_CREDIT 0x1c -#define MFDES_WRITE_RECORD 0x3b -#define MFDES_READ_RECORDS 0xbb -#define MFDES_CLEAR_RECORD_FILE 0xeb -#define MFDES_COMMIT_TRANSACTION 0xc7 -#define MFDES_ABORT_TRANSACTION 0xa7 -#define MFDES_GET_FREE_MEMORY 0x6e -#define MFDES_GET_FILE_IDS 0x6f -#define MFDES_GET_ISOFILE_IDS 0x61 -#define MFDES_GET_FILE_SETTINGS 0xf5 -#define MFDES_CHANGE_FILE_SETTINGS 0x5f -#define MFDES_CREATE_STD_DATA_FILE 0xcd -#define MFDES_CREATE_BACKUP_DATA_FILE 0xcb -#define MFDES_CREATE_VALUE_FILE 0xcc -#define MFDES_CREATE_LINEAR_RECORD_FILE 0xc1 -#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xc0 -#define MFDES_DELETE_FILE 0xdf -#define MFDES_AUTHENTICATE 0x0a // AUTHENTICATE_NATIVE -#define MFDES_AUTHENTICATE_ISO 0x1a // AUTHENTICATE_STANDARD -#define MFDES_AUTHENTICATE_AES 0xaa -#define MFDES_CHANGE_KEY_SETTINGS 0x54 + +#define MFDES_AUTHENTICATE 0x0A // AUTHENTICATE_NATIVE +#define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD +#define MFDES_AUTHENTICATE_AES 0xAA + +#define MFDES_CREDIT 0x0C +#define MFDES_LIMITED_CREDIT 0x1C +#define MFDES_DEBIT 0xDC + +#define MFDES_WRITE_RECORD 0x3B +#define MFDES_READSIG 0x3C +#define MFDES_WRITE_DATA 0x3D + #define MFDES_GET_KEY_SETTINGS 0x45 -#define MFDES_CHANGE_KEY 0xc4 +#define MFDES_CHANGE_KEY_SETTINGS 0x54 +#define MFDES_SELECT_APPLICATION 0x5A +#define MFDES_CHANGE_FILE_SETTINGS 0x5F +#define MFDES_GET_ISOFILE_IDS 0x61 #define MFDES_GET_KEY_VERSION 0x64 +#define MFDES_GET_APPLICATION_IDS 0x6A +#define MFDES_GET_VALUE 0x6C +#define MFDES_GET_FREE_MEMORY 0x6E +#define MFDES_GET_DF_NAMES 0x6D +#define MFDES_GET_FILE_IDS 0x6F + + +#define MFDES_ABORT_TRANSACTION 0xA7 #define MFDES_AUTHENTICATION_FRAME 0xAF #define MFDES_ADDITIONAL_FRAME 0xAF -#define MFDES_READSIG 0x3C +#define MFDES_ADDITIONAL_FRAME_RESP 0x91AF +#define MFDES_SUCCESS_FRAME_RESP 0x9100 +#define MFDES_EAUTH_RESP 0x91AE +#define MFDES_ENO_SUCH_KEY_RESP 0x9140 + +#define MFDES_READ_RECORDS 0xBB +#define MFDES_READ_DATA 0xBD + +#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 +#define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 +#define MFDES_CHANGE_KEY 0xC4 +#define MFDES_COMMIT_TRANSACTION 0xC7 +#define MFDES_CREATE_APPLICATION 0xCA +#define MFDES_CREATE_BACKUP_DATA_FILE 0xCB +#define MFDES_CREATE_VALUE_FILE 0xCC +#define MFDES_CREATE_STD_DATA_FILE 0xCD + +#define MFDES_CLEAR_RECORD_FILE 0xEB + +#define MFDES_DELETE_APPLICATION 0xDA +#define MFDES_DELETE_FILE 0xDF + +#define MFDES_GET_FILE_SETTINGS 0xF5 +#define MFDES_FORMAT_PICC 0xFC // LEGIC Commands #define LEGIC_MIM_22 0x0D From 1b8b8f012876b37b770a36663857b69ac60c8fe9 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 15:04:11 +1000 Subject: [PATCH 31/66] Settings Added --- client/proxguiqt.cpp | 7 +- client/proxmark3.c | 10 +- client/settings.c | 212 +++++++++++++++++++++++++------------------ client/settings.h | 20 +--- client/ui.h | 6 ++ 5 files changed, 143 insertions(+), 112 deletions(-) diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index dc67953e6..dd5fd3f24 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -26,6 +26,7 @@ #include #include "proxgui.h" #include +#include "ui.h" extern "C" { #include "util_darwin.h" @@ -168,7 +169,11 @@ void ProxWidget::vchange_dthr_down(int v) { } ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { this->master = master; - resize(800, 400); + // Set the initail postion and size from settings + if (session.settings_loaded) + setGeometry (session.window_plot_xpos,session.window_plot_ypos,session.window_plot_wsize,session.window_plot_hsize); + else + resize(800, 400); // Setup the controller widget controlWidget = new QWidget(); diff --git a/client/proxmark3.c b/client/proxmark3.c index 0438f81ad..869df5996 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -582,10 +582,14 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); - // Settings Load and Test - // settings_load (); + // Load Settings and assign + // This will allow the command line to override the settings.json values + settings_load (); + + // quick patch for debug level + g_debugMode = session.logging_level; + // settings_save (); - // printf ("Ver : %s\n",mySettings.version); // End Settings for (int i = 1; i < argc; i++) { diff --git a/client/settings.c b/client/settings.c index 79fa00fd1..aeed31c7a 100644 --- a/client/settings.c +++ b/client/settings.c @@ -39,55 +39,62 @@ // Settings Functions //----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// Notes +// To add a new setting +// Add the new setting to the session_arg_t; in ui.h +// Add the default value for the setting in the settings_load page below +// Update the settings_load_callback to load your setting into the stucture +// Update the settings_save_callback to enusre your setting gets saved (not used yet) +// Include "settingdata.h" (if needed) in the source file where you wish to use the setting +// use the setting as needed : mySettings. +// Should use if (mySettings.loaded) { use settings } +//----------------------------------------------------------------------------- + #include "settings.h" #include "comms.h" #include "emv/emvjson.h" +#include // Load all settings into memory (struct) int settings_load (void) { + + // Set all defaults +// mySettings.os_windows_usecolor = false; +// mySettings.os_windows_useansicolor = false; + session.logging_level = NORMAL; + session.window_plot_xpos = 10; + session.window_plot_ypos = 30; + session.window_plot_hsize = 400; + session.window_plot_wsize = 800; +// mySettings.window_xpos = 10; +// mySettings.window_ypos = 210; +// mySettings.window_hsize = 300; +// mySettings.window_wsize = 500; +// mySettings.show_emoji = ALIAS; + session.emoji_mode = ALIAS; + session.show_hints = false; + // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - // clear all settings - memset (&mySettings,0x00,sizeof(mySettings)); - if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { - printf ("==> Settings Loaded\n"); - mySettings.loaded = true; + session.settings_loaded = true; } - - - // Test results - /* - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis - bool use_hints - */ - printf (" Settings Version : [%s]\n", mySettings.version); - printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); - printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); - printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); - printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); - printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); - printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); - printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); - printf (" use hints (bool) : [%d]\n", mySettings.use_hints); + else // Save default/create settings.json file + settings_save (); + return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save(void) { +int settings_save (void) { // Note sure if backup has value ? char backupFilename[500]; - snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -95,7 +102,7 @@ int settings_save(void) { return PM3_ESOFT; } } - + if (fileExists (settingsFilename)) { if (rename (settingsFilename,backupFilename) != 0) { PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",settingsFilename,backupFilename); @@ -105,90 +112,115 @@ int settings_save(void) { uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - + if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); - + return PM3_SUCCESS; } -void settings_save_callback(json_t *root) { - - printf ("==> Save Settings\n"); - //JsonSaveStr(root, "FileType", "settings"); - //JsonSaveStr (root,"Test1.Test2","test settings"); - /* - "version": "1.0 Nov 2019", - "os.windows.usecolor": true, - "os.windows.useAnsiColor": true, - "window.xpos": 10, - "window.ypos": 10, - "window.hsize": 300, - "window.wsize": 600 - */ - JsonSaveStr (root,"FileType","settings"); - JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); - JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); - JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); - JsonSaveInt (root,"window.xpos", mySettings.window_xpos); - JsonSaveInt (root,"window.ypos", mySettings.window_ypos); - JsonSaveInt (root,"window.hsize", mySettings.window_hsize); - JsonSaveInt (root,"window.wsize", mySettings.window_wsize); - JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); - JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); +void settings_save_callback (json_t *root) { + JsonSaveStr (root,"FileType","settings"); +// JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); +// JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); + // Log level, convert to text + // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); + switch (session.logging_level) { + case NORMAL: JsonSaveStr (root,"logging.level","normal"); break; + case SUCCESS: JsonSaveStr (root,"logging.level","success"); break; + case INFO: JsonSaveStr (root,"logging.level","info"); break; + case FAILED: JsonSaveStr (root,"logging.level","failed"); break; + case WARNING: JsonSaveStr (root,"logging.level","warning"); break; + case ERR: JsonSaveStr (root,"logging.level","err"); break; + case DEBUG: JsonSaveStr (root,"logging.level","debug"); break; + case INPLACE: JsonSaveStr (root,"logging.level","inplace"); break; + case HINT: JsonSaveStr (root,"logging.level","hint"); break; + default: + JsonSaveStr (root,"logging.level","NORMAL"); + } + + // Plot window + JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); + JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); + JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); + JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); +// JsonSaveInt (root,"window.xpos",mySettings.window_xpos); +// JsonSaveInt (root,"window.ypos",mySettings.window_ypos); +// JsonSaveInt (root,"window.hsize",mySettings.window_hsize); +// JsonSaveInt (root,"window.wsize",mySettings.window_wsize); + + // Emoji + switch (session.emoji_mode) { + case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; + case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; + case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; + case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; + default: + JsonSaveStr (root,"show.emoji","ALIAS"); + } + JsonSaveBoolean (root,"show.hints",session.show_hints); } -void settings_load_callback(json_t *root) { - +void settings_load_callback (json_t *root) { json_error_t up_error = {0}; - int b1; + bool b1; int i1; const char *s1; - - if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) - strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); - else - strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); - + + // Left for example of a string json read +// if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) +// strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); +/* // os.windows... if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useColor",&b1) == 0) mySettings.os_windows_usecolor = b1; - else // default - mySettings.os_windows_useansicolor = false; - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useAnsiColor",&b1) == 0) mySettings.os_windows_useansicolor = b1; - else // default - mySettings.os_windows_useansicolor = false; +*/ + // Logging Level +// typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; + if (json_unpack_ex(root,&up_error, 0, "{s:s}","logging.level",&s1) == 0) { + if (strncasecmp (s1,"NORMAL",7) == 0) session.logging_level = NORMAL; + if (strncasecmp (s1,"SUCCESS",8) == 0) session.logging_level = SUCCESS; + if (strncasecmp (s1,"INFO",4) == 0) session.logging_level = INFO; + if (strncasecmp (s1,"FAILED",6) == 0) session.logging_level = FAILED; + if (strncasecmp (s1,"WARNING",7) == 0) session.logging_level = WARNING; + if (strncasecmp (s1,"ERR",3) == 0) session.logging_level = ERR; + if (strncasecmp (s1,"DEBUG",5) == 0) session.logging_level = DEBUG; + if (strncasecmp (s1,"INPLACE",7) == 0) session.logging_level = INPLACE; + if (strncasecmp (s1,"HINT",7) == 0) session.logging_level = HINT; + } + // window plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) + session.window_plot_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) + session.window_plot_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) + session.window_plot_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) + session.window_plot_wsize = i1; +/* // window... if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.xpos",&i1) == 0) mySettings.window_xpos = i1; - else // default - mySettings.window_xpos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.ypos",&i1) == 0) mySettings.window_ypos = i1; - else // default - mySettings.window_ypos = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.hsize",&i1) == 0) mySettings.window_hsize = i1; - else // default - mySettings.window_hsize = 0; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.wsize",&i1) == 0) mySettings.window_wsize = i1; - else // default - mySettings.window_wsize = 0; - - // Use EMOJIS - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) - mySettings.use_emojis = b1; - else // default - mySettings.use_emojis = false; - - // Use Hints - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) - mySettings.use_hints = b1; - else // default - mySettings.use_hints = false; + +*/ + // show options + // typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","show.emoji",&s1) == 0) { + if (strncasecmp (s1,"ALIAS",5) == 0) session.emoji_mode = ALIAS; + if (strncasecmp (s1,"EMOJI",5) == 0) session.emoji_mode = EMOJI; + if (strncasecmp (s1,"ALTTEXT",7) == 0) session.emoji_mode = ALTTEXT; + if (strncasecmp (s1,"ERASE",5) == 0) session.emoji_mode = ERASE; + } + if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) + session.show_hints = b1; } diff --git a/client/settings.h b/client/settings.h index 4bf8b2a5e..c404a82e2 100644 --- a/client/settings.h +++ b/client/settings.h @@ -8,29 +8,13 @@ //----------------------------------------------------------------------------- // Settings Functions //----------------------------------------------------------------------------- -#ifndef settings_h -#define settings_h +#ifndef SETTINGS_H_ +#define SETTINGS_H_ #include "fileutils.h" #define settingsFilename "settings.json" -typedef struct { - bool loaded; - char version[20]; - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis; - bool use_hints; -} settings_t; - -// Settings struct so as to be available to other modules by including settings.h -settings_t mySettings; - int settings_load (void); int settings_save (void); diff --git a/client/ui.h b/client/ui.h index 5bb814b81..aea04b6ce 100644 --- a/client/ui.h +++ b/client/ui.h @@ -21,6 +21,7 @@ typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLA typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; typedef struct { + bool settings_loaded; bool stdinOnTTY; bool stdoutOnTTY; bool supports_colors; @@ -28,6 +29,11 @@ typedef struct { bool pm3_present; bool help_dump_mode; bool show_hints; + int window_plot_xpos; + int window_plot_ypos; + int window_plot_hsize; + int window_plot_wsize; + logLevel_t logging_level; } session_arg_t; extern session_arg_t session; From 970b2bf2cb1c776da5ad4510696312225867bcb5 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 16:14:43 +1000 Subject: [PATCH 32/66] debug level fix --- client/proxmark3.c | 3 +-- client/settings.c | 36 ++++++++++++------------------------ 2 files changed, 13 insertions(+), 26 deletions(-) diff --git a/client/proxmark3.c b/client/proxmark3.c index 869df5996..2c20afa17 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -588,10 +588,9 @@ int main(int argc, char *argv[]) { // quick patch for debug level g_debugMode = session.logging_level; - // settings_save (); // End Settings - + for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { diff --git a/client/settings.c b/client/settings.c index aeed31c7a..64aec90ba 100644 --- a/client/settings.c +++ b/client/settings.c @@ -62,7 +62,7 @@ int settings_load (void) { // Set all defaults // mySettings.os_windows_usecolor = false; // mySettings.os_windows_useansicolor = false; - session.logging_level = NORMAL; + session.logging_level = 0; session.window_plot_xpos = 10; session.window_plot_ypos = 30; session.window_plot_hsize = 400; @@ -126,15 +126,9 @@ void settings_save_callback (json_t *root) { // Log level, convert to text // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); switch (session.logging_level) { - case NORMAL: JsonSaveStr (root,"logging.level","normal"); break; - case SUCCESS: JsonSaveStr (root,"logging.level","success"); break; - case INFO: JsonSaveStr (root,"logging.level","info"); break; - case FAILED: JsonSaveStr (root,"logging.level","failed"); break; - case WARNING: JsonSaveStr (root,"logging.level","warning"); break; - case ERR: JsonSaveStr (root,"logging.level","err"); break; - case DEBUG: JsonSaveStr (root,"logging.level","debug"); break; - case INPLACE: JsonSaveStr (root,"logging.level","inplace"); break; - case HINT: JsonSaveStr (root,"logging.level","hint"); break; + case 0: JsonSaveStr (root,"logging.level","off"); break; + case 1: JsonSaveStr (root,"logging.level","on"); break; + case 2: JsonSaveStr (root,"logging.level","full"); break; default: JsonSaveStr (root,"logging.level","NORMAL"); } @@ -180,15 +174,9 @@ void settings_load_callback (json_t *root) { // Logging Level // typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; if (json_unpack_ex(root,&up_error, 0, "{s:s}","logging.level",&s1) == 0) { - if (strncasecmp (s1,"NORMAL",7) == 0) session.logging_level = NORMAL; - if (strncasecmp (s1,"SUCCESS",8) == 0) session.logging_level = SUCCESS; - if (strncasecmp (s1,"INFO",4) == 0) session.logging_level = INFO; - if (strncasecmp (s1,"FAILED",6) == 0) session.logging_level = FAILED; - if (strncasecmp (s1,"WARNING",7) == 0) session.logging_level = WARNING; - if (strncasecmp (s1,"ERR",3) == 0) session.logging_level = ERR; - if (strncasecmp (s1,"DEBUG",5) == 0) session.logging_level = DEBUG; - if (strncasecmp (s1,"INPLACE",7) == 0) session.logging_level = INPLACE; - if (strncasecmp (s1,"HINT",7) == 0) session.logging_level = HINT; + if (strncmp (s1,"off",3) == 0) session.logging_level = 0; + if (strncmp (s1,"on",2) == 0) session.logging_level = 1; + if (strncmp (s1,"full",4) == 0) session.logging_level = 2; } // window plot @@ -214,11 +202,11 @@ void settings_load_callback (json_t *root) { */ // show options // typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","show.emoji",&s1) == 0) { - if (strncasecmp (s1,"ALIAS",5) == 0) session.emoji_mode = ALIAS; - if (strncasecmp (s1,"EMOJI",5) == 0) session.emoji_mode = EMOJI; - if (strncasecmp (s1,"ALTTEXT",7) == 0) session.emoji_mode = ALTTEXT; - if (strncasecmp (s1,"ERASE",5) == 0) session.emoji_mode = ERASE; + if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { + if (strncmp (s1,"alias",5) == 0) session.emoji_mode = ALIAS; + if (strncmp (s1,"emoji",5) == 0) session.emoji_mode = EMOJI; + if (strncmp (s1,"alttext",7) == 0) session.emoji_mode = ALTTEXT; + if (strncmp (s1,"erase",5) == 0) session.emoji_mode = ERASE; } if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) session.show_hints = b1; From 9fc232390b7f80eb68525f47438a84d09803a601 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 18:20:02 +1000 Subject: [PATCH 33/66] Update Client debug level --- client/proxmark3.c | 3 ++- client/settings.c | 19 +++++++++---------- client/ui.h | 3 ++- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/client/proxmark3.c b/client/proxmark3.c index 2c20afa17..be7c1eafe 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -587,7 +587,8 @@ int main(int argc, char *argv[]) { settings_load (); // quick patch for debug level - g_debugMode = session.logging_level; + g_debugMode = session.client_debug_level; + PrintAndLogEx(ERR,"Emojo test [%d] :smile:",session.emoji_mode); // settings_save (); // End Settings diff --git a/client/settings.c b/client/settings.c index 64aec90ba..f550604a1 100644 --- a/client/settings.c +++ b/client/settings.c @@ -62,7 +62,7 @@ int settings_load (void) { // Set all defaults // mySettings.os_windows_usecolor = false; // mySettings.os_windows_useansicolor = false; - session.logging_level = 0; + session.client_debug_level = OFF; session.window_plot_xpos = 10; session.window_plot_ypos = 30; session.window_plot_hsize = 400; @@ -125,10 +125,10 @@ void settings_save_callback (json_t *root) { // JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); // Log level, convert to text // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); - switch (session.logging_level) { - case 0: JsonSaveStr (root,"logging.level","off"); break; - case 1: JsonSaveStr (root,"logging.level","on"); break; - case 2: JsonSaveStr (root,"logging.level","full"); break; + switch (session.client_debug_level) { + case OFF: JsonSaveStr (root,"client.debug.level","off"); break; + case SIMPLE: JsonSaveStr (root,"client.debug.level","on"); break; + case FULL: JsonSaveStr (root,"client.debug.level","full"); break; default: JsonSaveStr (root,"logging.level","NORMAL"); } @@ -172,11 +172,10 @@ void settings_load_callback (json_t *root) { mySettings.os_windows_useansicolor = b1; */ // Logging Level -// typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; - if (json_unpack_ex(root,&up_error, 0, "{s:s}","logging.level",&s1) == 0) { - if (strncmp (s1,"off",3) == 0) session.logging_level = 0; - if (strncmp (s1,"on",2) == 0) session.logging_level = 1; - if (strncmp (s1,"full",4) == 0) session.logging_level = 2; + if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { + if (strncmp (s1,"off",3) == 0) session.client_debug_level = OFF; + if (strncmp (s1,"simple",6) == 0) session.client_debug_level = SIMPLE; + if (strncmp (s1,"full",4) == 0) session.client_debug_level = FULL; } // window plot diff --git a/client/ui.h b/client/ui.h index aea04b6ce..343b55c1f 100644 --- a/client/ui.h +++ b/client/ui.h @@ -19,6 +19,7 @@ typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; +typedef enum clientdebugLevel {OFF,SIMPLE,FULL} clientdebugLevel_t; typedef struct { bool settings_loaded; @@ -33,7 +34,7 @@ typedef struct { int window_plot_ypos; int window_plot_hsize; int window_plot_wsize; - logLevel_t logging_level; + clientdebugLevel_t client_debug_level; } session_arg_t; extern session_arg_t session; From 732c012be776df237ac97faaeaa3c2767478b023 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:27:28 +0200 Subject: [PATCH 34/66] adjustments --- armsrc/iso14443a.c | 4 +++- armsrc/iso14443b.c | 10 +++++++--- armsrc/mifaredesfire.c | 3 +++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 23b3a2239..f789d87c6 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2672,8 +2672,10 @@ void ReaderIso14443a(PacketCommandNG *c) { uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; uint8_t par[MAX_PARITY_SIZE] = {0x00}; - if ((param & ISO14A_CONNECT)) + if ((param & ISO14A_CONNECT)) { + iso14_pcb_blocknum = 0; clear_trace(); + } set_tracing(true); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 31f2cae58..10beb4489 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -29,7 +29,7 @@ # define FWT_TIMEOUT_14B 35312 #endif #ifndef ISO14443B_DMA_BUFFER_SIZE -# define ISO14443B_DMA_BUFFER_SIZE 256 +# define ISO14443B_DMA_BUFFER_SIZE 512 //changed this from 256 #endif #ifndef RECEIVE_MASK # define RECEIVE_MASK (ISO14443B_DMA_BUFFER_SIZE-1) @@ -37,7 +37,7 @@ // Guard Time (per 14443-2) #ifndef TR0 -# define TR0 0 +# define TR0 32 //this value equals 8 ETU = 32 ssp clk (w/ 424 khz) #endif // Synchronization time (per 14443-2) @@ -261,6 +261,10 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // 80/fs < TR1 < 200/fs // 10 ETU < TR1 < 24 ETU + // Send TR1. + // 10-11 ETU * 4times samples ONES + for (int i = 0; i < 10; i++) { SEND4STUFFBIT(1); } + // Send SOF. // 10-11 ETU * 4times samples ZEROS for (int i = 0; i < 10; i++) { SEND4STUFFBIT(0); } @@ -307,7 +311,7 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { //for(i = 0; i < 10; i++) { ToSendStuffBit(0); } // why this? - for (int i = 0; i < 40; i++) { SEND4STUFFBIT(1); } + for (int i = 0; i < 2; i++) { SEND4STUFFBIT(1); } //for(i = 0; i < 40; i++) { ToSendStuffBit(1); } // Convert from last byte pos to length diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index ba2b20d2d..aa70e5ccb 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -117,6 +117,9 @@ void MifareDesfireGetInformation() { clear_trace(); set_tracing(true); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + // reset the pcb_blocknum, + pcb_blocknum = 0; // card select - information if (!iso14443a_select_card(NULL, &card, NULL, true, 0, false)) { From 0e2ac41717419519a84eeaf3e8f3fcbff02d5721 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:28:15 +0200 Subject: [PATCH 35/66] annotage desfire more --- client/cmdhflist.c | 4 +++- include/protocols.h | 52 +++++++++++++++++++++------------------------ 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/client/cmdhflist.c b/client/cmdhflist.c index 52894c52b..7aeac0bc7 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -709,7 +709,6 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { pos++; for (uint8_t i = 0; i < 2; i++, pos++) { - switch (cmd[pos]) { case MFDES_CREATE_APPLICATION: snprintf(exp, size, "CREATE APPLICATION"); @@ -822,6 +821,9 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { case MFDES_ADDITIONAL_FRAME: snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); break; + case MFDES_READSIG: + snprintf(exp, size, "READ SIGNATURE"); + break; default: break; } diff --git a/include/protocols.h b/include/protocols.h index 357fa9e4d..b927058b0 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -349,16 +349,12 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // 6x xx = ERROR // MIFARE DESFire command set: - -#define MFDES_GET_VERSION 0x60 #define MFDES_AUTHENTICATE 0x0A // AUTHENTICATE_NATIVE #define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD #define MFDES_AUTHENTICATE_AES 0xAA -#define MFDES_CREATE_APPLICATION 0xCA -#define MFDES_DELETE_APPLICATION 0xDA + #define MFDES_CREDIT 0x0C #define MFDES_LIMITED_CREDIT 0x1C -#define MFDES_DEBIT 0xDC #define MFDES_WRITE_RECORD 0x3B #define MFDES_READSIG 0x3C #define MFDES_WRITE_DATA 0x3D @@ -366,6 +362,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_CHANGE_KEY_SETTINGS 0x54 #define MFDES_SELECT_APPLICATION 0x5A #define MFDES_CHANGE_FILE_SETTINGS 0x5F +#define MFDES_GET_VERSION 0x60 #define MFDES_GET_ISOFILE_IDS 0x61 #define MFDES_GET_KEY_VERSION 0x64 #define MFDES_GET_APPLICATION_IDS 0x6A @@ -373,15 +370,32 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_GET_FREE_MEMORY 0x6E #define MFDES_GET_DF_NAMES 0x6D #define MFDES_GET_FILE_IDS 0x6F +#define MFDES_ABORT_TRANSACTION 0xA7 +#define MFDES_ADDITIONAL_FRAME 0xAF #define MFDES_READ_RECORDS 0xBB #define MFDES_READ_DATA 0xBD -#define MFDES_ABORT_TRANSACTION 0xA7 +#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 +#define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 +#define MFDES_CHANGE_KEY 0xC4 +#define MFDES_COMMIT_TRANSACTION 0xC7 +#define MFDES_CREATE_APPLICATION 0xCA +#define MFDES_CREATE_BACKUP_DATA_FILE 0xCB +#define MFDES_CREATE_VALUE_FILE 0xCC +#define MFDES_CREATE_STD_DATA_FILE 0xCD +#define MFDES_DELETE_APPLICATION 0xDA +#define MFDES_DEBIT 0xDC +#define MFDES_DELETE_FILE 0xDF +#define MFDES_CLEAR_RECORD_FILE 0xEB +#define MFDES_GET_FILE_SETTINGS 0xF5 +#define MFDES_FORMAT_PICC 0xFC -// MIFARE DESFire status set: -#define MFDES_OPERATION_OK 0x00 -#define MFDES_NO_CHANGES 0x0C -#define MFDES_ADDITIONAL_FRAME 0xAF +// MIFARE DESFire status & error codes: +#define MFDES_S_OPERATION_OK 0x00 +#define MFDES_S_NO_CHANGES 0x0C +#define MFDES_S_SIGNATURE 0x90 +#define MFDES_S_ADDITIONAL_FRAME 0xAF + #define MFDES_E_OUT_OF_EEPROM 0x0E #define MFDES_E_ILLEGAL_COMMAND_CODE 0x1C #define MFDES_E_INTEGRITY_ERROR 0x1E @@ -401,26 +415,8 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_E_EEPROM 0xEE #define MFDES_E_FILE_NOT_FOUND 0xF0 #define MFDES_E_FILE_INTEGRITY 0xF1 -#define MFDES_SIGNATURE 0x90 -#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 -#define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 -#define MFDES_CHANGE_KEY 0xC4 -#define MFDES_COMMIT_TRANSACTION 0xC7 -#define MFDES_CREATE_APPLICATION 0xCA -#define MFDES_CREATE_BACKUP_DATA_FILE 0xCB -#define MFDES_CREATE_VALUE_FILE 0xCC -#define MFDES_CREATE_STD_DATA_FILE 0xCD - -#define MFDES_CLEAR_RECORD_FILE 0xEB - -#define MFDES_DELETE_APPLICATION 0xDA -#define MFDES_DELETE_FILE 0xDF - -#define MFDES_GET_FILE_SETTINGS 0xF5 -#define MFDES_FORMAT_PICC 0xFC - // LEGIC Commands #define LEGIC_MIM_22 0x0D #define LEGIC_MIM_256 0x1D From df0aaa020d25c329d79fb359da601e0ede0666b6 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:28:52 +0200 Subject: [PATCH 36/66] fix: string too short --- client/util.c | 1 - 1 file changed, 1 deletion(-) diff --git a/client/util.c b/client/util.c index 36362f83b..654a87cc3 100644 --- a/client/util.c +++ b/client/util.c @@ -212,7 +212,6 @@ void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex sprintf(tmp, " "); // remove last space - --tmp; *tmp = '\0'; return; } From 69732ef709471a91cb08092bd094e81a5462ac04 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:30:37 +0200 Subject: [PATCH 37/66] better identification of PLus vs Plus EV1. Be verycareful of that WRITEPERSO cmd inside INFO to detect card type. No good at all --- client/cmdhfmfp.c | 133 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 110 insertions(+), 23 deletions(-) diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index 71da93bcc..e85f0861a 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -27,11 +27,19 @@ #include "protocols.h" #include "crypto/libpcrypto.h" - static const uint8_t DefaultKey[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; - uint16_t CardAddresses[] = {0x9000, 0x9001, 0x9002, 0x9003, 0x9004, 0xA000, 0xA001, 0xA080, 0xA081, 0xC000, 0xC001}; +typedef enum { + MFP_UNKNOWN = 0, + DESFIRE_MF3ICD40, + DESFIRE_EV1, + DESFIRE_EV2, + DESFIRE_EV3, + DESFIRE_LIGHT, + PLUS_EV1, +} nxp_cardtype_t; + static int CmdHelp(const char *Cmd); /* @@ -56,15 +64,21 @@ static char *getCardSizeStr(uint8_t fsize) { return buf; } -static char *getProtocolStr(uint8_t id) { +static char *getProtocolStr(uint8_t id, bool hw) { - static char buf[40] = {0x00}; + static char buf[50] = {0x00}; char *retStr = buf; - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else + if (id == 0x04) { + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3 MIFARE, 14443-4") ")", id); + } else if (id == 0x05) { + if (hw) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-2, 14443-3") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + } else { sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + } return buf; } @@ -91,6 +105,59 @@ static char *getVersionStr(uint8_t major, uint8_t minor) { return buf; } +static char *getTypeStr(uint8_t type) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + switch (type) { + case 1: + sprintf(retStr, "0x%02X ( " _YELLOW_("DESFire") ")", type); + break; + case 2: + sprintf(retStr, "0x%02X ( " _YELLOW_("Plus") ")", type); + break; + case 3: + sprintf(retStr, "0x%02X ( " _YELLOW_("Ultralight") ")", type); + break; + case 4: + sprintf(retStr, "0x%02X ( " _YELLOW_("NTAG") ")", type); + break; + default: + break; + } + return buf; +} + +static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { + + // DESFire MF3ICD40 + if (major == 0x00 && minor == 0x00 ) + return DESFIRE_MF3ICD40; + + // DESFire EV1 + if (major == 0x01 && minor == 0x00 ) + return DESFIRE_EV1; + + // DESFire EV2 + if (major == 0x12 && minor == 0x00 ) + return DESFIRE_EV2; + + // DESFire EV3 +// if (major == 0x13 && minor == 0x00 ) +// return DESFIRE_EV3; + + // DESFire Light + if (major == 0x30 && minor == 0x00 ) + return DESFIRE_LIGHT; + + // Plus EV1 + if (major == 0x11 && minor == 0x00 ) + return PLUS_EV1; + + return MFP_UNKNOWN; +} + // --- GET SIGNATURE static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature, int signature_len) { @@ -115,13 +182,15 @@ static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature if (is_valid) break; } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + if (is_valid == false) { PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); return PM3_ESOFT; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_plus_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_plus_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 16); @@ -162,19 +231,19 @@ static int plus_print_version(uint8_t *version) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); + PrintAndLogEx(INFO, " Type: %s", getTypeStr(version[1])); PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); PrintAndLogEx(INFO, " Version: %s", getVersionStr(version[3], version[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6], true)); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); - PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[3], version[4]); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[7])); + PrintAndLogEx(INFO, " Type: %s", getTypeStr(version[8])); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[9]); + PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[10], version[11]); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[12])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[13], false)); return PM3_SUCCESS; } static int get_plus_version(uint8_t *version, int *version_len) { @@ -235,17 +304,28 @@ static int CmdHFMFPInfo(const char *Cmd) { if (select_status == 1 || select_status == 2) { PrintAndLogEx(INFO, "--- " _CYAN_("Fingerprint")); - - if (supportVersion && supportSignature) { - PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); - } else { - PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); + + bool isPlus = false; + + if (supportVersion) { + + int cardtype = getCardType(version[3], version[4]); + + if (cardtype == 6) { + if (supportSignature) { + PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); + } else { + PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); + } + isPlus = true; + } else { + + } } // MIFARE Type Identification Procedure // https://www.nxp.com/docs/en/application-note/AN10833.pdf uint16_t ATQA = card.atqa[0] + (card.atqa[1] << 8); - bool isPlus = false; if (ATQA & 0x0004) { PrintAndLogEx(INFO, " SIZE: " _GREEN_("2K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); @@ -289,6 +369,10 @@ static int CmdHFMFPInfo(const char *Cmd) { uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; int res = ExchangeRAW14a(cmd, sizeof(cmd), true, false, data, sizeof(data), &datalen, false); + // DESFire answers 0x1C + // Plus answers 0x0B, 0x09 + PrintAndLogEx(INFO, "ICEE: %s", sprint_hex(data, datalen)); + if (memcmp(data, "\x67\x00", 2) == 0) { PrintAndLogEx(INFO, "\tMost likely a MIFARE DESFire tag"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfdes info`")); @@ -1105,10 +1189,13 @@ static int CmdHFMFPChk(const char *Cmd) { if (keyListLen == 0) { PrintAndLogEx(ERR, "Key list is empty. Nothing to check."); return PM3_EINVARG; + } else { + PrintAndLogEx(INFO, "Loaded " _YELLOW_("%zu") "keys", keyListLen); } if (!verbose) printf("Search keys:"); + while (true) { res = MFPKeyCheck(startSector, endSector, startKeyAB, endKeyAB, keyList, keyListLen, foundKeys, verbose); if (res == PM3_EOPABORTED) From 8e74978855d86414aaf5a2f322d9da9ec35a545a Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:31:18 +0200 Subject: [PATCH 38/66] code fixes, better handling of card identification and outputs accordingly. --- client/cmdhfmfdes.c | 643 ++++++++++++++++++++++++-------------------- client/cmdhfmfdes.h | 11 +- 2 files changed, 360 insertions(+), 294 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 3e21d60be..8ab1f4e95 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -38,12 +38,13 @@ uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x typedef enum { UNKNOWN = 0, - MF3ICD40, - EV1, - EV2, - EV3, - LIGHT, -} desfire_cardtype_t; + DESFIRE_MF3ICD40, + DESFIRE_EV1, + DESFIRE_EV2, + DESFIRE_EV3, + DESFIRE_LIGHT, + PLUS_EV1, +} nxp_cardtype_t; typedef struct { uint8_t aid[3]; @@ -54,14 +55,65 @@ typedef struct { static int CmdHelp(const char *Cmd); /* - uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; - int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); - - if (!res && datalen > 1 && data[0] == 0x09) { - SLmode = 0; - } - + The 7 MSBits (= n) code the storage size itself based on 2^n, + the LSBit is set to '0' if the size is exactly 2^n + and set to '1' if the storage size is between 2^n and 2^(n+1). + For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. */ +static char *getCardSizeStr(uint8_t fsize) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + uint16_t usize = 1 << ((fsize >> 1) + 1); + uint16_t lsize = 1 << (fsize >> 1); + + // is LSB set? + if (fsize & 1) + sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); + return buf; +} + +static char *getProtocolStr(uint8_t id, bool hw) { + + static char buf[50] = {0x00}; + char *retStr = buf; + + if (id == 0x04) { + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3 MIFARE, 14443-4") ")", id); + } else if (id == 0x05) { + if (hw) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-2, 14443-3") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + } else { + sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + } + return buf; +} + +static char *getVersionStr(uint8_t major, uint8_t minor) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (major == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); + else if (major == 0x01 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); + else if (major == 0x12 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); +// else if (major == 0x13 && minor == 0x00) +// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); + else if (major == 0x30 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); + else + sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); + return buf; +} + int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { @@ -107,7 +159,7 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t if (sw) *sw = isw; - if (isw != 0x9000 && isw != status(MFDES_OPERATION_OK) && isw != status(MFDES_SIGNATURE) && isw != status(MFDES_ADDITIONAL_FRAME) && isw != status(MFDES_NO_CHANGES)) { + if (isw != 0x9000 && isw != status(MFDES_S_OPERATION_OK) && isw != status(MFDES_S_SIGNATURE) && isw != status(MFDES_S_ADDITIONAL_FRAME) && isw != status(MFDES_S_NO_CHANGES)) { if (GetAPDULogging()) { if (isw >> 8 == 0x61) { PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); @@ -240,15 +292,23 @@ static char *GetErrorString(int res, uint16_t *sw) { return ""; } - static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize, bool readalldata) { - if (g_debugMode > 1) { - if (apdu == NULL) PrintAndLogEx(ERR, "APDU=NULL"); - if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (sw == NULL) PrintAndLogEx(ERR, "SW=NULL"); - if (recv_len == NULL) PrintAndLogEx(ERR, "RECV_LEN=NULL"); + if (apdu == NULL) { + PrintAndLogEx(DEBUG, "APDU=NULL"); + return PM3_EINVARG; + } + if (dest == NULL) { + PrintAndLogEx(DEBUG, "DEST=NULL"); + return PM3_EINVARG; + } + if (sw == NULL) { + PrintAndLogEx(DEBUG, "SW=NULL"); + return PM3_EINVARG; + } + if (recv_len == NULL) { + PrintAndLogEx(DEBUG, "RECV_LEN=NULL"); + return PM3_EINVARG; } - if (apdu == NULL || sw == NULL || recv_len == NULL) return PM3_EINVARG; *sw = 0; uint8_t data[255 * 5] = {0x00}; @@ -257,7 +317,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { - if (g_debugMode > 1) GetErrorString(res, sw); + PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); return res; } if (dest != NULL) { @@ -276,6 +336,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } return res; } + while (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF apdu->Lc = 0; @@ -284,9 +345,10 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { - if (g_debugMode > 1) GetErrorString(res, sw); + PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); return res; } + if (dest != NULL) { if (splitbysize) { memcpy(&dest[i * splitbysize], data, resplen); @@ -296,33 +358,33 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } } pos += resplen; + if (*sw != status(MFDES_ADDITIONAL_FRAME)) break; } - if (splitbysize) *recv_len = i; - else { - *recv_len = pos; - } - return PM3_SUCCESS; + *recv_len = (splitbysize) ? i : pos; + return PM3_SUCCESS; } -static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { +static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { if (major == 0x00) - return MF3ICD40; - else if (major == 0x01 && minor == 0x00) - return EV1; - else if (major == 0x12 && minor == 0x00) - return EV2; -// else if (major == 0x13 && minor == 0x00) -// return EV3; - else if (major == 0x30 && minor == 0x00) - return LIGHT; - else - return UNKNOWN; + return DESFIRE_MF3ICD40; + if (major == 0x01 && minor == 0x00) + return DESFIRE_EV1; + if (major == 0x12 && minor == 0x00) + return DESFIRE_EV2; +// if (major == 0x13 && minor == 0x00) +// return DESFIRE_EV3; + if (major == 0x30 && minor == 0x00) + return DESFIRE_LIGHT; + if (major == 0x11 && minor == 0x00 ) + return PLUS_EV1; + + return UNKNOWN; } -//none, verified +// -- test if card supports 0x0A static int test_desfire_authenticate() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 @@ -331,7 +393,7 @@ static int test_desfire_authenticate() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -// none, verified +// -- test if card supports 0x1A static int test_desfire_authenticate_iso() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 @@ -340,7 +402,7 @@ static int test_desfire_authenticate_iso() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -//none, verified +// -- test if card supports 0xAA static int test_desfire_authenticate_aes() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 @@ -349,37 +411,44 @@ static int test_desfire_authenticate_aes() { return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -// --- FREE MEM, verified +// --- GET FREE MEM static int desfire_print_freemem(uint32_t free_mem) { PrintAndLogEx(SUCCESS, " Available free memory on card : " _GREEN_("%d bytes"), free_mem); return PM3_SUCCESS; } -// init / disconnect, verified static int get_desfire_freemem(uint32_t *free_mem) { if (free_mem == NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E + *free_mem = 0; int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); - if (res == PM3_SUCCESS) { - *free_mem = le24toh(fmem); + + if (res != PM3_SUCCESS ) return res; - } - *free_mem = 0; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + + *free_mem = le24toh(fmem); return res; } +// --- GET SIGNATURE +static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, nxp_cardtype_t card_type) { -// --- GET SIGNATURE, verified -static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { - if (g_debugMode > 1) { - if (uid == NULL) PrintAndLogEx(ERR, "UID=NULL"); - if (signature == NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); + if (uid == NULL) { + PrintAndLogEx(DEBUG, "UID=NULL"); + return PM3_EINVARG; + } + if (signature == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE=NULL"); + return PM3_EINVARG; } - if (uid == NULL || signature == NULL) return PM3_EINVARG; // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -389,7 +458,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, - {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, + {"DESFire Light", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; @@ -413,8 +482,8 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign return PM3_ESOFT; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); +// PrintAndLogEx(NORMAL, ""); +// PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); @@ -429,35 +498,34 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign return PM3_SUCCESS; } -// init / disconnect, verified static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - if (g_debugMode > 1) { - if (signature == NULL) PrintAndLogEx(ERR, "SIGNATURE=NULL"); - if (signature_len == NULL) PrintAndLogEx(ERR, "SIGNATURE_LEN=NULL"); + + if (signature == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE=NULL"); + return PM3_EINVARG; } - if (signature == NULL || signature_len == NULL) return PM3_EINVARG; - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C + if (signature_len == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE_LEN=NULL"); + return PM3_EINVARG; + } + + uint8_t c[] = {0x00}; + sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, sizeof(c), c}; // 0x3C int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { if (recv_len != 56) { *signature_len = 0; - DropField(); - return PM3_ESOFT; + res = PM3_ESOFT; } else { *signature_len = recv_len; - } - DropField(); - return PM3_SUCCESS; } DropField(); return res; } - // --- KEY SETTING static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { @@ -490,23 +558,29 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { return PM3_SUCCESS; } -// none, verified static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { - if (g_debugMode > 1) { - if (key_settings == NULL) PrintAndLogEx(ERR, "KEY_SETTINGS=NULL"); - if (num_keys == NULL) PrintAndLogEx(ERR, "NUM_KEYS=NULL"); + if (key_settings == NULL) { + PrintAndLogEx(DEBUG, "KEY_SETTINGS=NULL"); + return PM3_EINVARG; + } + if (num_keys == NULL) { + PrintAndLogEx(DEBUG, "NUM_KEYS=NULL"); + return PM3_EINVARG; } - if (key_settings == NULL || num_keys == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0, true); - if (res != PM3_SUCCESS) return res; + + if (res != PM3_SUCCESS ) + return res; + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; *key_settings = data[0]; *num_keys = data[1]; - return PM3_SUCCESS; + return res; } // --- KEY VERSION @@ -515,37 +589,52 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { return PM3_SUCCESS; } -// none, verified static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { - if (g_debugMode > 1) { - if (num_versions == NULL) PrintAndLogEx(ERR, "NUM_VERSIONS=NULL"); + if (num_versions == NULL) { + PrintAndLogEx(DEBUG, "NUM_VERSIONS=NULL"); + return PM3_EINVARG; } - if (num_versions == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS ) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + return res; } - -// init / disconnect, verified +// --- GET APPIDS static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { - if (g_debugMode > 1) { - if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); - if (app_ids_len == NULL) PrintAndLogEx(ERR, "APP_IDS_LEN=NULL"); + if (dest == NULL) { + PrintAndLogEx(DEBUG, "DEST=NULL"); + return PM3_EINVARG; } - if (dest == NULL || app_ids_len == NULL) return PM3_EINVARG; + if (app_ids_len == NULL) { + PrintAndLogEx(DEBUG, "APP_IDS_LEN=NULL"); + return PM3_EINVARG; + } + sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); - if (res != PM3_SUCCESS) return res; + + if (res != PM3_SUCCESS ) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + *app_ids_len = (uint8_t)recv_len & 0xFF; return res; } -// init, verified +// --- GET DF NAMES static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); @@ -556,13 +645,14 @@ static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t), true); - if (res != PM3_SUCCESS) return res; + if (res != PM3_SUCCESS) + return res; + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; *dfname_count = recv_len; return res; } - -// init, verified static int get_desfire_select_application(uint8_t *aid) { if (g_debugMode > 1) { if (aid == NULL) PrintAndLogEx(ERR, "AID=NULL"); @@ -632,7 +722,7 @@ static int get_desfire_createapp(aidhdr_t *aidhdr) { sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t *)aidhdr}; // 0xCA uint16_t sw = 0; int recvlen = 0; - int res = send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0, true); + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"), GetErrorString(res, &sw)); DropField(); @@ -646,7 +736,7 @@ static int get_desfire_deleteapp(uint8_t *aid) { sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA uint16_t sw = 0; int recvlen = 0; - int res = send_desfire_cmd(&apdu, false, NONE, &recvlen, &sw, 0, true); + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"), GetErrorString(res, &sw)); DropField(); @@ -655,6 +745,116 @@ static int get_desfire_deleteapp(uint8_t *aid) { return res; } +int getKeySettings(uint8_t *aid) { + if (aid == NULL) return PM3_EINVARG; + + int res = 0; + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + + // CARD MASTER KEY + //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + + // KEY Settings - AMK + uint8_t num_keys = 0; + uint8_t key_setting = 0; + res = get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { + // number of Master keys (0x01) + PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); + + PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_setting & (1 << 3)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x04] CMK required for create/delete : %s", (key_setting & (1 << 2)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x02] Directory list access with CMK : %s", (key_setting & (1 << 1)) ? _GREEN_("YES") : "NO"); + PrintAndLogEx(SUCCESS, " [0x01] CMK is changeable : %s", (key_setting & (1 << 0)) ? _GREEN_("YES") : "NO"); + } else { + PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); + } + + const char *str = " Operation of PICC master key : " _YELLOW_("%s"); + + // 2 MSB denotes + switch (num_keys >> 6) { + case 0: + PrintAndLogEx(SUCCESS, str, "(3)DES"); + break; + case 1: + PrintAndLogEx(SUCCESS, str, "3K3DES"); + break; + case 2: + PrintAndLogEx(SUCCESS, str, "AES"); + break; + default: + break; + } + + uint8_t cmk_num_versions = 0; + if (get_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, " PICC Master key Version : " _YELLOW_("%d (0x%02x)"), cmk_num_versions, cmk_num_versions); + PrintAndLogEx(INFO, " ----------------------------------------------------------"); + } + + // Authentication tests + int res = test_desfire_authenticate(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + res = test_desfire_authenticate_iso(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + res = test_desfire_authenticate_aes(); + if (res == PM3_ETIMEOUT) return res; + PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); + + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + + } else { + + // AID - APPLICATION MASTER KEYS + //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + + // KEY Settings - AMK + uint8_t num_keys = 0; + uint8_t key_setting = 0; + res = get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { + desfire_print_keysetting(key_setting, num_keys); + } else { + PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); + } + + // KEY VERSION - AMK + uint8_t num_version = 0; + if (get_desfire_keyversion(0, &num_version) == PM3_SUCCESS) { + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(INFO, " Application keys"); + desfire_print_keyversion(0, num_version); + } else { + PrintAndLogEx(WARNING, " Can't read AID master key version. Trying all keys"); + } + + // From 0x01 to numOfKeys. We already got 0x00. (AMK) + num_keys &= 0x3F; + if (num_keys > 1) { + for (uint8_t i = 0x01; i < num_keys; ++i) { + if (get_desfire_keyversion(i, &num_version) == PM3_SUCCESS) { + desfire_print_keyversion(i, num_version); + } else { + PrintAndLogEx(WARNING, " Can't read key %d (0x%02x) version", i, i); + } + } + } + } + + DropField(); + return PM3_SUCCESS; +} + + static int CmdHF14ADesCreateApp(const char *Cmd) { clearCommandBuffer(); @@ -852,7 +1052,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { uint8_t isOK = resp.oldarg[0] & 0xff; if (isOK) { uint8_t rdata[] = {0xFC}; // 0xFC - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NULL, sizeof(rdata), 0, rdata, sizeof(rdata)); if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { PrintAndLogEx(WARNING, "Client reset command execute timeout"); DropField(); @@ -893,13 +1093,12 @@ static int CmdHF14ADesInfo(const char *Cmd) { struct p *package = (struct p *) resp.data.asBytes; if (resp.status != PM3_SUCCESS) { - switch (package->isOK) { case 1: PrintAndLogEx(WARNING, "Can't select card"); break; case 2: - PrintAndLogEx(WARNING, "Card is most likely not Desfire. Its UID has wrong size"); + PrintAndLogEx(WARNING, "Card is most likely not DESFire. Wrong size UID"); break; case 3: default: @@ -908,6 +1107,12 @@ static int CmdHF14ADesInfo(const char *Cmd) { } return PM3_ESOFT; } + + nxp_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); + if (cardtype == PLUS_EV1) { + PrintAndLogEx(INFO, "Card seems to be MIFARE Plus EV1. Try " _YELLOW_("`hf mfp info`")); + return PM3_SUCCESS; + } PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); @@ -922,7 +1127,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionHW[2]); PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6], true)); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); @@ -930,7 +1135,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionSW[2]); PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6], false)); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Card capabilities")); @@ -954,32 +1159,36 @@ static int CmdHF14ADesInfo(const char *Cmd) { if (major == 0 && minor == 2) PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); - // Signature originality check - uint8_t signature[56] = {0}; - size_t signature_len = 0; - desfire_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); + if (cardtype == DESFIRE_EV2 || cardtype == DESFIRE_LIGHT || cardtype == DESFIRE_EV3) { + // Signature originality check + uint8_t signature[56] = {0}; + size_t signature_len = 0; - if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) - desfire_print_signature(package->uid, signature, signature_len, cardtype); - else { - PrintAndLogEx(WARNING, "--- " _YELLOW_("Couldn't verify signature. Unknown public key ?")); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) { + desfire_print_signature(package->uid, signature, signature_len, cardtype); + } else { + PrintAndLogEx(WARNING, "--- Card doesn't support GetSignature cmd"); + } } // Master Key settings uint8_t master_aid[3] = {0x00, 0x00, 0x00}; getKeySettings(master_aid); - // Free memory on card - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); - uint32_t free_mem = 0; - if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { - desfire_print_freemem(free_mem); - } else { - PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); + if (cardtype != DESFIRE_LIGHT) { + // Free memory on card + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); + uint32_t free_mem = 0; + if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { + desfire_print_freemem(free_mem); + } else { + PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); + } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); } - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - /* Card Master key (CMK) 0x00 AID = 00 00 00 (card level) Application Master Key (AMK) 0x00 AID != 00 00 00 @@ -999,167 +1208,6 @@ static int CmdHF14ADesInfo(const char *Cmd) { return PM3_SUCCESS; } -/* - The 7 MSBits (= n) code the storage size itself based on 2^n, - the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). - For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. -*/ -char *getCardSizeStr(uint8_t fsize) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - uint16_t usize = 1 << ((fsize >> 1) + 1); - uint16_t lsize = 1 << (fsize >> 1); - - // is LSB set? - if (fsize & 1) - sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); - return buf; -} - -char *getProtocolStr(uint8_t id) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); - return buf; -} - -char *getVersionStr(uint8_t major, uint8_t minor) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (major == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); - else if (major == 0x01 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); - else if (major == 0x12 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); -// else if (major == 0x13 && minor == 0x00) -// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); - else if (major == 0x30 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); - else - sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); - return buf; -} - -int getKeySettings(uint8_t *aid) { - if (aid == NULL) return PM3_EINVARG; - int res = 0; - if (memcmp(aid, "\x00\x00\x00", 3) == 0) { - - // CARD MASTER KEY - //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - res = get_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; - - // KEY Settings - AMK - uint8_t num_keys = 0; - uint8_t key_setting = 0; - res = get_desfire_keysettings(&key_setting, &num_keys); - if (res == PM3_SUCCESS) { - // number of Master keys (0x01) - PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); - - PrintAndLogEx(SUCCESS, " [0x08] Configuration changeable : %s", (key_setting & (1 << 3)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x04] CMK required for create/delete : %s", (key_setting & (1 << 2)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x02] Directory list access with CMK : %s", (key_setting & (1 << 1)) ? _GREEN_("YES") : "NO"); - PrintAndLogEx(SUCCESS, " [0x01] CMK is changeable : %s", (key_setting & (1 << 0)) ? _GREEN_("YES") : "NO"); - } else { - PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); - } - - const char *str = " Operation of PICC master key : " _YELLOW_("%s"); - - // 2 MSB denotes - switch (num_keys >> 6) { - case 0: - PrintAndLogEx(SUCCESS, str, "(3)DES"); - break; - case 1: - PrintAndLogEx(SUCCESS, str, "3K3DES"); - break; - case 2: - PrintAndLogEx(SUCCESS, str, "AES"); - break; - default: - break; - } - - uint8_t cmk_num_versions = 0; - if (get_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, " PICC Master key Version : " _YELLOW_("%d (0x%02x)"), cmk_num_versions, cmk_num_versions); - PrintAndLogEx(INFO, " ----------------------------------------------------------"); - } - - // Authentication tests - int res = test_desfire_authenticate(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - res = test_desfire_authenticate_iso(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - res = test_desfire_authenticate_aes(); - if (res == PM3_ETIMEOUT) return res; - PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); - - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - - } else { - - // AID - APPLICATION MASTER KEYS - //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - res = get_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; - - // KEY Settings - AMK - uint8_t num_keys = 0; - uint8_t key_setting = 0; - res = get_desfire_keysettings(&key_setting, &num_keys); - if (res == PM3_SUCCESS) { - desfire_print_keysetting(key_setting, num_keys); - } else { - PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); - } - - // KEY VERSION - AMK - uint8_t num_version = 0; - if (get_desfire_keyversion(0, &num_version) == PM3_SUCCESS) { - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(INFO, " Application keys"); - desfire_print_keyversion(0, num_version); - } else { - PrintAndLogEx(WARNING, " Can't read AID master key version. Trying all keys"); - } - - // From 0x01 to numOfKeys. We already got 0x00. (AMK) - num_keys &= 0x3F; - if (num_keys > 1) { - for (uint8_t i = 0x01; i < num_keys; ++i) { - if (get_desfire_keyversion(i, &num_version) == PM3_SUCCESS) { - desfire_print_keyversion(i, num_version); - } else { - PrintAndLogEx(WARNING, " Can't read key %d (0x%02x) version", i, i); - } - } - } - } - - DropField(); - return PM3_SUCCESS; -} static void DecodeFileType(uint8_t filetype) { switch (filetype) { @@ -1202,8 +1250,10 @@ static void DecodeComSet(uint8_t comset) { } static char *DecodeAccessValue(uint8_t value) { - char *car = (char *)malloc(255); - memset(car, 0x0, 255); + char *car = (char *)calloc(255, sizeof(char)); + if (car == NULL) + return NULL; + switch (value) { case 0xE: strcat(car, "(Free Access)"); @@ -1224,9 +1274,17 @@ static void DecodeAccessRights(uint16_t accrights) { int write_access = (accrights >> 8) & 0xF; int read_access = (accrights >> 12) & 0xF; char *car = DecodeAccessValue(change_access_rights); + if (car == NULL) return; + char *rwa = DecodeAccessValue(read_write_access); + if (rwa == NULL) return; + char *wa = DecodeAccessValue(write_access); + if (wa == NULL) return; + char *ra = DecodeAccessValue(read_access); + if (ra == NULL) return; + PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights, car, rwa, wa, ra); free(car); free(rwa); @@ -1234,23 +1292,23 @@ static void DecodeAccessRights(uint16_t accrights) { free(ra); } -static int DecodeFileSettings(uint8_t *filesettings, int fileset_len, int maclen) { - uint8_t filetype = filesettings[0]; - uint8_t comset = filesettings[1]; +static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) { + uint8_t filetype = src[0]; + uint8_t comset = src[1]; - uint16_t accrights = (filesettings[4] << 8) + filesettings[3]; - if (fileset_len == 1 + 1 + 2 + 3 + maclen) { - int filesize = (filesettings[7] << 16) + (filesettings[6] << 8) + filesettings[5]; + uint16_t accrights = (src[4] << 8) + src[3]; + if (src_len == 1 + 1 + 2 + 3 + maclen) { + int filesize = (src[7] << 16) + (src[6] << 8) + src[5]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); PrintAndLogEx(INFO, " Filesize: %d", filesize); return PM3_SUCCESS; - } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) { - int lowerlimit = (filesettings[8] << 24) + (filesettings[7] << 16) + (filesettings[6] << 8) + filesettings[5]; - int upperlimit = (filesettings[12] << 24) + (filesettings[11] << 16) + (filesettings[10] << 8) + filesettings[9]; - int limitcredvalue = (filesettings[16] << 24) + (filesettings[15] << 16) + (filesettings[14] << 8) + filesettings[13]; - uint8_t limited_credit_enabled = filesettings[17]; + } else if (src_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) { + int lowerlimit = (src[8] << 24) + (src[7] << 16) + (src[6] << 8) + src[5]; + int upperlimit = (src[12] << 24) + (src[11] << 16) + (src[10] << 8) + src[9]; + int limitcredvalue = (src[16] << 24) + (src[15] << 16) + (src[14] << 8) + src[13]; + uint8_t limited_credit_enabled = src[17]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); @@ -1547,6 +1605,5 @@ static int CmdHelp(const char *Cmd) { int CmdHFMFDes(const char *Cmd) { // flush clearCommandBuffer(); - //g_debugMode=2; return CmdsParse(CommandTable, Cmd); } diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index c1ed4ed60..eb4dd77e0 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -14,10 +14,11 @@ int CmdHFMFDes(const char *Cmd); +/* char *getCardSizeStr(uint8_t fsize); -char *getProtocolStr(uint8_t id); char *getVersionStr(uint8_t major, uint8_t minor); int getKeySettings(uint8_t *aid); +*/ // Ev1 card limits #define MAX_NUM_KEYS 0x0F @@ -26,6 +27,14 @@ int getKeySettings(uint8_t *aid); #define MAX_FRAME_SIZE 60 #define FRAME_PAYLOAD_SIZE (MAX_FRAME_SIZE - 5) +// Ev2 card limits + +// Ev3 card limits + +// Light card limits + +// Light Ev1 card limits + #define NOT_YET_AUTHENTICATED 0xFF From 6bd5cda49c0432e1a5ea3f28f8df28f4b47856ec Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:44:15 +0200 Subject: [PATCH 39/66] setting a standalone mode when copying this file by default --- Makefile.platform.sample | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile.platform.sample b/Makefile.platform.sample index 9d0e2d965..8d587e3b7 100644 --- a/Makefile.platform.sample +++ b/Makefile.platform.sample @@ -5,3 +5,4 @@ PLATFORM=PM3RDV4 # If you want more than one PLATFORM_EXTRAS option, separate them by spaces: #PLATFORM_EXTRAS=BTADDON #STANDALONE=LF_SAMYRUN +STANDALONE=LF_ICEHID From bb0b368e68a47721ef1526184f4772591c65e73d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 10 Apr 2020 10:50:17 +0200 Subject: [PATCH 40/66] fix... --- client/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 8ab1f4e95..0afc03cde 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -1052,7 +1052,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { uint8_t isOK = resp.oldarg[0] & 0xff; if (isOK) { uint8_t rdata[] = {0xFC}; // 0xFC - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NULL, sizeof(rdata), 0, rdata, sizeof(rdata)); + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { PrintAndLogEx(WARNING, "Client reset command execute timeout"); DropField(); From 933d7523f74b9b1a14a656bbde92114e28cbf25e Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Fri, 10 Apr 2020 19:51:08 +1000 Subject: [PATCH 41/66] Tweaks and supports_colors --- client/proxmark3.c | 23 ++++++++++++- client/settings.c | 86 ++++++++++++++++++---------------------------- 2 files changed, 55 insertions(+), 54 deletions(-) diff --git a/client/proxmark3.c b/client/proxmark3.c index be7c1eafe..4d36c490b 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -29,6 +29,10 @@ #include "flash.h" #include "settings.h" +// Used to enable/disable use of settings json file +// #define USE_SETTING_FILE + + static void showBanner(void) { g_printAndLog = PRINTANDLOG_PRINT; @@ -489,12 +493,15 @@ finish2: return ret; } +#ifndef USE_SETTING_FILE + // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] // "VirtualTerminalLevel"=dword:00000001 // 2nd Key needs to be enabled... This key takes the console out of legacy mode. // [HKEY_CURRENT_USER\Console] // "ForceV2"=dword:00000001 + static bool DetectWindowsAnsiSupport(void) { bool ret = false; #if defined(_WIN32) @@ -543,6 +550,8 @@ static bool DetectWindowsAnsiSupport(void) { return ret; } +#endif + int main(int argc, char *argv[]) { srand(time(0)); @@ -582,15 +591,16 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); +#ifdef USE_SETTING_FILE // Load Settings and assign // This will allow the command line to override the settings.json values settings_load (); // quick patch for debug level g_debugMode = session.client_debug_level; - PrintAndLogEx(ERR,"Emojo test [%d] :smile:",session.emoji_mode); // settings_save (); // End Settings +#endif for (int i = 1; i < argc; i++) { @@ -770,8 +780,11 @@ int main(int argc, char *argv[]) { return 1; } +#ifndef USE_SETTING_FILE + // comment next 2 lines to use session values set from settings_load session.supports_colors = DetectWindowsAnsiSupport(); session.emoji_mode = ALTTEXT; +#endif session.stdinOnTTY = isatty(STDIN_FILENO); session.stdoutOnTTY = isatty(STDOUT_FILENO); @@ -841,6 +854,14 @@ int main(int argc, char *argv[]) { if (!script_cmds_file && !script_cmd && session.stdinOnTTY && session.stdoutOnTTY && !flash_mode) showBanner(); +#ifdef USE_SETTING_FILE + // Save settings if not load from settings json file. + // Doing this here will ensure other checks and updates are saved to over rule default + // e.g. Linux color use check + if (!session.settings_loaded) + settings_save (); +#endif + #ifdef HAVE_GUI # ifdef _WIN32 diff --git a/client/settings.c b/client/settings.c index f550604a1..cca0fda00 100644 --- a/client/settings.c +++ b/client/settings.c @@ -45,10 +45,9 @@ // Add the new setting to the session_arg_t; in ui.h // Add the default value for the setting in the settings_load page below // Update the settings_load_callback to load your setting into the stucture -// Update the settings_save_callback to enusre your setting gets saved (not used yet) -// Include "settingdata.h" (if needed) in the source file where you wish to use the setting -// use the setting as needed : mySettings. -// Should use if (mySettings.loaded) { use settings } +// Update the settings_save_callback to enusre your setting gets saved when needed. +// use the setting as needed : session. +// Can use (session.settings_loaded) to check if json settings file was used //----------------------------------------------------------------------------- #include "settings.h" @@ -60,20 +59,14 @@ int settings_load (void) { // Set all defaults -// mySettings.os_windows_usecolor = false; -// mySettings.os_windows_useansicolor = false; session.client_debug_level = OFF; session.window_plot_xpos = 10; session.window_plot_ypos = 30; session.window_plot_hsize = 400; session.window_plot_wsize = 800; -// mySettings.window_xpos = 10; -// mySettings.window_ypos = 210; -// mySettings.window_hsize = 300; -// mySettings.window_wsize = 500; -// mySettings.show_emoji = ALIAS; session.emoji_mode = ALIAS; session.show_hints = false; + session.supports_colors = false; // loadFileJson wants these, so pass in place holder values, though not used // in settings load; @@ -83,10 +76,10 @@ int settings_load (void) { if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { session.settings_loaded = true; } - else // Save default/create settings.json file - settings_save (); + // Note, if session.settings_loaded == false then the settings_save + // will be called in main () to save settings as set in defaults and main() checks. - return PM3_SUCCESS; + return PM3_SUCCESS; } // Save all settings from memory (struct) to file @@ -120,14 +113,13 @@ int settings_save (void) { } void settings_save_callback (json_t *root) { + JsonSaveStr (root,"FileType","settings"); -// JsonSaveBoolean (root,"os.windows.useColor",mySettings.os_windows_usecolor); -// JsonSaveBoolean (root,"os.windows.useAnsiColor",mySettings.os_windows_useansicolor); + // Log level, convert to text - // JsonSaveInt (root,"window.logging.level",mySettings.logging_level); switch (session.client_debug_level) { case OFF: JsonSaveStr (root,"client.debug.level","off"); break; - case SIMPLE: JsonSaveStr (root,"client.debug.level","on"); break; + case SIMPLE: JsonSaveStr (root,"client.debug.level","simple"); break; case FULL: JsonSaveStr (root,"client.debug.level","full"); break; default: JsonSaveStr (root,"logging.level","NORMAL"); @@ -138,10 +130,6 @@ void settings_save_callback (json_t *root) { JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); -// JsonSaveInt (root,"window.xpos",mySettings.window_xpos); -// JsonSaveInt (root,"window.ypos",mySettings.window_ypos); -// JsonSaveInt (root,"window.hsize",mySettings.window_hsize); -// JsonSaveInt (root,"window.wsize",mySettings.window_wsize); // Emoji switch (session.emoji_mode) { @@ -152,7 +140,10 @@ void settings_save_callback (json_t *root) { default: JsonSaveStr (root,"show.emoji","ALIAS"); } + JsonSaveBoolean (root,"show.hints",session.show_hints); + + JsonSaveBoolean (root,"os.supports.colors",session.supports_colors); } void settings_load_callback (json_t *root) { @@ -160,22 +151,16 @@ void settings_load_callback (json_t *root) { bool b1; int i1; const char *s1; - - // Left for example of a string json read -// if (json_unpack_ex(root, &up_error , 0, "{s:s}","version",&s1) == 0) -// strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); -/* - // os.windows... - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useColor",&b1) == 0) - mySettings.os_windows_usecolor = b1; - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useAnsiColor",&b1) == 0) - mySettings.os_windows_useansicolor = b1; -*/ + char tempStr [500]; // to use str_lower() since json unpack uses const char * + // Logging Level - if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { - if (strncmp (s1,"off",3) == 0) session.client_debug_level = OFF; - if (strncmp (s1,"simple",6) == 0) session.client_debug_level = SIMPLE; - if (strncmp (s1,"full",4) == 0) session.client_debug_level = FULL; + if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { + memset (tempStr,0x00,sizeof(tempStr)); + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"off",3) == 0) session.client_debug_level = OFF; + if (strncmp (tempStr,"simple",6) == 0) session.client_debug_level = SIMPLE; + if (strncmp (tempStr,"full",4) == 0) session.client_debug_level = FULL; } // window plot @@ -187,27 +172,22 @@ void settings_load_callback (json_t *root) { session.window_plot_hsize = i1; if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) session.window_plot_wsize = i1; -/* - // window... - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.xpos",&i1) == 0) - mySettings.window_xpos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.ypos",&i1) == 0) - mySettings.window_ypos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.hsize",&i1) == 0) - mySettings.window_hsize = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.wsize",&i1) == 0) - mySettings.window_wsize = i1; -*/ // show options - // typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { - if (strncmp (s1,"alias",5) == 0) session.emoji_mode = ALIAS; - if (strncmp (s1,"emoji",5) == 0) session.emoji_mode = EMOJI; - if (strncmp (s1,"alttext",7) == 0) session.emoji_mode = ALTTEXT; - if (strncmp (s1,"erase",5) == 0) session.emoji_mode = ERASE; + memset (tempStr,0x00,sizeof(tempStr)); + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"alias",5) == 0) session.emoji_mode = ALIAS; + if (strncmp (tempStr,"emoji",5) == 0) session.emoji_mode = EMOJI; + if (strncmp (tempStr,"alttext",7) == 0) session.emoji_mode = ALTTEXT; + if (strncmp (tempStr,"erase",5) == 0) session.emoji_mode = ERASE; } + if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) session.show_hints = b1; + if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.supports.colors",&b1) == 0) + session.supports_colors = b1; + } From 68faa88e6afcc8e17a13f3ffedd054877b17ef8d Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 21:02:46 +0200 Subject: [PATCH 42/66] Auth test --- armsrc/appmain.c | 2 +- armsrc/mifaredesfire.c | 769 ++++++++++++++++++----------------------- armsrc/mifaredesfire.h | 3 +- client/cmdhfmfdes.c | 70 +++- 4 files changed, 387 insertions(+), 457 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 5bec32364..15eb40f26 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1271,7 +1271,7 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_DESFIRE_AUTH1: { - MifareDES_Auth1(packet->oldarg[0], packet->oldarg[1], packet->oldarg[2], packet->data.asBytes); + MifareDES_Auth1(packet->data.asBytes); break; } case CMD_HF_DESFIRE_AUTH2: { diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index ba2b20d2d..815c301ac 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -185,178 +185,340 @@ void MifareDesfireGetInformation() { OnSuccess(); } -void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { - // mode = arg0 - // algo = arg1 - // keyno = arg2 +typedef enum { + MFDES_AUTH_DES = 1, + MFDES_AUTH_ISO = 2, + MFDES_AUTH_AES = 3, + MFDES_AUTH_PICC = 4 +} mifare_des_authmode_t; + +typedef enum { + MFDES_ALGO_DES = 1, + MFDES_ALGO_3DES = 2, + MFDES_ALGO_3K3DES = 3, + MFDES_ALGO_AES = 4 +} mifare_des_authalgo_t; + +void MifareDES_Auth1(uint8_t *datain) { int len = 0; - //uint8_t PICC_MASTER_KEY8[8] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47}; - uint8_t PICC_MASTER_KEY16[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; - //uint8_t null_key_data16[16] = {0x00}; - //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; - //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; - - uint8_t resp[256] = {0x00}; - - size_t datalen = datain[0]; - - uint8_t cmd[40] = {0x00}; - uint8_t encRndB[16] = {0x00}; - uint8_t decRndB[16] = {0x00}; - uint8_t both[32] = {0x00}; - - //InitDesfireCard(); - - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); + struct p { + uint8_t isOK; + uint8_t mode; + uint8_t algo; + uint8_t keyno; + uint8_t key[24]; + uint8_t keylen; + uint8_t sessionkey[24]; + } PACKED; + struct p *payload = (struct p *) datain; // 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32) // 4 different crypto arg1 DES, 3DES, 3K3DES, AES // 3 different communication modes, PLAIN,MAC,CRYPTO - // des, key 0, - switch (arg0) { - case 1: { - uint8_t keybytes[16]; - uint8_t RndA[8] = {0x00}; - uint8_t RndB[8] = {0x00}; + mbedtls_aes_context ctx; - if (arg1 == 2) { - if (datain[1] == 0xff) { - memcpy(keybytes, PICC_MASTER_KEY16, 16); - } else { - memcpy(keybytes, datain + 1, datalen); - } - } else { - if (arg1 == 1) { - if (datain[1] == 0xff) { - uint8_t null_key_data8[8] = {0x00}; - memcpy(keybytes, null_key_data8, 8); - } else { - memcpy(keybytes, datain + 1, datalen); - } - } + uint8_t keybytes[24]; + uint8_t resp[256] = {0x00}; + uint8_t cmd[40] = {0x00}; + + // Crypt constants + uint8_t IV[16] = {0x00}; + uint8_t RndA[16] = {0x00}; + uint8_t RndB[16] = {0x00}; + uint8_t encRndB[16] = {0x00}; + uint8_t rotRndB[16] = {0x00}; //RndB' + uint8_t both[32] = {0x00}; // ek/dk_keyNo(RndA+RndB') + + // Generate Random Value + uint32_t value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &RndA[0]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &RndA[4]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &RndA[8]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &RndA[12]); + + // Default Keys + uint8_t PICC_MASTER_KEY8[8] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + //uint8_t null_key_data16[16] = {0x00}; + //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; + //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; + + + //InitDesfireCard(); + + // Part 1 + LED_A_ON(); + LED_B_OFF(); + LED_C_OFF(); + + if (payload->key==NULL) + { + if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) + { + memcpy(keybytes, PICC_MASTER_KEY8, 8); } + else if (payload->mode==MFDES_AUTH_AES) + { + memcpy(keybytes, PICC_MASTER_KEY16, 16); + } + } + else { + memcpy(keybytes, payload->key, payload->keylen); + } - struct desfire_key defaultkey = {0}; - desfirekey_t key = &defaultkey; + struct desfire_key defaultkey = {0}; + desfirekey_t key = &defaultkey; - if (arg1 == 2) - Desfire_3des_key_new_with_version(keybytes, key); - else if (arg1 == 1) - Desfire_des_key_new(keybytes, key); - - cmd[0] = 0x90; - cmd[1] = AUTHENTICATE; - cmd[2] = 0x0; - cmd[3] = 0x0; - cmd[4] = 0x1; - cmd[5] = arg2; //keynumber - cmd[6] = 0x0; - len = DesfireAPDU(cmd, 7, resp); - - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); + if (payload->algo==MFDES_ALGO_AES) { + mbedtls_aes_init(&ctx); + if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { + if (DBGLEVEL >= DBG_EXTENDED) { + DbpString("mbedtls_aes_setkey_dec failed"); } - OnError(3); + OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); return; } + Desfire_aes_key_new(keybytes, key); + } + else if (payload->algo == MFDES_ALGO_3DES) { + key->type=T_3DES; + Desfire_3des_key_new_with_version(keybytes, key); + } + else if (payload->algo == MFDES_ALGO_DES) { + key->type=T_DES; + Desfire_des_key_new(keybytes, key); + } + else if (payload->algo == MFDES_ALGO_3K3DES) { + Desfire_3k3des_key_new_with_version(keybytes, key); + } - if (resp[2] == (uint8_t)0xaf) { - DbpString("Authentication failed. Invalid key number."); - OnError(3); + uint8_t subcommand=AUTHENTICATE; + + if (payload->mode==MFDES_AUTH_AES) + subcommand=AUTHENTICATE_AES; + else if (payload->mode==MFDES_AUTH_ISO) + subcommand=AUTHENTICATE_ISO; + + if (payload->mode != MFDES_AUTH_PICC) { + // Let's send our auth command + cmd[0] = 0x90; + cmd[1] = subcommand; + cmd[2] = 0x0; + cmd[3] = 0x0; + cmd[4] = 0x1; + cmd[5] = payload->keyno; + cmd[6] = 0x0; + len = DesfireAPDU(cmd, 7, resp); + } + else { + cmd[0] = AUTHENTICATE; + cmd[1] = payload->keyno; + len = DesfireAPDU(cmd, 2, resp); + } + + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + return; + } + + if (resp[2] == (uint8_t)0xaf) { + DbpString("Authentication failed. Invalid key number."); + OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + return; + } + + // Part 2 + if (payload->mode != MFDES_AUTH_PICC) { + memcpy(encRndB, resp + 1, payload->keylen); + } else { + memcpy(encRndB, resp + 2, payload->keylen); + } + + // Part 3 + if (payload->algo==MFDES_ALGO_AES) + mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, RndB); + else if (payload->algo == MFDES_ALGO_3DES) + tdes_dec(&RndB, &encRndB, key->data); + else if (payload->algo == MFDES_ALGO_DES) + des_dec(&RndB, &encRndB, key->data); + + // - Rotate RndB by 8 bits + memcpy(rotRndB, RndB, payload->keylen); + rol(rotRndB, payload->keylen); + + //memcpy(RndA, decRndA, payload->keylen); + uint8_t encRndA[16] = {0x00}; + + // - Encrypt our response + if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) { + if (payload->algo == MFDES_ALGO_3DES) + tdes_dec(&encRndA, &RndA, key->data); + else if (payload->algo == MFDES_ALGO_DES) + des_dec(&encRndA, &RndA, key->data); + + memcpy(both, encRndA, 8); + + for (int x = 0; x < 8; x++) { + rotRndB[x] = rotRndB[x] ^ encRndA[x]; + } + + if (payload->algo == MFDES_ALGO_3DES) + tdes_dec(&encRndB, &rotRndB, key->data); + else if (payload->algo == MFDES_ALGO_DES) + des_dec(&encRndB, &rotRndB, key->data); + + memcpy(both + 8, encRndB, 8); + } + else if (payload->mode==MFDES_AUTH_AES || payload->mode==MFDES_AUTH_ISO) { + uint8_t tmp[32] = {0x00}; + memcpy(tmp, RndA, 16); + memcpy(tmp + 16, rotRndB, 16); + if (payload->algo==MFDES_ALGO_AES) { + if (mbedtls_aes_setkey_enc(&ctx, key->data, 128) != 0) { + if (DBGLEVEL >= DBG_EXTENDED) { + DbpString("mbedtls_aes_setkey_enc failed"); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); return; } + mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, tmp, both); + } + } - memcpy(encRndB, resp + 1, 8); - if (arg1 == 2) - tdes_dec(&decRndB, &encRndB, key->data); - else if (arg1 == 1) - des_dec(&decRndB, &encRndB, key->data); + if (payload->mode != MFDES_AUTH_PICC) { + cmd[0] = 0x90; + cmd[1] = ADDITIONAL_FRAME; + cmd[2] = 0x00; + cmd[3] = 0x00; + cmd[4] = (payload->keylen * 2); + memcpy(cmd + 5, both, payload->keylen * 2); + cmd[(payload->keylen * 2) + 5] = 0x0; + len = DesfireAPDU(cmd, 5 + (payload->keylen * 2) + 1, resp); + } else { + cmd[0] = ADDITIONAL_FRAME; + memcpy(cmd + 1, both, 16); + len = DesfireAPDU(cmd, 1 + 16, resp); + } - memcpy(RndB, decRndB, 8); - rol(decRndB, 8); + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + return; + } - // This should be random - uint8_t decRndA[8] = {0x00}; - uint32_t value = prng_successor(GetTickCount(), 32); - num_to_bytes(value, 4, &decRndA[0]); - value = prng_successor(GetTickCount(), 32); - num_to_bytes(value, 4, &decRndA[4]); + if (payload->mode != MFDES_AUTH_PICC) { + if ((resp[len - 4] != 0x91) || (resp[len - 3] != 0x00)) { + DbpString("Authentication failed."); + OnErrorNG(CMD_HF_DESFIRE_AUTH1,6); + return; + } + } + else { + if (resp[1] != 0x00) { + DbpString("Authentication failed."); + OnErrorNG(CMD_HF_DESFIRE_AUTH1,6); + return; + } + } - memcpy(RndA, decRndA, 8); - uint8_t encRndA[8] = {0x00}; + // Part 4 + struct desfire_key sessionKey = {0}; + desfirekey_t skey = &sessionKey; + Desfire_session_key_new(RndA, RndB, key, skey); + memset(payload->sessionkey,0x0,24); + memcpy(payload->sessionkey,skey->data,payload->keylen); + print_result("SESSION : ", skey->data, payload->keylen); + print_result("SESSION : ", payload->sessionkey, payload->keylen); - if (arg1 == 2) - tdes_dec(&encRndA, &decRndA, key->data); - else if (arg1 == 1) - des_dec(&encRndA, &decRndA, key->data); + if (payload->mode != MFDES_AUTH_PICC) { + memcpy(encRndA, resp + 1, payload->keylen); + } + else { + memcpy(encRndA, resp + 2, payload->keylen); + } - memcpy(both, encRndA, 8); + if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) { + if (payload->algo == MFDES_ALGO_3DES) + tdes_dec(&encRndA, &encRndA, key->data); + else if (payload->algo == MFDES_ALGO_DES) + des_dec(&encRndA, &encRndA, key->data); + } + else if (payload->mode==MFDES_AUTH_AES) { + mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndA, encRndA); + } - for (int x = 0; x < 8; x++) { - decRndB[x] = decRndB[x] ^ encRndA[x]; + rol(RndA, payload->keylen); + print_result("RndA : ", RndA, payload->keylen); + print_result("encRndA : ", encRndA, payload->keylen); + for (int x = 0; x < payload->keylen; x++) { + if (RndA[x] != encRndA[x]) { + DbpString("Authentication failed. Cannot verify Session Key."); + OnErrorNG(CMD_HF_DESFIRE_AUTH1,4); + return; + } + } + //Change the selected key to a new value. - } + /* + // Current key is a 3DES key, change it to a DES key + if (payload->algo == 2) { + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = payload->keyno; - if (arg1 == 2) - tdes_dec(&encRndB, &decRndB, key->data); - else if (arg1 == 1) - des_dec(&encRndB, &decRndB, key->data); + uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; - memcpy(both + 8, encRndB, 8); + uint8_t first, second; + uint8_t buff1[8] = {0x00}; + uint8_t buff2[8] = {0x00}; + uint8_t buff3[8] = {0x00}; - cmd[0] = 0x90; - cmd[1] = ADDITIONAL_FRAME; - cmd[2] = 0x00; - cmd[3] = 0x00; - cmd[4] = 0x10; - memcpy(cmd + 5, both, 16); - cmd[16 + 5] = 0x0; - len = DesfireAPDU(cmd, 5 + 16 + 1, resp); - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); - } - OnError(3); - return; - } + memcpy(buff1,newKey, 8); + memcpy(buff2,newKey + 8, 8); - if (resp[len - 3] == 0x00) { + compute_crc(CRC_14443_A, newKey, 16, &first, &second); + memcpy(buff3, &first, 1); + memcpy(buff3 + 1, &second, 1); - struct desfire_key sessionKey = {0}; - desfirekey_t skey = &sessionKey; - Desfire_session_key_new(RndA, RndB, key, skey); - //print_result("SESSION : ", skey->data, 8); + tdes_dec(&buff1, &buff1, skey->data); + memcpy(cmd+2,buff1,8); - memcpy(encRndA, resp + 1, 8); + for (int x = 0; x < 8; x++) { + buff2[x] = buff2[x] ^ buff1[x]; + } + tdes_dec(&buff2, &buff2, skey->data); + memcpy(cmd+10,buff2,8); - if (arg1 == 2) - tdes_dec(&encRndA, &encRndA, key->data); - else if (arg1 == 1) - des_dec(&encRndA, &encRndA, key->data); + for (int x = 0; x < 8; x++) { + buff3[x] = buff3[x] ^ buff2[x]; + } + tdes_dec(&buff3, &buff3, skey->data); + memcpy(cmd+19,buff3,8); - rol(decRndA, 8); - for (int x = 0; x < 8; x++) { - if (decRndA[x] != encRndA[x]) { - DbpString("Authentication failed. Cannot verify PICC."); - OnError(4); - return; - } - } + // The command always times out on the first attempt, this will retry until a response + // is recieved. + len = 0; + while(!len) { + len = DesfireAPDU(cmd,27,resp); + } - //Change the selected key to a new value. - - /* - // Current key is a 3DES key, change it to a DES key - if (arg1 == 2) { + } else { + // Current key is a DES key, change it to a 3DES key + if (payload->algo == 1) { cmd[0] = 0x90; cmd[1] = CHANGE_KEY; - cmd[2] = arg2; + cmd[2] = payload->keyno; - uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; + uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; uint8_t first, second; uint8_t buff1[8] = {0x00}; @@ -370,319 +532,39 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(buff3, &first, 1); memcpy(buff3 + 1, &second, 1); - tdes_dec(&buff1, &buff1, skey->data); - memcpy(cmd+2,buff1,8); + des_dec(&buff1, &buff1, skey->data); + memcpy(cmd+3,buff1,8); - for (int x = 0; x < 8; x++) { - buff2[x] = buff2[x] ^ buff1[x]; - } - tdes_dec(&buff2, &buff2, skey->data); - memcpy(cmd+10,buff2,8); - - for (int x = 0; x < 8; x++) { - buff3[x] = buff3[x] ^ buff2[x]; - } - tdes_dec(&buff3, &buff3, skey->data); - memcpy(cmd+19,buff3,8); - - // The command always times out on the first attempt, this will retry until a response - // is recieved. - len = 0; - while(!len) { - len = DesfireAPDU(cmd,27,resp); - } - - } else { - // Current key is a DES key, change it to a 3DES key - if (arg1 == 1) { - cmd[0] = 0x90; - cmd[1] = CHANGE_KEY; - cmd[2] = arg2; - - uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; - - uint8_t first, second; - uint8_t buff1[8] = {0x00}; - uint8_t buff2[8] = {0x00}; - uint8_t buff3[8] = {0x00}; - - memcpy(buff1,newKey, 8); - memcpy(buff2,newKey + 8, 8); - - compute_crc(CRC_14443_A, newKey, 16, &first, &second); - memcpy(buff3, &first, 1); - memcpy(buff3 + 1, &second, 1); - - des_dec(&buff1, &buff1, skey->data); - memcpy(cmd+3,buff1,8); - - for (int x = 0; x < 8; x++) { - buff2[x] = buff2[x] ^ buff1[x]; - } - des_dec(&buff2, &buff2, skey->data); - memcpy(cmd+11,buff2,8); - - for (int x = 0; x < 8; x++) { - buff3[x] = buff3[x] ^ buff2[x]; - } - des_dec(&buff3, &buff3, skey->data); - memcpy(cmd+19,buff3,8); - - // The command always times out on the first attempt, this will retry until a response - // is recieved. - len = 0; - while(!len) { - len = DesfireAPDU(cmd,27,resp); - } - } - } - */ - - //OnSuccess(); - if (arg1 == 2) - reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); - else if (arg1 == 1) - reply_old(CMD_ACK, 1, 0, 0, skey->data, 8); - } else { - DbpString("Authentication failed."); - OnError(6); - return; - } + for (int x = 0; x < 8; x++) { + buff2[x] = buff2[x] ^ buff1[x]; } - break; - case 2: { - //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp); - uint8_t keybytes[16]; - uint8_t RndA[8] = {0x00}; - uint8_t RndB[8] = {0x00}; + des_dec(&buff2, &buff2, skey->data); + memcpy(cmd+11,buff2,8); - if (arg1 == 2) { - if (datain[1] == 0xff) { - memcpy(keybytes, PICC_MASTER_KEY16, 16); - } else { - memcpy(keybytes, datain + 1, datalen); - } - } else { - if (arg1 == 1) { - if (datain[1] == 0xff) { - uint8_t null_key_data8[8] = {0x00}; - memcpy(keybytes, null_key_data8, 8); - } else { - memcpy(keybytes, datain + 1, datalen); - } - } - } - - struct desfire_key defaultkey = {0}; - desfirekey_t key = &defaultkey; - - if (arg1 == 2) - Desfire_3des_key_new_with_version(keybytes, key); - else if (arg1 == 1) - Desfire_des_key_new(keybytes, key); - - cmd[0] = AUTHENTICATE; - cmd[1] = arg2; //keynumber - len = DesfireAPDU(cmd, 2, resp); - - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); - } - OnError(3); - return; - } - - if (resp[2] == (uint8_t)0xaf) { - DbpString("Authentication failed. Invalid key number."); - OnError(3); - return; - } - - memcpy(encRndB, resp + 2, 8); - if (arg1 == 2) - tdes_dec(&decRndB, &encRndB, key->data); - else if (arg1 == 1) - des_dec(&decRndB, &encRndB, key->data); - - memcpy(RndB, decRndB, 8); - rol(decRndB, 8); - - // This should be random - uint8_t decRndA[8] = {0x00}; - uint32_t value = prng_successor(GetTickCount(), 32); - num_to_bytes(value, 4, &decRndA[0]); - value = prng_successor(GetTickCount(), 32); - num_to_bytes(value, 4, &decRndA[4]); - - memcpy(RndA, decRndA, 8); - uint8_t encRndA[8] = {0x00}; - - if (arg1 == 2) - tdes_dec(&encRndA, &decRndA, key->data); - else if (arg1 == 1) - des_dec(&encRndA, &decRndA, key->data); - - memcpy(both, encRndA, 8); - - for (int x = 0; x < 8; x++) { - decRndB[x] = decRndB[x] ^ encRndA[x]; - - } - - if (arg1 == 2) - tdes_dec(&encRndB, &decRndB, key->data); - else if (arg1 == 1) - des_dec(&encRndB, &decRndB, key->data); - - memcpy(both + 8, encRndB, 8); - - cmd[0] = ADDITIONAL_FRAME; - memcpy(cmd + 1, both, 16); - len = DesfireAPDU(cmd, 1 + 16, resp); - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); - } - OnError(3); - return; - } - - if (resp[1] == 0x00) { - struct desfire_key sessionKey = {0}; - desfirekey_t skey = &sessionKey; - Desfire_session_key_new(RndA, RndB, key, skey); - //print_result("SESSION : ", skey->data, 8); - - memcpy(encRndA, resp + 2, 8); - - if (arg1 == 2) - tdes_dec(&encRndA, &encRndA, key->data); - else if (arg1 == 1) - des_dec(&encRndA, &encRndA, key->data); - - rol(decRndA, 8); - for (int x = 0; x < 8; x++) { - if (decRndA[x] != encRndA[x]) { - DbpString("Authentication failed. Cannot verify PICC."); - OnError(4); - return; - } - } - - //OnSuccess(); - if (arg1 == 2) - reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); - else if (arg1 == 1) - reply_old(CMD_ACK, 1, 0, 0, skey->data, 8); - } else { - DbpString("Authentication failed."); - OnError(6); - return; - } + for (int x = 0; x < 8; x++) { + buff3[x] = buff3[x] ^ buff2[x]; } - break; - case 3: { - //defaultkey - uint8_t keybytes[16] = {0x00}; - if (datain[1] == 0xff) { - memcpy(keybytes, PICC_MASTER_KEY16, 16); - } else { - memcpy(keybytes, datain + 1, datalen); - } + des_dec(&buff3, &buff3, skey->data); + memcpy(cmd+19,buff3,8); - struct desfire_key defaultkey = {0x00}; - desfirekey_t key = &defaultkey; - Desfire_aes_key_new(keybytes, key); - - mbedtls_aes_context ctx; - uint8_t IV[16] = {0x00}; - mbedtls_aes_init(&ctx); - - cmd[0] = 0x90; - cmd[1] = AUTHENTICATE_AES; - cmd[2] = 0x0; - cmd[3] = 0x0; - cmd[4] = 0x1; - cmd[5] = arg2; //keynumber - cmd[6] = 0x0; - len = DesfireAPDU(cmd, 7, resp); - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); - } - OnError(3); - return; - } - - memcpy(encRndB, resp + 1, 16); - - // dekryptera tagnonce. - if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { - if (DBGLEVEL >= DBG_EXTENDED) { - DbpString("mbedtls_aes_setkey_dec failed"); - } - OnError(7); - return; - } - mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, decRndB); - rol(decRndB, 16); - uint8_t nonce[16] = {0x00}; - uint32_t val = prng_successor(GetTickCount(), 32); - num_to_bytes(val, 4, &nonce[0]); - val = prng_successor(GetTickCount(), 32); - num_to_bytes(val, 4, &nonce[4]); - val = prng_successor(GetTickCount(), 32); - num_to_bytes(val, 4, &nonce[8]); - val = prng_successor(GetTickCount(), 32); - num_to_bytes(val, 4, &nonce[12]); - memcpy(both, nonce, 16); - memcpy(both + 16, decRndB, 16); - uint8_t encBoth[32] = {0x00}; - if (mbedtls_aes_setkey_enc(&ctx, key->data, 128) != 0) { - if (DBGLEVEL >= DBG_EXTENDED) { - DbpString("mbedtls_aes_setkey_enc failed"); - } - OnError(7); - return; - } - mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, both, encBoth); - - cmd[0] = 0x90; - cmd[1] = ADDITIONAL_FRAME; - cmd[2] = 0x00; - cmd[3] = 0x00; - cmd[4] = 0x20; - memcpy(cmd + 5, encBoth, 32); - cmd[32 + 5] = 0x0; - - len = DesfireAPDU(cmd, 5 + 32 + 1, resp); - if (!len) { - if (DBGLEVEL >= DBG_ERROR) { - DbpString("Authentication failed. Card timeout."); - } - OnError(3); - return; - } - - if ((resp[1 + 16] == 0x91) && (resp[1 + 16 + 1] == 0x00)) { - // Create AES Session key - struct desfire_key sessionKey = {0}; - desfirekey_t skey = &sessionKey; - Desfire_session_key_new(nonce, decRndB, key, skey); - print_result("SESSION : ", skey->data, 16); - } else { - DbpString("Authentication failed."); - OnError(7); - return; - } - - break; + // The command always times out on the first attempt, this will retry until a response + // is recieved. + len = 0; + while(!len) { + len = DesfireAPDU(cmd,27,resp); } - } + } + } + */ + //OnSuccess(); - reply_mix(CMD_ACK, 1, len, 0, resp, len); + //reply_old(CMD_ACK, 1, 0, 0, skey->data, payload->keylen); + //reply_mix(CMD_ACK, 1, len, 0, resp, len); + + LED_B_ON(); + reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)payload, sizeof(payload)); + LED_B_OFF(); } // 3 different ISO ways to send data to a DESFIRE (direct, capsuled, capsuled ISO) @@ -767,3 +649,8 @@ void OnError(uint8_t reason) { reply_mix(CMD_ACK, 0, reason, 0, 0, 0); OnSuccess(); } + +void OnErrorNG(uint16_t cmd, uint8_t reason) { + reply_ng(cmd, reason, NULL, 0); + OnSuccess(); +} \ No newline at end of file diff --git a/armsrc/mifaredesfire.h b/armsrc/mifaredesfire.h index 8daed69aa..ae4b135c5 100644 --- a/armsrc/mifaredesfire.h +++ b/armsrc/mifaredesfire.h @@ -16,11 +16,12 @@ bool InitDesfireCard(); void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareDesfireGetInformation(); -void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); +void MifareDES_Auth1(uint8_t *datain); void ReaderMifareDES(uint32_t param, uint32_t param2, uint8_t *datain); int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout); size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout); void OnSuccess(); void OnError(uint8_t reason); +void OnErrorNG(uint16_t cmd, uint8_t reason); #endif diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 3e21d60be..da56766f6 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -36,6 +36,20 @@ uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x #define status(x) ( ((uint16_t)(0x91<<8)) + x ) +typedef enum { + MFDES_AUTH_DES = 1, + MFDES_AUTH_ISO = 2, + MFDES_AUTH_AES = 3, + MFDES_AUTH_PICC = 4 +} mifare_des_authmode_t; + +typedef enum { + MFDES_ALGO_DES = 1, + MFDES_ALGO_3DES = 2, + MFDES_ALGO_3K3DES = 3, + MFDES_ALGO_AES = 4 +} mifare_des_authalgo_t; + typedef enum { UNKNOWN = 0, MF3ICD40, @@ -838,18 +852,31 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { uint8_t aid[3] = {0}; int res = get_desfire_select_application(aid); if (res != PM3_SUCCESS) return res; - uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) - memcpy(data + 1, key, keylen); - SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); + struct { + uint8_t isOK; + uint8_t mode; + uint8_t algo; + uint8_t keyno; + uint8_t key[24]; + uint8_t keylen; + uint8_t sessionkey[24]; + } PACKED payload; + payload.keylen=keylen; + memcpy(payload.key,key,keylen); + payload.mode=MFDES_AUTH_PICC; + payload.algo=MFDES_ALGO_DES; + payload.keyno=0; + //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); + SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { PrintAndLogEx(WARNING, "Client command execute timeout"); DropField(); return PM3_ETIMEOUT; } - uint8_t isOK = resp.oldarg[0] & 0xff; + uint8_t isOK = (resp.status==PM3_SUCCESS); if (isOK) { uint8_t rdata[] = {0xFC}; // 0xFC SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); @@ -1492,28 +1519,43 @@ static int CmdHF14ADesAuth(const char *Cmd) { if (res != PM3_SUCCESS) return res; } - // algo, keylength, - uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) - memcpy(data + 1, key, keylength); - SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); + struct { + uint8_t isOK; + uint8_t mode; + uint8_t algo; + uint8_t keyno; + uint8_t key[24]; + uint8_t keylen; + uint8_t sessionkey[24]; + } PACKED payload; + payload.keylen=keylength; + memcpy(payload.key,key,keylength); + payload.mode=cmdAuthMode; + payload.algo=cmdAuthAlgo; + payload.keyno=cmdKeyNo; + //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); + SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); + + //uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) + //memcpy(data + 1, key, keylength); + //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { PrintAndLogEx(WARNING, "Client command execute timeout"); DropField(); return PM3_ETIMEOUT; } - uint8_t isOK = resp.oldarg[0] & 0xff; + uint8_t isOK = (resp.status == PM3_SUCCESS); if (isOK) { - uint8_t *session_key = resp.data.asBytes; + uint8_t *session_key = payload.sessionkey; PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); - //PrintAndLogEx(NORMAL, " Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); } else { - PrintAndLogEx(WARNING, _RED_("Client command failed.")); + PrintAndLogEx(WARNING, _RED_("Client command failed, reason: %d."), resp.status); } PrintAndLogEx(INFO, "-------------------------------------------------------------"); return PM3_SUCCESS; From 08469f940af422e07da60e03fbe7bd4f9dff3c62 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 22:52:16 +0200 Subject: [PATCH 43/66] Replace MIX and OLD Commands --- armsrc/appmain.c | 2 +- armsrc/mifaredesfire.c | 88 ++++++++++++++++++++++++++++-------------- armsrc/mifaredesfire.h | 2 +- client/cmdhfmfdes.c | 43 +++++++++++---------- 4 files changed, 82 insertions(+), 53 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 15eb40f26..b44dbc5c5 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1287,7 +1287,7 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_HF_DESFIRE_COMMAND: { - MifareSendCommand(packet->oldarg[0], packet->oldarg[1], packet->data.asBytes); + MifareSendCommand(packet->data.asBytes); break; } case CMD_HF_MIFARE_NACK_DETECT: { diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 815c301ac..eddff857a 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -52,29 +52,33 @@ bool InitDesfireCard() { return true; } -void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain) { +void MifareSendCommand(uint8_t *datain) { + struct p { + uint8_t flags; + uint8_t datalen; + uint8_t datain[FRAME_PAYLOAD_SIZE]; + } PACKED; + struct p *payload = (struct p *) datain; - uint8_t flags = arg0; - size_t datalen = arg1; uint8_t resp[RECEIVE_SIZE]; memset(resp, 0, sizeof(resp)); if (DBGLEVEL >= DBG_EXTENDED) { - Dbprintf(" flags : %02X", flags); - Dbprintf(" len : %02X", datalen); - print_result(" RX : ", datain, datalen); + Dbprintf(" flags : %02X", payload->flags); + Dbprintf(" len : %02X", payload->datalen); + print_result(" RX : ", payload->datain, payload->datalen); } - if (flags & CLEARTRACE) + if (payload->flags & CLEARTRACE) clear_trace(); - if (flags & INIT) { + if (payload->flags & INIT) { if (!InitDesfireCard()) { return; } } - int len = DesfireAPDU(datain, datalen, resp); + int len = DesfireAPDU(payload->datain, payload->datalen, resp); if (DBGLEVEL >= DBG_EXTENDED) print_result("RESP <--: ", resp, len); @@ -83,10 +87,21 @@ void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain) { return; } - if (flags & DISCONNECT) + if (payload->flags & DISCONNECT) OnSuccess(); - reply_mix(CMD_ACK, 1, len, 0, resp, len); + //reply_mix(CMD_ACK, 1, len, 0, resp, len); + LED_B_ON(); + struct r { + uint8_t len; + uint8_t data[RECEIVE_SIZE]; + } PACKED; + + struct r rpayload; + rpayload.len=len; + memcpy(rpayload.data,resp,rpayload.len); + reply_ng(CMD_HF_DESFIRE_COMMAND, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); + LED_B_OFF(); } void MifareDesfireGetInformation() { @@ -202,13 +217,11 @@ typedef enum { void MifareDES_Auth1(uint8_t *datain) { int len = 0; struct p { - uint8_t isOK; uint8_t mode; uint8_t algo; uint8_t keyno; uint8_t key[24]; uint8_t keylen; - uint8_t sessionkey[24]; } PACKED; struct p *payload = (struct p *) datain; @@ -275,13 +288,6 @@ void MifareDES_Auth1(uint8_t *datain) { if (payload->algo==MFDES_ALGO_AES) { mbedtls_aes_init(&ctx); - if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { - if (DBGLEVEL >= DBG_EXTENDED) { - DbpString("mbedtls_aes_setkey_dec failed"); - } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); - return; - } Desfire_aes_key_new(keybytes, key); } else if (payload->algo == MFDES_ALGO_3DES) { @@ -342,8 +348,16 @@ void MifareDES_Auth1(uint8_t *datain) { } // Part 3 - if (payload->algo==MFDES_ALGO_AES) + if (payload->algo==MFDES_ALGO_AES) { + if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { + if (DBGLEVEL >= DBG_EXTENDED) { + DbpString("mbedtls_aes_setkey_dec failed"); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); + return; + } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, RndB); + } else if (payload->algo == MFDES_ALGO_3DES) tdes_dec(&RndB, &encRndB, key->data); else if (payload->algo == MFDES_ALGO_DES) @@ -353,7 +367,6 @@ void MifareDES_Auth1(uint8_t *datain) { memcpy(rotRndB, RndB, payload->keylen); rol(rotRndB, payload->keylen); - //memcpy(RndA, decRndA, payload->keylen); uint8_t encRndA[16] = {0x00}; // - Encrypt our response @@ -434,10 +447,8 @@ void MifareDES_Auth1(uint8_t *datain) { struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; Desfire_session_key_new(RndA, RndB, key, skey); - memset(payload->sessionkey,0x0,24); - memcpy(payload->sessionkey,skey->data,payload->keylen); - print_result("SESSION : ", skey->data, payload->keylen); - print_result("SESSION : ", payload->sessionkey, payload->keylen); + if (DBGLEVEL >= DBG_EXTENDED) + print_result("SESSIONKEY : ", skey->data, payload->keylen); if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndA, resp + 1, payload->keylen); @@ -453,12 +464,21 @@ void MifareDES_Auth1(uint8_t *datain) { des_dec(&encRndA, &encRndA, key->data); } else if (payload->mode==MFDES_AUTH_AES) { - mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndA, encRndA); + if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { + if (DBGLEVEL >= DBG_EXTENDED) { + DbpString("mbedtls_aes_setkey_dec failed"); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); + return; + } + mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndA, encRndA); } rol(RndA, payload->keylen); - print_result("RndA : ", RndA, payload->keylen); - print_result("encRndA : ", encRndA, payload->keylen); + if (DBGLEVEL >= DBG_EXTENDED) { + print_result("RndA : ", RndA, payload->keylen); + print_result("encRndA : ", encRndA, payload->keylen); + } for (int x = 0; x < payload->keylen; x++) { if (RndA[x] != encRndA[x]) { DbpString("Authentication failed. Cannot verify Session Key."); @@ -563,7 +583,15 @@ void MifareDES_Auth1(uint8_t *datain) { //reply_mix(CMD_ACK, 1, len, 0, resp, len); LED_B_ON(); - reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)payload, sizeof(payload)); + struct r { + uint8_t sessionkeylen; + uint8_t sessionkey[24]; + } PACKED; + + struct r rpayload; + rpayload.sessionkeylen=payload->keylen; + memcpy(rpayload.sessionkey,skey->data,rpayload.sessionkeylen); + reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); LED_B_OFF(); } diff --git a/armsrc/mifaredesfire.h b/armsrc/mifaredesfire.h index ae4b135c5..1e19ec49f 100644 --- a/armsrc/mifaredesfire.h +++ b/armsrc/mifaredesfire.h @@ -14,7 +14,7 @@ #include "common.h" bool InitDesfireCard(); -void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain); +void MifareSendCommand(uint8_t *datain); void MifareDesfireGetInformation(); void MifareDES_Auth1(uint8_t *datain); void ReaderMifareDES(uint32_t param, uint32_t param2, uint8_t *datain); diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index da56766f6..b23d78ec3 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -853,20 +853,17 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { int res = get_desfire_select_application(aid); if (res != PM3_SUCCESS) return res; struct { - uint8_t isOK; uint8_t mode; uint8_t algo; uint8_t keyno; uint8_t key[24]; uint8_t keylen; - uint8_t sessionkey[24]; } PACKED payload; payload.keylen=keylen; memcpy(payload.key,key,keylen); payload.mode=MFDES_AUTH_PICC; payload.algo=MFDES_ALGO_DES; payload.keyno=0; - //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); PacketResponseNG resp; @@ -878,14 +875,26 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { uint8_t isOK = (resp.status==PM3_SUCCESS); if (isOK) { - uint8_t rdata[] = {0xFC}; // 0xFC - SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); - if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + struct { + uint8_t flags; + uint8_t datalen; + uint8_t datain[FRAME_PAYLOAD_SIZE]; + } PACKED payload; + payload.datain[0]=0xFC; + payload.flags=NONE; + payload.datalen=1; + SendCommandNG(CMD_HF_DESFIRE_COMMAND,(uint8_t*)&payload,sizeof(payload)); + if (!WaitForResponseTimeout(CMD_HF_DESFIRE_COMMAND, &resp, 3000)) { PrintAndLogEx(WARNING, "Client reset command execute timeout"); DropField(); return PM3_ETIMEOUT; } - if (resp.oldarg[0] & 0xFF) { + if (resp.status==PM3_SUCCESS) { + /*struct r { + uint8_t len; + uint8_t data[RECEIVE_SIZE]; + } PACKED; + struct r *rpayload = (struct r *)&resp.data.asBytes;*/ PrintAndLogEx(INFO, "Card successfully reset"); return PM3_SUCCESS; } @@ -1407,7 +1416,6 @@ static int CmdHF14ADesAuth(const char *Cmd) { // 2 = 3DES 16 // 3 = 3K 3DES 24 // 4 = AES 16 - //SetAPDULogging(true); uint8_t keylength = 8; CLIParserInit("hf mfdes auth", @@ -1443,14 +1451,12 @@ static int CmdHF14ADesAuth(const char *Cmd) { if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); - //SetAPDULogging(false); return PM3_EINVARG; } // AID if (aidlength != 3) { PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - //SetAPDULogging(false); return PM3_EINVARG; } @@ -1458,27 +1464,23 @@ static int CmdHF14ADesAuth(const char *Cmd) { case 1: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; case 2: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; case 3: if (cmdAuthAlgo != 4) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - //SetAPDULogging(false); return PM3_EINVARG; } break; default: PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - //SetAPDULogging(false); return PM3_EINVARG; } @@ -1520,25 +1522,19 @@ static int CmdHF14ADesAuth(const char *Cmd) { } struct { - uint8_t isOK; uint8_t mode; uint8_t algo; uint8_t keyno; uint8_t key[24]; uint8_t keylen; - uint8_t sessionkey[24]; } PACKED payload; payload.keylen=keylength; memcpy(payload.key,key,keylength); payload.mode=cmdAuthMode; payload.algo=cmdAuthAlgo; payload.keyno=cmdKeyNo; - //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); - //uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) - //memcpy(data + 1, key, keylength); - //SendCommandOLD(CMD_HF_DESFIRE_AUTH1, cmdAuthMode, cmdAuthAlgo, cmdKeyNo, data, keylength + 1); PacketResponseNG resp; if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { @@ -1549,8 +1545,13 @@ static int CmdHF14ADesAuth(const char *Cmd) { uint8_t isOK = (resp.status == PM3_SUCCESS); if (isOK) { - uint8_t *session_key = payload.sessionkey; + struct r { + uint8_t sessionkeylen; + uint8_t sessionkey[24]; + } PACKED; + struct r *rpayload = (struct r *)&resp.data.asBytes; + uint8_t *session_key = rpayload->sessionkey; PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); From 8f3a02fc504fa80e6013f96ef017f426e87fae8f Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 22:56:45 +0200 Subject: [PATCH 44/66] Add Deselect on info and enum --- client/cmdhfmfdes.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index b23d78ec3..c3989401f 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -908,7 +908,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { static int CmdHF14ADesInfo(const char *Cmd) { (void)Cmd; // Cmd is not used so far - + DropField(); SendCommandNG(CMD_HF_DESFIRE_INFO, NULL, 0); PacketResponseNG resp; @@ -1298,7 +1298,7 @@ static int DecodeFileSettings(uint8_t *filesettings, int fileset_len, int maclen static int CmdHF14ADesEnumApplications(const char *Cmd) { (void)Cmd; // Cmd is not used so far - + DropField(); // uint8_t isOK = 0x00; uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; From 70b000bc795a98c478271849c9a9eb283cca164e Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 22:59:55 +0200 Subject: [PATCH 45/66] Make style --- armsrc/mifaredesfire.c | 252 +++++++++++++++++++---------------------- client/cmdhfmfdes.c | 46 ++++---- 2 files changed, 142 insertions(+), 156 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index eddff857a..be8889d48 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -98,8 +98,8 @@ void MifareSendCommand(uint8_t *datain) { } PACKED; struct r rpayload; - rpayload.len=len; - memcpy(rpayload.data,resp,rpayload.len); + rpayload.len = len; + memcpy(rpayload.data, resp, rpayload.len); reply_ng(CMD_HF_DESFIRE_COMMAND, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); LED_B_OFF(); } @@ -254,7 +254,7 @@ void MifareDES_Auth1(uint8_t *datain) { num_to_bytes(value, 4, &RndA[12]); // Default Keys - uint8_t PICC_MASTER_KEY8[8] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t PICC_MASTER_KEY8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //uint8_t null_key_data16[16] = {0x00}; //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; @@ -268,46 +268,38 @@ void MifareDES_Auth1(uint8_t *datain) { LED_B_OFF(); LED_C_OFF(); - if (payload->key==NULL) - { - if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) - { - memcpy(keybytes, PICC_MASTER_KEY8, 8); - } - else if (payload->mode==MFDES_AUTH_AES) - { - memcpy(keybytes, PICC_MASTER_KEY16, 16); - } - } - else { - memcpy(keybytes, payload->key, payload->keylen); + if (payload->key == NULL) { + if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { + memcpy(keybytes, PICC_MASTER_KEY8, 8); + } else if (payload->mode == MFDES_AUTH_AES) { + memcpy(keybytes, PICC_MASTER_KEY16, 16); } + } else { + memcpy(keybytes, payload->key, payload->keylen); + } struct desfire_key defaultkey = {0}; desfirekey_t key = &defaultkey; - if (payload->algo==MFDES_ALGO_AES) { - mbedtls_aes_init(&ctx); - Desfire_aes_key_new(keybytes, key); - } - else if (payload->algo == MFDES_ALGO_3DES) { - key->type=T_3DES; + if (payload->algo == MFDES_ALGO_AES) { + mbedtls_aes_init(&ctx); + Desfire_aes_key_new(keybytes, key); + } else if (payload->algo == MFDES_ALGO_3DES) { + key->type = T_3DES; Desfire_3des_key_new_with_version(keybytes, key); - } - else if (payload->algo == MFDES_ALGO_DES) { - key->type=T_DES; + } else if (payload->algo == MFDES_ALGO_DES) { + key->type = T_DES; Desfire_des_key_new(keybytes, key); - } - else if (payload->algo == MFDES_ALGO_3K3DES) { + } else if (payload->algo == MFDES_ALGO_3K3DES) { Desfire_3k3des_key_new_with_version(keybytes, key); } - uint8_t subcommand=AUTHENTICATE; + uint8_t subcommand = AUTHENTICATE; - if (payload->mode==MFDES_AUTH_AES) - subcommand=AUTHENTICATE_AES; - else if (payload->mode==MFDES_AUTH_ISO) - subcommand=AUTHENTICATE_ISO; + if (payload->mode == MFDES_AUTH_AES) + subcommand = AUTHENTICATE_AES; + else if (payload->mode == MFDES_AUTH_ISO) + subcommand = AUTHENTICATE_ISO; if (payload->mode != MFDES_AUTH_PICC) { // Let's send our auth command @@ -319,8 +311,7 @@ void MifareDES_Auth1(uint8_t *datain) { cmd[5] = payload->keyno; cmd[6] = 0x0; len = DesfireAPDU(cmd, 7, resp); - } - else { + } else { cmd[0] = AUTHENTICATE; cmd[1] = payload->keyno; len = DesfireAPDU(cmd, 2, resp); @@ -330,13 +321,13 @@ void MifareDES_Auth1(uint8_t *datain) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 3); return; } if (resp[2] == (uint8_t)0xaf) { DbpString("Authentication failed. Invalid key number."); - OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 3); return; } @@ -348,17 +339,16 @@ void MifareDES_Auth1(uint8_t *datain) { } // Part 3 - if (payload->algo==MFDES_ALGO_AES) { + if (payload->algo == MFDES_ALGO_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { if (DBGLEVEL >= DBG_EXTENDED) { DbpString("mbedtls_aes_setkey_dec failed"); } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 7); return; } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, RndB); - } - else if (payload->algo == MFDES_ALGO_3DES) + } else if (payload->algo == MFDES_ALGO_3DES) tdes_dec(&RndB, &encRndB, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&RndB, &encRndB, key->data); @@ -370,7 +360,7 @@ void MifareDES_Auth1(uint8_t *datain) { uint8_t encRndA[16] = {0x00}; // - Encrypt our response - if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) { + if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { if (payload->algo == MFDES_ALGO_3DES) tdes_dec(&encRndA, &RndA, key->data); else if (payload->algo == MFDES_ALGO_DES) @@ -388,17 +378,16 @@ void MifareDES_Auth1(uint8_t *datain) { des_dec(&encRndB, &rotRndB, key->data); memcpy(both + 8, encRndB, 8); - } - else if (payload->mode==MFDES_AUTH_AES || payload->mode==MFDES_AUTH_ISO) { + } else if (payload->mode == MFDES_AUTH_AES || payload->mode == MFDES_AUTH_ISO) { uint8_t tmp[32] = {0x00}; memcpy(tmp, RndA, 16); memcpy(tmp + 16, rotRndB, 16); - if (payload->algo==MFDES_ALGO_AES) { + if (payload->algo == MFDES_ALGO_AES) { if (mbedtls_aes_setkey_enc(&ctx, key->data, 128) != 0) { if (DBGLEVEL >= DBG_EXTENDED) { DbpString("mbedtls_aes_setkey_enc failed"); } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 7); return; } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, tmp, both); @@ -424,21 +413,20 @@ void MifareDES_Auth1(uint8_t *datain) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,3); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 3); return; } if (payload->mode != MFDES_AUTH_PICC) { if ((resp[len - 4] != 0x91) || (resp[len - 3] != 0x00)) { DbpString("Authentication failed."); - OnErrorNG(CMD_HF_DESFIRE_AUTH1,6); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 6); return; } - } - else { + } else { if (resp[1] != 0x00) { DbpString("Authentication failed."); - OnErrorNG(CMD_HF_DESFIRE_AUTH1,6); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 6); return; } } @@ -452,23 +440,21 @@ void MifareDES_Auth1(uint8_t *datain) { if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndA, resp + 1, payload->keylen); - } - else { + } else { memcpy(encRndA, resp + 2, payload->keylen); } - if (payload->mode==MFDES_AUTH_DES || payload->mode==MFDES_AUTH_PICC) { + if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { if (payload->algo == MFDES_ALGO_3DES) tdes_dec(&encRndA, &encRndA, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&encRndA, &encRndA, key->data); - } - else if (payload->mode==MFDES_AUTH_AES) { + } else if (payload->mode == MFDES_AUTH_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { if (DBGLEVEL >= DBG_EXTENDED) { DbpString("mbedtls_aes_setkey_dec failed"); } - OnErrorNG(CMD_HF_DESFIRE_AUTH1,7); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 7); return; } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndA, encRndA); @@ -482,100 +468,100 @@ void MifareDES_Auth1(uint8_t *datain) { for (int x = 0; x < payload->keylen; x++) { if (RndA[x] != encRndA[x]) { DbpString("Authentication failed. Cannot verify Session Key."); - OnErrorNG(CMD_HF_DESFIRE_AUTH1,4); + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 4); return; } } - //Change the selected key to a new value. + //Change the selected key to a new value. - /* - // Current key is a 3DES key, change it to a DES key - if (payload->algo == 2) { - cmd[0] = 0x90; - cmd[1] = CHANGE_KEY; - cmd[2] = payload->keyno; + /* + // Current key is a 3DES key, change it to a DES key + if (payload->algo == 2) { + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = payload->keyno; - uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; + uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; - uint8_t first, second; - uint8_t buff1[8] = {0x00}; - uint8_t buff2[8] = {0x00}; - uint8_t buff3[8] = {0x00}; + uint8_t first, second; + uint8_t buff1[8] = {0x00}; + uint8_t buff2[8] = {0x00}; + uint8_t buff3[8] = {0x00}; - memcpy(buff1,newKey, 8); - memcpy(buff2,newKey + 8, 8); + memcpy(buff1,newKey, 8); + memcpy(buff2,newKey + 8, 8); - compute_crc(CRC_14443_A, newKey, 16, &first, &second); - memcpy(buff3, &first, 1); - memcpy(buff3 + 1, &second, 1); + compute_crc(CRC_14443_A, newKey, 16, &first, &second); + memcpy(buff3, &first, 1); + memcpy(buff3 + 1, &second, 1); - tdes_dec(&buff1, &buff1, skey->data); - memcpy(cmd+2,buff1,8); + tdes_dec(&buff1, &buff1, skey->data); + memcpy(cmd+2,buff1,8); - for (int x = 0; x < 8; x++) { - buff2[x] = buff2[x] ^ buff1[x]; - } - tdes_dec(&buff2, &buff2, skey->data); - memcpy(cmd+10,buff2,8); + for (int x = 0; x < 8; x++) { + buff2[x] = buff2[x] ^ buff1[x]; + } + tdes_dec(&buff2, &buff2, skey->data); + memcpy(cmd+10,buff2,8); - for (int x = 0; x < 8; x++) { - buff3[x] = buff3[x] ^ buff2[x]; - } - tdes_dec(&buff3, &buff3, skey->data); - memcpy(cmd+19,buff3,8); + for (int x = 0; x < 8; x++) { + buff3[x] = buff3[x] ^ buff2[x]; + } + tdes_dec(&buff3, &buff3, skey->data); + memcpy(cmd+19,buff3,8); - // The command always times out on the first attempt, this will retry until a response - // is recieved. - len = 0; - while(!len) { - len = DesfireAPDU(cmd,27,resp); - } + // The command always times out on the first attempt, this will retry until a response + // is recieved. + len = 0; + while(!len) { + len = DesfireAPDU(cmd,27,resp); + } - } else { - // Current key is a DES key, change it to a 3DES key - if (payload->algo == 1) { - cmd[0] = 0x90; - cmd[1] = CHANGE_KEY; - cmd[2] = payload->keyno; + } else { + // Current key is a DES key, change it to a 3DES key + if (payload->algo == 1) { + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = payload->keyno; - uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; + uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; - uint8_t first, second; - uint8_t buff1[8] = {0x00}; - uint8_t buff2[8] = {0x00}; - uint8_t buff3[8] = {0x00}; + uint8_t first, second; + uint8_t buff1[8] = {0x00}; + uint8_t buff2[8] = {0x00}; + uint8_t buff3[8] = {0x00}; - memcpy(buff1,newKey, 8); - memcpy(buff2,newKey + 8, 8); + memcpy(buff1,newKey, 8); + memcpy(buff2,newKey + 8, 8); - compute_crc(CRC_14443_A, newKey, 16, &first, &second); - memcpy(buff3, &first, 1); - memcpy(buff3 + 1, &second, 1); + compute_crc(CRC_14443_A, newKey, 16, &first, &second); + memcpy(buff3, &first, 1); + memcpy(buff3 + 1, &second, 1); - des_dec(&buff1, &buff1, skey->data); - memcpy(cmd+3,buff1,8); + des_dec(&buff1, &buff1, skey->data); + memcpy(cmd+3,buff1,8); - for (int x = 0; x < 8; x++) { - buff2[x] = buff2[x] ^ buff1[x]; + for (int x = 0; x < 8; x++) { + buff2[x] = buff2[x] ^ buff1[x]; + } + des_dec(&buff2, &buff2, skey->data); + memcpy(cmd+11,buff2,8); + + for (int x = 0; x < 8; x++) { + buff3[x] = buff3[x] ^ buff2[x]; + } + des_dec(&buff3, &buff3, skey->data); + memcpy(cmd+19,buff3,8); + + // The command always times out on the first attempt, this will retry until a response + // is recieved. + len = 0; + while(!len) { + len = DesfireAPDU(cmd,27,resp); + } } - des_dec(&buff2, &buff2, skey->data); - memcpy(cmd+11,buff2,8); - - for (int x = 0; x < 8; x++) { - buff3[x] = buff3[x] ^ buff2[x]; - } - des_dec(&buff3, &buff3, skey->data); - memcpy(cmd+19,buff3,8); - - // The command always times out on the first attempt, this will retry until a response - // is recieved. - len = 0; - while(!len) { - len = DesfireAPDU(cmd,27,resp); - } - } - } - */ + } + */ //OnSuccess(); @@ -589,8 +575,8 @@ void MifareDES_Auth1(uint8_t *datain) { } PACKED; struct r rpayload; - rpayload.sessionkeylen=payload->keylen; - memcpy(rpayload.sessionkey,skey->data,rpayload.sessionkeylen); + rpayload.sessionkeylen = payload->keylen; + memcpy(rpayload.sessionkey, skey->data, rpayload.sessionkeylen); reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); LED_B_OFF(); } @@ -681,4 +667,4 @@ void OnError(uint8_t reason) { void OnErrorNG(uint16_t cmd, uint8_t reason) { reply_ng(cmd, reason, NULL, 0); OnSuccess(); -} \ No newline at end of file +} diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index c3989401f..ec44404a8 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -853,18 +853,18 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { int res = get_desfire_select_application(aid); if (res != PM3_SUCCESS) return res; struct { - uint8_t mode; - uint8_t algo; - uint8_t keyno; - uint8_t key[24]; - uint8_t keylen; + uint8_t mode; + uint8_t algo; + uint8_t keyno; + uint8_t key[24]; + uint8_t keylen; } PACKED payload; - payload.keylen=keylen; - memcpy(payload.key,key,keylen); - payload.mode=MFDES_AUTH_PICC; - payload.algo=MFDES_ALGO_DES; - payload.keyno=0; - SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); + payload.keylen = keylen; + memcpy(payload.key, key, keylen); + payload.mode = MFDES_AUTH_PICC; + payload.algo = MFDES_ALGO_DES; + payload.keyno = 0; + SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { @@ -873,23 +873,23 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { return PM3_ETIMEOUT; } - uint8_t isOK = (resp.status==PM3_SUCCESS); + uint8_t isOK = (resp.status == PM3_SUCCESS); if (isOK) { struct { uint8_t flags; uint8_t datalen; uint8_t datain[FRAME_PAYLOAD_SIZE]; } PACKED payload; - payload.datain[0]=0xFC; - payload.flags=NONE; - payload.datalen=1; - SendCommandNG(CMD_HF_DESFIRE_COMMAND,(uint8_t*)&payload,sizeof(payload)); + payload.datain[0] = 0xFC; + payload.flags = NONE; + payload.datalen = 1; + SendCommandNG(CMD_HF_DESFIRE_COMMAND, (uint8_t *)&payload, sizeof(payload)); if (!WaitForResponseTimeout(CMD_HF_DESFIRE_COMMAND, &resp, 3000)) { PrintAndLogEx(WARNING, "Client reset command execute timeout"); DropField(); return PM3_ETIMEOUT; } - if (resp.status==PM3_SUCCESS) { + if (resp.status == PM3_SUCCESS) { /*struct r { uint8_t len; uint8_t data[RECEIVE_SIZE]; @@ -1528,12 +1528,12 @@ static int CmdHF14ADesAuth(const char *Cmd) { uint8_t key[24]; uint8_t keylen; } PACKED payload; - payload.keylen=keylength; - memcpy(payload.key,key,keylength); - payload.mode=cmdAuthMode; - payload.algo=cmdAuthAlgo; - payload.keyno=cmdKeyNo; - SendCommandNG(CMD_HF_DESFIRE_AUTH1,(uint8_t*)&payload,sizeof(payload)); + payload.keylen = keylength; + memcpy(payload.key, key, keylength); + payload.mode = cmdAuthMode; + payload.algo = cmdAuthAlgo; + payload.keyno = cmdKeyNo; + SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; From e0338284c0baea4f6e3a7592ee31b9c9b6515fac Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 23:03:31 +0200 Subject: [PATCH 46/66] Add changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f32ea1497..66fa27ac6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] + - Port 'hf mfdes' Authentification to CommandNG structure, fix auth session key (@bkerler) - Updates `hf mfdes` functions, improved logging and added new commands (@bkerler) - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) From c6323a5fe1e7552ac79faf67ca407428e55c2b64 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Fri, 10 Apr 2020 23:45:54 +0200 Subject: [PATCH 47/66] Fix bad bug. Don't check dest for NULL --- client/cmdhfmfdes.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index d910cb669..1da5bbd20 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -311,10 +311,10 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l PrintAndLogEx(DEBUG, "APDU=NULL"); return PM3_EINVARG; } - if (dest == NULL) { + /*if (dest == NULL) { PrintAndLogEx(DEBUG, "DEST=NULL"); return PM3_EINVARG; - } + }*/ if (sw == NULL) { PrintAndLogEx(DEBUG, "SW=NULL"); return PM3_EINVARG; @@ -675,7 +675,7 @@ static int get_desfire_select_application(uint8_t *aid) { sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t), true); + int res = send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t), true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[0] << 16) + (aid[1] << 8) + aid[2], GetErrorString(res, &sw)); DropField(); From 7fa7eeba97d2ceacf6d6276e23bebcef4149e890 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Sat, 11 Apr 2020 08:21:16 +1000 Subject: [PATCH 48/66] Update settings.c --- client/settings.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/client/settings.c b/client/settings.c index cca0fda00..c3cb02ad6 100644 --- a/client/settings.c +++ b/client/settings.c @@ -155,7 +155,6 @@ void settings_load_callback (json_t *root) { // Logging Level if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { - memset (tempStr,0x00,sizeof(tempStr)); strncpy (tempStr,s1,sizeof(tempStr)-1); str_lower (tempStr); if (strncmp (tempStr,"off",3) == 0) session.client_debug_level = OFF; @@ -175,7 +174,6 @@ void settings_load_callback (json_t *root) { // show options if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { - memset (tempStr,0x00,sizeof(tempStr)); strncpy (tempStr,s1,sizeof(tempStr)-1); str_lower (tempStr); if (strncmp (tempStr,"alias",5) == 0) session.emoji_mode = ALIAS; From 93e4a6697139b63a489637fd5ddea1cd298d5d8e Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 00:31:55 +0200 Subject: [PATCH 49/66] Improve UI handling and fix AID/FID display --- client/cmdhfmfdes.c | 76 ++++++++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 35 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 1da5bbd20..6d8dc5cf0 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -236,7 +236,7 @@ static char *getstatus(uint16_t *sw) { return "Application count is limited to 28, not addition CreateApplication possible"; case MFDES_E_DUPLICATE: - return "Duplicate entry: File/Application does already exist"; + return "Duplicate entry: File/Application/ISO Text does already exist"; case MFDES_E_EEPROM: return "Eeprom error due to loss of power, internal backup/rollback mechanism activated"; @@ -677,7 +677,7 @@ static int get_desfire_select_application(uint8_t *aid) { uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NONE, &recv_len, &sw, sizeof(dfname_t), true); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[0] << 16) + (aid[1] << 8) + aid[2], GetErrorString(res, &sw)); + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[2] << 16) + (aid[1] << 8) + aid[0], GetErrorString(res, &sw)); DropField(); return res; } @@ -868,26 +868,37 @@ int getKeySettings(uint8_t *aid) { return PM3_SUCCESS; } +static void swap24(uint8_t* data){ + if (data==NULL) return; + uint8_t tmp=data[0]; + data[0]=data[2]; + data[2]=tmp; +}; + +static void swap16(uint8_t* data){ + if (data==NULL) return; + uint8_t tmp=data[0]; + data[0]=data[1]; + data[1]=tmp; +}; + static int CmdHF14ADesCreateApp(const char *Cmd) { - clearCommandBuffer(); - CLIParserInit("hf mfdes createaid", "Create Application ID", - "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" + "Usage:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to create"), - arg_strx0("fF", "fid", "", "File ID"), + arg_strx0("aA", "aid", "", "App ID to create as hex bytes ("), + arg_strx0("fF", "fid", "", "File ID to create"), arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), arg_strx0("lL", "keysetting2", "", "Key Setting 2"), arg_str0("nN", "name", "", "App ISO-4 Name"), arg_param_end }; - CLIExecWithReturn(Cmd, argtable, true); + CLIExecWithReturn(Cmd, argtable, false); /* KeySetting 1 (AMK Setting): 0: Allow change master key 1: Free Directory list access without master key @@ -927,7 +938,9 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { int keylen2 = 1; int namelen = 16; CLIGetHexWithReturn(1, aid, &aidlength); + swap24(aid); CLIGetHexWithReturn(2, fid, &fidlength); + swap16(fid); CLIGetHexWithReturn(3, &keysetting1, &keylen1); CLIGetHexWithReturn(4, &keysetting2, &keylen2); CLIGetStrWithReturn(5, name, &namelen); @@ -935,27 +948,27 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { if (aidlength < 3) { PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_EINVARG; + return PM3_SNONCES; } if (fidlength < 2) { PrintAndLogEx(ERR, "FID must have 2 bytes length."); - return PM3_EINVARG; + return PM3_SNONCES; } if (keylen1 < 1) { PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); - return PM3_EINVARG; + return PM3_SNONCES; } if (keylen1 < 1) { PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); - return PM3_EINVARG; + return PM3_SNONCES; } if (namelen > 16) { PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); - return PM3_EINVARG; + return PM3_SNONCES; } //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 @@ -985,8 +998,6 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { } static int CmdHF14ADesDeleteApp(const char *Cmd) { - clearCommandBuffer(); - CLIParserInit("hf mfdes deleteaid", "Delete Application ID", "Usage:\n\t-a aid (3 bytes)\n\n" @@ -998,7 +1009,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { arg_strx0("aA", "aid", "", "App ID to delete"), arg_param_end }; - CLIExecWithReturn(Cmd, argtable, true); + CLIExecWithReturn(Cmd, argtable, false); int aidlength = 3; uint8_t aid[3] = {0}; CLIGetHexWithReturn(1, aid, &aidlength); @@ -1006,7 +1017,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { if (aidlength < 3) { PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_EINVARG; + return PM3_SNONCES; } if (memcmp(aid, "\x00\x00\x00", 3) == 0) { @@ -1022,7 +1033,6 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { static int CmdHF14ADesFormatPICC(const char *Cmd) { - (void) Cmd; // Cmd is not used so far CLIParserInit("hf mfdes formatpicc", "Formats MIFARE DESFire PICC to factory state", "Usage:\n\t-k PICC key (8 bytes)\n\n" @@ -1034,7 +1044,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), arg_param_end }; - CLIExecWithReturn(Cmd, argtable, true); + CLIExecWithReturn(Cmd, argtable, false); uint8_t key[8] = {0}; int keylen = 8; @@ -1043,11 +1053,9 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { if ((keylen < 8) || (keylen > 8)) { PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); - //SetAPDULogging(false); - return PM3_EINVARG; + return PM3_SNONCES; } - clearCommandBuffer(); DropField(); uint8_t aid[3] = {0}; int res = get_desfire_select_application(aid); @@ -1402,10 +1410,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); } - PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X %02X %02X"), aid[0], aid[1], aid[2]); + PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]); for (int m = 0; m < dfname_count; m++) { if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { - PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X %02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[0], dfnames[m].fid[1], dfnames[m].name); + PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X%02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[1], dfnames[m].fid[0], dfnames[m].name); } } @@ -1467,7 +1475,6 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { static int CmdHF14ADesAuth(const char *Cmd) { int res = 0; DropField(); - clearCommandBuffer(); // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 @@ -1491,7 +1498,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), arg_param_end }; - CLIExecWithReturn(Cmd, argtable, true); + CLIExecWithReturn(Cmd, argtable, false); uint8_t cmdAuthMode = arg_get_int_def(1, 0); uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); @@ -1509,37 +1516,37 @@ static int CmdHF14ADesAuth(const char *Cmd) { if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); - return PM3_EINVARG; + return PM3_SNONCES; } // AID if (aidlength != 3) { PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + return PM3_SNONCES; } switch (cmdAuthMode) { case 1: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - return PM3_EINVARG; + return PM3_SNONCES; } break; case 2: if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - return PM3_EINVARG; + return PM3_SNONCES; } break; case 3: if (cmdAuthAlgo != 4) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); - return PM3_EINVARG; + return PM3_SNONCES; } break; default: PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - return PM3_EINVARG; + return PM3_SNONCES; } switch (cmdAuthAlgo) { @@ -1565,7 +1572,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { // KEY if (keylen != keylength) { PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); - return PM3_EINVARG; + return PM3_SNONCES; } @@ -1646,7 +1653,6 @@ static int CmdHelp(const char *Cmd) { } int CmdHFMFDes(const char *Cmd) { - // flush clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } From 327d8a8bfe2742fca14bd59bdf051bc15ea67c8e Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 01:38:47 +0200 Subject: [PATCH 50/66] Further aid and auth info fixes --- client/cmdhfmfdes.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 6d8dc5cf0..0c7f6b621 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -1493,7 +1493,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { arg_param_begin, arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), - arg_strx0("aA", "aid", "", "AID used for authentification"), + arg_strx0("aA", "aid", "", "AID used for authentification (HEX 3 bytes)"), arg_int0("nN", "keyno", "Key number used for authentification", NULL), arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), arg_param_end @@ -1506,7 +1506,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { int aidlength = 3; uint8_t aid[3] = {0}; CLIGetHexWithReturn(3, aid, &aidlength); - + swap16(aid); uint8_t cmdKeyNo = arg_get_int_def(4, 0); uint8_t key[24] = {0}; @@ -1643,6 +1643,18 @@ static command_t CommandTable[] = { {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, +/* + ISO/IEC 7816 Cmds + 'A4' Select + 'B0' Read Binary + 'D6' Update Binary + 'B2' Read Records + 'E2' Append Records + '84' Get Challenge + '88' Internal Authenticate + '82' External Authenticate + +*/ {NULL, NULL, NULL, NULL} }; From fceae52e68433a36b4e2809808d951971da71624 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 01:39:24 +0200 Subject: [PATCH 51/66] Add 3K3 basic support --- armsrc/des.c | 100 ++++++++++++++++++++++++++++++++++++++------------- armsrc/des.h | 2 ++ 2 files changed, 78 insertions(+), 24 deletions(-) diff --git a/armsrc/des.c b/armsrc/des.c index ccd32be7d..af10423f3 100644 --- a/armsrc/des.c +++ b/armsrc/des.c @@ -388,30 +388,6 @@ void tdes_dec(void *out, void *in, const uint8_t *key) { des_dec(out, out, (uint8_t *)key + 0); } -void tdes_2key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) { - - if (length % 8) return; - - uint8_t i; - uint8_t *tin = (uint8_t *) in; - uint8_t *tout = (uint8_t *) out; - - while (length > 0) { - for (i = 0; i < 8; i++) - tout[i] = (unsigned char)(tin[i] ^ iv[i]); - - des_enc(tout, tin, (uint8_t *)key + 0); - des_dec(tout, tout, (uint8_t *)key + 8); - des_enc(tout, tout, (uint8_t *)key + 0); - - memcpy(iv, tout, 8); - - tin += 8; - tout += 8; - length -= 8; - } -} - void tdes_2key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) { if (length % 8) return; @@ -439,6 +415,82 @@ void tdes_2key_dec(void *out, const void *in, size_t length, const void *key, un } } +void tdes_2key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) { + + if (length % 8) return; + + uint8_t i; + uint8_t *tin = (uint8_t *) in; + uint8_t *tout = (uint8_t *) out; + + while (length > 0) { + for (i = 0; i < 8; i++) + tout[i] = (unsigned char)(tin[i] ^ iv[i]); + + des_enc(tout, tin, (uint8_t *)key + 0); + des_dec(tout, tout, (uint8_t *)key + 8); + des_enc(tout, tout, (uint8_t *)key + 0); + + memcpy(iv, tout, 8); + + tin += 8; + tout += 8; + length -= 8; + } +} + +void tdes_3key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) { + + if (length % 8) return; + + uint8_t i; + uint8_t *tin = (uint8_t *) in; + uint8_t *tout = (uint8_t *) out; + + while (length > 0) { + for (i = 0; i < 8; i++) + tout[i] = (unsigned char)(tin[i] ^ iv[i]); + + des_enc(tout, tin, (uint8_t *)key + 0); + des_dec(tout, tout, (uint8_t *)key + 8); + des_enc(tout, tout, (uint8_t *)key + 16); + + memcpy(iv, tout, 8); + + tin += 8; + tout += 8; + length -= 8; + } +} + +void tdes_3key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]) { + + if (length % 8) return; + + uint8_t i; + unsigned char temp[8]; + uint8_t *tin = (uint8_t *) in; + uint8_t *tout = (uint8_t *) out; + + while (length > 0) { + memcpy(temp, tin, 8); + + des_dec(tout, tin, (uint8_t *)key + 0); + des_enc(tout, tout, (uint8_t *)key + 8); + des_dec(tout, tout, (uint8_t *)key + 16); + + for (i = 0; i < 8; i++) + tout[i] = (unsigned char)(tout[i] ^ iv[i]); + + memcpy(iv, temp, 8); + + tin += 8; + tout += 8; + length -= 8; + } +} + + /******************************************************************************/ diff --git a/armsrc/des.h b/armsrc/des.h index 8cf41b8ae..1a0549606 100644 --- a/armsrc/des.h +++ b/armsrc/des.h @@ -104,6 +104,8 @@ void tdes_dec(void *out, void *in, const uint8_t *key); void tdes_2key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]); void tdes_2key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]); +void tdes_3key_enc(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]); +void tdes_3key_dec(void *out, const void *in, size_t length, const void *key, unsigned char iv[8]); // Copied from des.h in desfire imp. typedef unsigned long DES_KS[16][2]; /* Single-key DES key schedule */ From 9b26fab1c2926335a5ea92e8cdb0d1e511c536f4 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 01:41:39 +0200 Subject: [PATCH 52/66] Further auth info fixes --- client/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 0c7f6b621..51acf8a5e 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -1491,7 +1491,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { void *argtable[] = { arg_param_begin, - arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes)", NULL), + arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)", NULL), arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), arg_strx0("aA", "aid", "", "AID used for authentification (HEX 3 bytes)"), arg_int0("nN", "keyno", "Key number used for authentification", NULL), From 4c2f98ac3d87574afc27f75fc35f2c19754df729 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 02:32:55 +0200 Subject: [PATCH 53/66] Add first 3K3 support. Improve algo error handling --- armsrc/mifaredesfire.c | 65 ++++++++++++++++++++++++-------- client/cmdhfmfdes.c | 84 +++++++++++++++++++++--------------------- 2 files changed, 92 insertions(+), 57 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index af902e868..3543bcc3a 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -132,7 +132,7 @@ void MifareDesfireGetInformation() { clear_trace(); set_tracing(true); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + // reset the pcb_blocknum, pcb_blocknum = 0; @@ -259,6 +259,7 @@ void MifareDES_Auth1(uint8_t *datain) { // Default Keys uint8_t PICC_MASTER_KEY8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t PICC_MASTER_KEY24[24] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //uint8_t null_key_data16[16] = {0x00}; //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; @@ -272,10 +273,12 @@ void MifareDES_Auth1(uint8_t *datain) { LED_C_OFF(); if (payload->key == NULL) { - if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { + if (payload->algo == MFDES_AUTH_DES) { memcpy(keybytes, PICC_MASTER_KEY8, 8); - } else if (payload->mode == MFDES_AUTH_AES) { + } else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) { memcpy(keybytes, PICC_MASTER_KEY16, 16); + } else if (payload->algo == MFDES_ALGO_3DES) { + memcpy(keybytes, PICC_MASTER_KEY24, 24); } } else { memcpy(keybytes, payload->key, payload->keylen); @@ -334,6 +337,20 @@ void MifareDES_Auth1(uint8_t *datain) { return; } + int expectedlen = 1 + 8 + 2 + 2; + if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { + expectedlen = 1 + 16 + 2 + 2; + } + + if (len != expectedlen) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Length of answer doesn't match algo."); + print_result("Res-Buffer: ", resp, len); + } + OnErrorNG(CMD_HF_DESFIRE_AUTH1, 3); + return; + } + // Part 2 if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndB, resp + 1, payload->keylen); @@ -355,6 +372,8 @@ void MifareDES_Auth1(uint8_t *datain) { tdes_dec(&RndB, &encRndB, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&RndB, &encRndB, key->data); + else if (payload->algo == MFDES_ALGO_3K3DES) + tdes_3key_dec(&RndB, &encRndB, 16, key->data, IV); // - Rotate RndB by 8 bits memcpy(rotRndB, RndB, payload->keylen); @@ -363,25 +382,35 @@ void MifareDES_Auth1(uint8_t *datain) { uint8_t encRndA[16] = {0x00}; // - Encrypt our response - if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { - if (payload->algo == MFDES_ALGO_3DES) + if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_ISO || payload->mode == MFDES_AUTH_PICC) { + if (payload->algo == MFDES_ALGO_3DES) { tdes_dec(&encRndA, &RndA, key->data); - else if (payload->algo == MFDES_ALGO_DES) + memcpy(both, encRndA, 8); + } else if (payload->algo == MFDES_ALGO_DES) { des_dec(&encRndA, &RndA, key->data); + memcpy(both, encRndA, 8); + } else if (payload->algo == MFDES_ALGO_3K3DES) { + tdes_3key_dec(&encRndA, &RndA, 16, key->data, IV); + memcpy(both, encRndA, 16); + } - memcpy(both, encRndA, 8); for (int x = 0; x < 8; x++) { rotRndB[x] = rotRndB[x] ^ encRndA[x]; } - if (payload->algo == MFDES_ALGO_3DES) + if (payload->algo == MFDES_ALGO_3DES) { tdes_dec(&encRndB, &rotRndB, key->data); - else if (payload->algo == MFDES_ALGO_DES) + memcpy(both + 8, encRndB, 8); + } else if (payload->algo == MFDES_ALGO_DES) { des_dec(&encRndB, &rotRndB, key->data); + memcpy(both + 8, encRndB, 8); + } else if (payload->algo == MFDES_ALGO_3K3DES) { + tdes_3key_dec(&encRndB, &rotRndB, 16, key->data, IV); + memcpy(both + 16, encRndB, 16); + } - memcpy(both + 8, encRndB, 8); - } else if (payload->mode == MFDES_AUTH_AES || payload->mode == MFDES_AUTH_ISO) { + } else if (payload->mode == MFDES_AUTH_AES) { uint8_t tmp[32] = {0x00}; memcpy(tmp, RndA, 16); memcpy(tmp + 16, rotRndB, 16); @@ -397,15 +426,19 @@ void MifareDES_Auth1(uint8_t *datain) { } } + int bothlen = 16; + if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { + bothlen = 32; + } if (payload->mode != MFDES_AUTH_PICC) { cmd[0] = 0x90; cmd[1] = ADDITIONAL_FRAME; cmd[2] = 0x00; cmd[3] = 0x00; - cmd[4] = (payload->keylen * 2); - memcpy(cmd + 5, both, payload->keylen * 2); - cmd[(payload->keylen * 2) + 5] = 0x0; - len = DesfireAPDU(cmd, 5 + (payload->keylen * 2) + 1, resp); + cmd[4] = bothlen; + memcpy(cmd + 5, both, bothlen); + cmd[bothlen + 5] = 0x0; + len = DesfireAPDU(cmd, 5 + bothlen + 1, resp); } else { cmd[0] = ADDITIONAL_FRAME; memcpy(cmd + 1, both, 16); @@ -452,6 +485,8 @@ void MifareDES_Auth1(uint8_t *datain) { tdes_dec(&encRndA, &encRndA, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&encRndA, &encRndA, key->data); + else if (payload->algo == MFDES_ALGO_3K3DES) + tdes_3key_dec(&encRndA, &encRndA, 16, key->data, IV); } else if (payload->mode == MFDES_AUTH_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { if (DBGLEVEL >= DBG_EXTENDED) { diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 51acf8a5e..d43c2a654 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -92,13 +92,13 @@ static char *getCardSizeStr(uint8_t fsize) { static char *getProtocolStr(uint8_t id, bool hw) { - static char buf[50] = {0x00}; + static char buf[50] = {0x00}; char *retStr = buf; if (id == 0x04) { sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3 MIFARE, 14443-4") ")", id); } else if (id == 0x05) { - if (hw) + if (hw) sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-2, 14443-3") ")", id); else sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); @@ -308,7 +308,7 @@ static char *GetErrorString(int res, uint16_t *sw) { static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize, bool readalldata) { if (apdu == NULL) { - PrintAndLogEx(DEBUG, "APDU=NULL"); + PrintAndLogEx(DEBUG, "APDU=NULL"); return PM3_EINVARG; } /*if (dest == NULL) { @@ -362,7 +362,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); return res; } - + if (dest != NULL) { if (splitbysize) { memcpy(&dest[i * splitbysize], data, resplen); @@ -376,7 +376,7 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l if (*sw != status(MFDES_ADDITIONAL_FRAME)) break; } - *recv_len = (splitbysize) ? i : pos; + *recv_len = (splitbysize) ? i : pos; return PM3_SUCCESS; } @@ -392,7 +392,7 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { // return DESFIRE_EV3; if (major == 0x30 && minor == 0x00) return DESFIRE_LIGHT; - if (major == 0x11 && minor == 0x00 ) + if (major == 0x11 && minor == 0x00) return PLUS_EV1; return UNKNOWN; @@ -442,12 +442,12 @@ static int get_desfire_freemem(uint32_t *free_mem) { int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); - if (res != PM3_SUCCESS ) + if (res != PM3_SUCCESS) return res; - + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; - + *free_mem = le24toh(fmem); return res; } @@ -587,7 +587,7 @@ static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { uint8_t data[2] = {0}; int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0, true); - if (res != PM3_SUCCESS ) + if (res != PM3_SUCCESS) return res; if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; @@ -612,8 +612,8 @@ static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); - - if (res != PM3_SUCCESS ) + + if (res != PM3_SUCCESS) return res; if (sw != status(MFDES_S_OPERATION_OK)) @@ -625,8 +625,8 @@ static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { // --- GET APPIDS static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { if (dest == NULL) { - PrintAndLogEx(DEBUG, "DEST=NULL"); - return PM3_EINVARG; + PrintAndLogEx(DEBUG, "DEST=NULL"); + return PM3_EINVARG; } if (app_ids_len == NULL) { PrintAndLogEx(DEBUG, "APP_IDS_LEN=NULL"); @@ -637,8 +637,8 @@ static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); - - if (res != PM3_SUCCESS ) + + if (res != PM3_SUCCESS) return res; if (sw != status(MFDES_S_OPERATION_OK)) @@ -868,18 +868,18 @@ int getKeySettings(uint8_t *aid) { return PM3_SUCCESS; } -static void swap24(uint8_t* data){ - if (data==NULL) return; - uint8_t tmp=data[0]; - data[0]=data[2]; - data[2]=tmp; +static void swap24(uint8_t *data) { + if (data == NULL) return; + uint8_t tmp = data[0]; + data[0] = data[2]; + data[2] = tmp; }; -static void swap16(uint8_t* data){ - if (data==NULL) return; - uint8_t tmp=data[0]; - data[0]=data[1]; - data[1]=tmp; +static void swap16(uint8_t *data) { + if (data == NULL) return; + uint8_t tmp = data[0]; + data[0] = data[1]; + data[1] = tmp; }; @@ -1151,7 +1151,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { } return PM3_ESOFT; } - + nxp_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); if (cardtype == PLUS_EV1) { PrintAndLogEx(INFO, "Card seems to be MIFARE Plus EV1. Try " _YELLOW_("`hf mfp info`")); @@ -1209,7 +1209,7 @@ static int CmdHF14ADesInfo(const char *Cmd) { size_t signature_len = 0; PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) { desfire_print_signature(package->uid, signature, signature_len, cardtype); } else { @@ -1322,7 +1322,7 @@ static void DecodeAccessRights(uint16_t accrights) { char *rwa = DecodeAccessValue(read_write_access); if (rwa == NULL) return; - + char *wa = DecodeAccessValue(write_access); if (wa == NULL) return; @@ -1515,7 +1515,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParserFree(); if ((keylen < 8) || (keylen > 24)) { - PrintAndLogEx(ERR, "Specified key must have 16 bytes length."); + PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); return PM3_SNONCES; } @@ -1621,7 +1621,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); } else { - PrintAndLogEx(WARNING, _RED_("Client command failed, reason: %d."), resp.status); + PrintAndLogEx(WARNING, _RED_("Auth command failed, reason: %d."), resp.status); } PrintAndLogEx(INFO, "-------------------------------------------------------------"); return PM3_SUCCESS; @@ -1643,18 +1643,18 @@ static command_t CommandTable[] = { {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, -/* - ISO/IEC 7816 Cmds - 'A4' Select - 'B0' Read Binary - 'D6' Update Binary - 'B2' Read Records - 'E2' Append Records - '84' Get Challenge - '88' Internal Authenticate - '82' External Authenticate + /* + ISO/IEC 7816 Cmds + 'A4' Select + 'B0' Read Binary + 'D6' Update Binary + 'B2' Read Records + 'E2' Append Records + '84' Get Challenge + '88' Internal Authenticate + '82' External Authenticate -*/ + */ {NULL, NULL, NULL, NULL} }; From 37aa19ad6c1b6cac1f417ee11df09d820edc80f0 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 02:56:08 +0200 Subject: [PATCH 54/66] Add 2k3 des iso support preparation --- armsrc/desfire.h | 3 ++- armsrc/desfire_key.c | 15 ++++++++++++++ armsrc/desfire_key.h | 1 + client/cmdhfmfdes.c | 47 +++++++++++++++++++++++++++----------------- 4 files changed, 47 insertions(+), 19 deletions(-) diff --git a/armsrc/desfire.h b/armsrc/desfire.h index e753106e7..507bda424 100644 --- a/armsrc/desfire.h +++ b/armsrc/desfire.h @@ -61,7 +61,8 @@ enum DESFIRE_CRYPTOALGO { T_DES = 0x00, T_3DES = 0x01, T_3K3DES = 0x02, - T_AES = 0x03 + T_AES = 0x03, + T_2K3DES = 0x04 }; diff --git a/armsrc/desfire_key.c b/armsrc/desfire_key.c index 272f18562..d9db46efa 100644 --- a/armsrc/desfire_key.c +++ b/armsrc/desfire_key.c @@ -74,6 +74,14 @@ void Desfire_3k3des_key_new(const uint8_t value[24], desfirekey_t key) { Desfire_3k3des_key_new_with_version(data, key); } +void Desfire_2k3des_key_new_with_version(const uint8_t value[16], desfirekey_t key) { + if (key != NULL) { + key->type = T_2K3DES; + memcpy(key->data, value, 16); + update_key_schedules(key); + } +} + void Desfire_3k3des_key_new_with_version(const uint8_t value[24], desfirekey_t key) { if (key != NULL) { key->type = T_3K3DES; @@ -136,6 +144,13 @@ void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfire memcpy(buffer + 12, rndb + 4, 4); Desfire_3des_key_new_with_version(buffer, key); break; + case T_2K3DES: + memcpy(buffer, rnda, 4); + memcpy(buffer + 4, rndb, 4); + memcpy(buffer + 8, rnda + 4, 4); + memcpy(buffer + 12, rndb + 4, 4); + Desfire_3des_key_new_with_version(buffer, key); + break; case T_3K3DES: memcpy(buffer, rnda, 4); memcpy(buffer + 4, rndb, 4); diff --git a/armsrc/desfire_key.h b/armsrc/desfire_key.h index 603fd5663..286d47178 100644 --- a/armsrc/desfire_key.h +++ b/armsrc/desfire_key.h @@ -9,6 +9,7 @@ void Desfire_des_key_new_with_version(const uint8_t value[8], desfirekey_t key); void Desfire_3des_key_new_with_version(const uint8_t value[16], desfirekey_t key); void Desfire_3k3des_key_new(const uint8_t value[24], desfirekey_t key); void Desfire_3k3des_key_new_with_version(const uint8_t value[24], desfirekey_t key); +void Desfire_2k3des_key_new_with_version(const uint8_t value[16], desfirekey_t key); void Desfire_aes_key_new(const uint8_t value[16], desfirekey_t key); void Desfire_aes_key_new_with_version(const uint8_t value[16], uint8_t version, desfirekey_t key); uint8_t Desfire_key_get_version(desfirekey_t key); diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index d43c2a654..afbb0634e 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -46,8 +46,9 @@ typedef enum { typedef enum { MFDES_ALGO_DES = 1, MFDES_ALGO_3DES = 2, - MFDES_ALGO_3K3DES = 3, - MFDES_ALGO_AES = 4 + MFDES_ALGO_2K3DES = 3, + MFDES_ALGO_3K3DES = 4, + MFDES_ALGO_AES = 5 } mifare_des_authalgo_t; typedef enum { @@ -1485,14 +1486,14 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParserInit("hf mfdes auth", "Authenticates Mifare DESFire using Key", - "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes auth -m 3 -t 4 -a 018380 -n 0 -k 404142434445464748494a4b4c4d4e4f\n" + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=2K3DES, 4=3K3DES, 5=AES)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes auth -m 3 -t 5 -a 018380 -n 0 -k 00000000000000000000000000000000\n" ); void *argtable[] = { arg_param_begin, arg_int0("mM", "type", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)", NULL), - arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)", NULL), + arg_int0("tT", "algo", "Crypt algo (1=DES, 2=3DES, 3=2K3DES, 4=3K3DES, 5=AES)", NULL), arg_strx0("aA", "aid", "", "AID used for authentification (HEX 3 bytes)"), arg_int0("nN", "keyno", "Key number used for authentification", NULL), arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), @@ -1526,21 +1527,27 @@ static int CmdHF14ADesAuth(const char *Cmd) { } switch (cmdAuthMode) { - case 1: - if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + case MFDES_AUTH_DES: + if (cmdAuthAlgo != MFDES_ALGO_DES && cmdAuthAlgo != MFDES_ALGO_3DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth des mode"); return PM3_SNONCES; } break; - case 2: - if (cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + case MFDES_AUTH_ISO: + if (cmdAuthAlgo != MFDES_ALGO_2K3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); return PM3_SNONCES; } break; - case 3: - if (cmdAuthAlgo != 4) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); + case MFDES_AUTH_AES: + if (cmdAuthAlgo != MFDES_ALGO_AES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth aes mode"); + return PM3_SNONCES; + } + break; + case MFDES_AUTH_PICC: + if (cmdAuthAlgo != MFDES_AUTH_DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); return PM3_SNONCES; } break; @@ -1550,20 +1557,24 @@ static int CmdHF14ADesAuth(const char *Cmd) { } switch (cmdAuthAlgo) { - case 2: + case MFDES_ALGO_2K3DES: + keylength = 16; + PrintAndLogEx(NORMAL, "2 key 3DES selected"); + break; + case MFDES_ALGO_3DES: keylength = 16; PrintAndLogEx(NORMAL, "3DES selected"); break; - case 3: + case MFDES_ALGO_3K3DES: keylength = 24; PrintAndLogEx(NORMAL, "3 key 3DES selected"); break; - case 4: + case MFDES_ALGO_AES: keylength = 16; PrintAndLogEx(NORMAL, "AES selected"); break; default: - cmdAuthAlgo = 1; + cmdAuthAlgo = MFDES_ALGO_DES; keylength = 8; PrintAndLogEx(NORMAL, "DES selected"); break; From 6afc8d39a495ed3140d6f0b964ce4f91f8c07cc9 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 02:56:48 +0200 Subject: [PATCH 55/66] Add 2k3 des iso support preparation --- armsrc/mifaredesfire.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 3543bcc3a..a1da5643d 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -213,8 +213,9 @@ typedef enum { typedef enum { MFDES_ALGO_DES = 1, MFDES_ALGO_3DES = 2, - MFDES_ALGO_3K3DES = 3, - MFDES_ALGO_AES = 4 + MFDES_ALGO_2K3DES = 3, + MFDES_ALGO_3K3DES = 4, + MFDES_ALGO_AES = 5 } mifare_des_authalgo_t; void MifareDES_Auth1(uint8_t *datain) { @@ -273,9 +274,9 @@ void MifareDES_Auth1(uint8_t *datain) { LED_C_OFF(); if (payload->key == NULL) { - if (payload->algo == MFDES_AUTH_DES) { + if (payload->algo == MFDES_AUTH_DES) { memcpy(keybytes, PICC_MASTER_KEY8, 8); - } else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) { + } else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES || payload->algo == MFDES_ALGO_2K3DES) { memcpy(keybytes, PICC_MASTER_KEY16, 16); } else if (payload->algo == MFDES_ALGO_3DES) { memcpy(keybytes, PICC_MASTER_KEY24, 24); @@ -291,11 +292,11 @@ void MifareDES_Auth1(uint8_t *datain) { mbedtls_aes_init(&ctx); Desfire_aes_key_new(keybytes, key); } else if (payload->algo == MFDES_ALGO_3DES) { - key->type = T_3DES; Desfire_3des_key_new_with_version(keybytes, key); } else if (payload->algo == MFDES_ALGO_DES) { - key->type = T_DES; Desfire_des_key_new(keybytes, key); + } else if (payload->algo == MFDES_ALGO_2K3DES) { + Desfire_2k3des_key_new_with_version(keybytes, key); } else if (payload->algo == MFDES_ALGO_3K3DES) { Desfire_3k3des_key_new_with_version(keybytes, key); } @@ -372,6 +373,8 @@ void MifareDES_Auth1(uint8_t *datain) { tdes_dec(&RndB, &encRndB, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&RndB, &encRndB, key->data); + else if (payload->algo == MFDES_ALGO_2K3DES) + tdes_2key_dec(&RndB, &encRndB, 8, key->data, IV); else if (payload->algo == MFDES_ALGO_3K3DES) tdes_3key_dec(&RndB, &encRndB, 16, key->data, IV); @@ -389,6 +392,9 @@ void MifareDES_Auth1(uint8_t *datain) { } else if (payload->algo == MFDES_ALGO_DES) { des_dec(&encRndA, &RndA, key->data); memcpy(both, encRndA, 8); + } else if (payload->algo == MFDES_ALGO_2K3DES) { + tdes_2key_dec(&encRndA, &RndA, 8, key->data, IV); + memcpy(both, encRndA, 8); } else if (payload->algo == MFDES_ALGO_3K3DES) { tdes_3key_dec(&encRndA, &RndA, 16, key->data, IV); memcpy(both, encRndA, 16); @@ -405,6 +411,9 @@ void MifareDES_Auth1(uint8_t *datain) { } else if (payload->algo == MFDES_ALGO_DES) { des_dec(&encRndB, &rotRndB, key->data); memcpy(both + 8, encRndB, 8); + } else if (payload->algo == MFDES_ALGO_2K3DES) { + tdes_2key_dec(&encRndB, &rotRndB, 8, key->data, IV); + memcpy(both + 8, encRndB, 8); } else if (payload->algo == MFDES_ALGO_3K3DES) { tdes_3key_dec(&encRndB, &rotRndB, 16, key->data, IV); memcpy(both + 16, encRndB, 16); @@ -485,6 +494,8 @@ void MifareDES_Auth1(uint8_t *datain) { tdes_dec(&encRndA, &encRndA, key->data); else if (payload->algo == MFDES_ALGO_DES) des_dec(&encRndA, &encRndA, key->data); + else if (payload->algo == MFDES_ALGO_2K3DES) + tdes_2key_dec(&encRndA, &encRndA, 8, key->data, IV); else if (payload->algo == MFDES_ALGO_3K3DES) tdes_3key_dec(&encRndA, &encRndA, 16, key->data, IV); } else if (payload->mode == MFDES_AUTH_AES) { From 63c7710976da3c8c29903436eea25bd8038ccb12 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 03:05:46 +0200 Subject: [PATCH 56/66] Fix 2k3 key handling --- armsrc/desfire_key.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/armsrc/desfire_key.c b/armsrc/desfire_key.c index d9db46efa..3bab33f50 100644 --- a/armsrc/desfire_key.c +++ b/armsrc/desfire_key.c @@ -147,9 +147,9 @@ void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfire case T_2K3DES: memcpy(buffer, rnda, 4); memcpy(buffer + 4, rndb, 4); - memcpy(buffer + 8, rnda + 4, 4); - memcpy(buffer + 12, rndb + 4, 4); - Desfire_3des_key_new_with_version(buffer, key); + memcpy(buffer + 8, rnda+4, 4); + memcpy(buffer + 12, rndb+4, 4); + Desfire_2k3des_key_new_with_version(buffer, key); break; case T_3K3DES: memcpy(buffer, rnda, 4); From f71e7438f7a23a9fa741b03f3300f7787ab6ae24 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 03:10:02 +0200 Subject: [PATCH 57/66] Improve DecodeFileSettings log --- client/cmdhfmfdes.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index afbb0634e..17ff33410 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -1359,6 +1359,15 @@ static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) { DecodeAccessRights(accrights); PrintAndLogEx(INFO, " Lower limit: %d - Upper limit: %d - limited credit value: %d - limited credit enabled: %d", lowerlimit, upperlimit, limitcredvalue, limited_credit_enabled); return PM3_SUCCESS; + } else if (src_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { + int recordsize = (src[7] << 16) + (src[6] << 8) + src[5]; + int maxrecords = (src[10] << 16) + (src[9] << 8) + src[8]; + int currentrecord = (src[13] << 16) + (src[12] << 8) + src[11]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Record size: %d - MaxNumberRecords: %d - Current Number Records: %d", recordsize, maxrecords, currentrecord); + return PM3_SUCCESS; } return PM3_ESOFT; } From 1900f6b16a822057dbce49a73678856f53ca4934 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Sat, 11 Apr 2020 17:26:43 +1000 Subject: [PATCH 58/66] Overlay --- client/proxguiqt.cpp | 12 ++++++++---- client/proxmark3.c | 2 +- client/settings.c | 20 ++++++++++++++++++++ client/ui.h | 4 ++++ 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index dd5fd3f24..4e2c9299f 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -210,10 +210,14 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { // shows plot window on the screen. show(); - // Move controller widget below plot - controlWidget->move(x(), y() + frameSize().height()); - controlWidget->resize(size().width(), 200); - + if (session.settings_loaded) + controlWidget->setGeometry (session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_wsize,session.window_overlay_hsize); + else { + // Move controller widget below plot + controlWidget->move(x(), y() + frameSize().height()); + controlWidget->resize(size().width(), 200); + } + // Olverlays / slider window title QString ct = QString("[*]Slider [ %1 ]").arg((char *)gui_serial_port_name); controlWidget->setWindowTitle(ct); diff --git a/client/proxmark3.c b/client/proxmark3.c index 4d36c490b..c5176dd64 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -30,7 +30,7 @@ #include "settings.h" // Used to enable/disable use of settings json file -// #define USE_SETTING_FILE +#define USE_SETTING_FILE static void showBanner(void) { diff --git a/client/settings.c b/client/settings.c index c3cb02ad6..4d59382e2 100644 --- a/client/settings.c +++ b/client/settings.c @@ -64,6 +64,10 @@ int settings_load (void) { session.window_plot_ypos = 30; session.window_plot_hsize = 400; session.window_plot_wsize = 800; + session.window_overlay_xpos = session.window_plot_xpos; + session.window_overlay_ypos = 20+session.window_plot_ypos + session.window_plot_hsize; + session.window_overlay_hsize = 200; + session.window_overlay_wsize = session.window_plot_wsize; session.emoji_mode = ALIAS; session.show_hints = false; session.supports_colors = false; @@ -131,6 +135,12 @@ void settings_save_callback (json_t *root) { JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); + // Overlay/Slider window + JsonSaveInt (root,"window.overlay.xpos",session.window_overlay_xpos); + JsonSaveInt (root,"window.overlay.ypos",session.window_overlay_ypos); + JsonSaveInt (root,"window.overlay.hsize",session.window_overlay_hsize); + JsonSaveInt (root,"window.overlay.wsize",session.window_overlay_wsize); + // Emoji switch (session.emoji_mode) { case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; @@ -172,6 +182,16 @@ void settings_load_callback (json_t *root) { if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) session.window_plot_wsize = i1; + // overlay/slider plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.xpos",&i1) == 0) + session.window_overlay_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.ypos",&i1) == 0) + session.window_overlay_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.hsize",&i1) == 0) + session.window_overlay_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.wsize",&i1) == 0) + session.window_overlay_wsize = i1; + // show options if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { strncpy (tempStr,s1,sizeof(tempStr)-1); diff --git a/client/ui.h b/client/ui.h index 343b55c1f..e5048e751 100644 --- a/client/ui.h +++ b/client/ui.h @@ -34,6 +34,10 @@ typedef struct { int window_plot_ypos; int window_plot_hsize; int window_plot_wsize; + int window_overlay_xpos; + int window_overlay_ypos; + int window_overlay_hsize; + int window_overlay_wsize; clientdebugLevel_t client_debug_level; } session_arg_t; From 637103224da0ebda1b5165507c232cae97c9ddec Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 11:32:31 +0200 Subject: [PATCH 59/66] Fixes --- armsrc/desfire_key.c | 5 ++- armsrc/mifaredesfire.c | 80 ++++++++++++++++--------------------- client/cmdhfmfdes.c | 89 +++++++++++++++++------------------------- include/mifare.h | 16 ++++++++ 4 files changed, 88 insertions(+), 102 deletions(-) diff --git a/armsrc/desfire_key.c b/armsrc/desfire_key.c index 3bab33f50..60219260a 100644 --- a/armsrc/desfire_key.c +++ b/armsrc/desfire_key.c @@ -19,6 +19,7 @@ #include "desfire_key.h" #include "string.h" +#include "dbprint.h" static inline void update_key_schedules(desfirekey_t key); @@ -147,8 +148,8 @@ void Desfire_session_key_new(const uint8_t rnda[], const uint8_t rndb[], desfire case T_2K3DES: memcpy(buffer, rnda, 4); memcpy(buffer + 4, rndb, 4); - memcpy(buffer + 8, rnda+4, 4); - memcpy(buffer + 12, rndb+4, 4); + memcpy(buffer + 8, rnda + 4, 4); + memcpy(buffer + 12, rndb + 4, 4); Desfire_2k3des_key_new_with_version(buffer, key); break; case T_3K3DES: diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index a1da5643d..10a7a3204 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -52,6 +52,11 @@ bool InitDesfireCard() { return true; } +typedef struct { + uint8_t len; + uint8_t data[RECEIVE_SIZE]; +} cmdres_t; + void MifareSendCommand(uint8_t *datain) { struct p { uint8_t flags; @@ -92,15 +97,12 @@ void MifareSendCommand(uint8_t *datain) { //reply_mix(CMD_ACK, 1, len, 0, resp, len); LED_B_ON(); - struct r { - uint8_t len; - uint8_t data[RECEIVE_SIZE]; - } PACKED; - struct r rpayload; + + cmdres_t rpayload; rpayload.len = len; memcpy(rpayload.data, resp, rpayload.len); - reply_ng(CMD_HF_DESFIRE_COMMAND, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); + reply_ng(CMD_HF_DESFIRE_COMMAND, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(rpayload)); LED_B_OFF(); } @@ -203,20 +205,10 @@ void MifareDesfireGetInformation() { OnSuccess(); } -typedef enum { - MFDES_AUTH_DES = 1, - MFDES_AUTH_ISO = 2, - MFDES_AUTH_AES = 3, - MFDES_AUTH_PICC = 4 -} mifare_des_authmode_t; - -typedef enum { - MFDES_ALGO_DES = 1, - MFDES_ALGO_3DES = 2, - MFDES_ALGO_2K3DES = 3, - MFDES_ALGO_3K3DES = 4, - MFDES_ALGO_AES = 5 -} mifare_des_authalgo_t; +typedef struct { + uint8_t sessionkeylen; + uint8_t sessionkey[24]; +} authres_t; void MifareDES_Auth1(uint8_t *datain) { int len = 0; @@ -224,8 +216,8 @@ void MifareDES_Auth1(uint8_t *datain) { uint8_t mode; uint8_t algo; uint8_t keyno; - uint8_t key[24]; uint8_t keylen; + uint8_t key[24]; } PACKED; struct p *payload = (struct p *) datain; @@ -370,13 +362,13 @@ void MifareDES_Auth1(uint8_t *datain) { } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, RndB); } else if (payload->algo == MFDES_ALGO_3DES) - tdes_dec(&RndB, &encRndB, key->data); + tdes_dec(RndB, encRndB, key->data); else if (payload->algo == MFDES_ALGO_DES) - des_dec(&RndB, &encRndB, key->data); + des_dec(RndB, encRndB, key->data); else if (payload->algo == MFDES_ALGO_2K3DES) - tdes_2key_dec(&RndB, &encRndB, 8, key->data, IV); + tdes_2key_dec(RndB, encRndB, 8, key->data, IV); else if (payload->algo == MFDES_ALGO_3K3DES) - tdes_3key_dec(&RndB, &encRndB, 16, key->data, IV); + tdes_3key_dec(RndB, encRndB, 16, key->data, IV); // - Rotate RndB by 8 bits memcpy(rotRndB, RndB, payload->keylen); @@ -387,16 +379,16 @@ void MifareDES_Auth1(uint8_t *datain) { // - Encrypt our response if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_ISO || payload->mode == MFDES_AUTH_PICC) { if (payload->algo == MFDES_ALGO_3DES) { - tdes_dec(&encRndA, &RndA, key->data); + tdes_dec(encRndA, RndA, key->data); memcpy(both, encRndA, 8); } else if (payload->algo == MFDES_ALGO_DES) { - des_dec(&encRndA, &RndA, key->data); + des_dec(encRndA, RndA, key->data); memcpy(both, encRndA, 8); } else if (payload->algo == MFDES_ALGO_2K3DES) { - tdes_2key_dec(&encRndA, &RndA, 8, key->data, IV); + tdes_2key_dec(encRndA, RndA, 8, key->data, IV); memcpy(both, encRndA, 8); } else if (payload->algo == MFDES_ALGO_3K3DES) { - tdes_3key_dec(&encRndA, &RndA, 16, key->data, IV); + tdes_3key_dec(encRndA, RndA, 16, key->data, IV); memcpy(both, encRndA, 16); } @@ -406,16 +398,16 @@ void MifareDES_Auth1(uint8_t *datain) { } if (payload->algo == MFDES_ALGO_3DES) { - tdes_dec(&encRndB, &rotRndB, key->data); + tdes_dec(encRndB, rotRndB, key->data); memcpy(both + 8, encRndB, 8); } else if (payload->algo == MFDES_ALGO_DES) { - des_dec(&encRndB, &rotRndB, key->data); + des_dec(encRndB, rotRndB, key->data); memcpy(both + 8, encRndB, 8); } else if (payload->algo == MFDES_ALGO_2K3DES) { - tdes_2key_dec(&encRndB, &rotRndB, 8, key->data, IV); + tdes_2key_dec(encRndB, rotRndB, 8, key->data, IV); memcpy(both + 8, encRndB, 8); } else if (payload->algo == MFDES_ALGO_3K3DES) { - tdes_3key_dec(&encRndB, &rotRndB, 16, key->data, IV); + tdes_3key_dec(encRndB, rotRndB, 16, key->data, IV); memcpy(both + 16, encRndB, 16); } @@ -481,7 +473,7 @@ void MifareDES_Auth1(uint8_t *datain) { desfirekey_t skey = &sessionKey; Desfire_session_key_new(RndA, RndB, key, skey); if (DBGLEVEL >= DBG_EXTENDED) - print_result("SESSIONKEY : ", skey->data, payload->keylen); + print_result("SESSIONKEY : ", sessionKey.data, payload->keylen); if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndA, resp + 1, payload->keylen); @@ -491,13 +483,13 @@ void MifareDES_Auth1(uint8_t *datain) { if (payload->mode == MFDES_AUTH_DES || payload->mode == MFDES_AUTH_PICC) { if (payload->algo == MFDES_ALGO_3DES) - tdes_dec(&encRndA, &encRndA, key->data); + tdes_dec(encRndA, encRndA, key->data); else if (payload->algo == MFDES_ALGO_DES) - des_dec(&encRndA, &encRndA, key->data); + des_dec(encRndA, encRndA, key->data); else if (payload->algo == MFDES_ALGO_2K3DES) - tdes_2key_dec(&encRndA, &encRndA, 8, key->data, IV); + tdes_2key_dec(encRndA, encRndA, 8, key->data, IV); else if (payload->algo == MFDES_ALGO_3K3DES) - tdes_3key_dec(&encRndA, &encRndA, 16, key->data, IV); + tdes_3key_dec(encRndA, encRndA, 16, key->data, IV); } else if (payload->mode == MFDES_AUTH_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { if (DBGLEVEL >= DBG_EXTENDED) { @@ -512,6 +504,7 @@ void MifareDES_Auth1(uint8_t *datain) { rol(RndA, payload->keylen); if (DBGLEVEL >= DBG_EXTENDED) { print_result("RndA : ", RndA, payload->keylen); + print_result("RndB: ", RndB, payload->keylen); print_result("encRndA : ", encRndA, payload->keylen); } for (int x = 0; x < payload->keylen; x++) { @@ -618,15 +611,10 @@ void MifareDES_Auth1(uint8_t *datain) { //reply_mix(CMD_ACK, 1, len, 0, resp, len); LED_B_ON(); - struct r { - uint8_t sessionkeylen; - uint8_t sessionkey[24]; - } PACKED; - - struct r rpayload; + authres_t rpayload; rpayload.sessionkeylen = payload->keylen; - memcpy(rpayload.sessionkey, skey->data, rpayload.sessionkeylen); - reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(payload)); + memcpy(rpayload.sessionkey, sessionKey.data, rpayload.sessionkeylen); + reply_ng(CMD_HF_DESFIRE_AUTH1, PM3_SUCCESS, (uint8_t *)&rpayload, sizeof(rpayload)); LED_B_OFF(); } diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 17ff33410..6259ac422 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -34,23 +34,21 @@ uint8_t key_ones_data[16] = { 0x01 }; uint8_t key_defa_data[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; +typedef struct { + uint8_t mode; + uint8_t algo; + uint8_t keyno; + uint8_t keylen; + uint8_t key[24]; +} mfdes_authinput_t; + +typedef struct mfdes_auth_res { + uint8_t sessionkeylen; + uint8_t sessionkey[24]; +} mfdes_auth_res_t; + #define status(x) ( ((uint16_t)(0x91<<8)) + x ) -typedef enum { - MFDES_AUTH_DES = 1, - MFDES_AUTH_ISO = 2, - MFDES_AUTH_AES = 3, - MFDES_AUTH_PICC = 4 -} mifare_des_authmode_t; - -typedef enum { - MFDES_ALGO_DES = 1, - MFDES_ALGO_3DES = 2, - MFDES_ALGO_2K3DES = 3, - MFDES_ALGO_3K3DES = 4, - MFDES_ALGO_AES = 5 -} mifare_des_authalgo_t; - typedef enum { UNKNOWN = 0, DESFIRE_MF3ICD40, @@ -949,27 +947,27 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { if (aidlength < 3) { PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_SNONCES; + return PM3_EINVARG; } if (fidlength < 2) { PrintAndLogEx(ERR, "FID must have 2 bytes length."); - return PM3_SNONCES; + return PM3_EINVARG; } if (keylen1 < 1) { PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); - return PM3_SNONCES; + return PM3_EINVARG; } if (keylen1 < 1) { PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); - return PM3_SNONCES; + return PM3_EINVARG; } if (namelen > 16) { PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); - return PM3_SNONCES; + return PM3_EINVARG; } //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 @@ -1018,7 +1016,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { if (aidlength < 3) { PrintAndLogEx(ERR, "AID must have 3 bytes length."); - return PM3_SNONCES; + return PM3_EINVARG; } if (memcmp(aid, "\x00\x00\x00", 3) == 0) { @@ -1054,20 +1052,15 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { if ((keylen < 8) || (keylen > 8)) { PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); - return PM3_SNONCES; + return PM3_EINVARG; } DropField(); uint8_t aid[3] = {0}; int res = get_desfire_select_application(aid); if (res != PM3_SUCCESS) return res; - struct { - uint8_t mode; - uint8_t algo; - uint8_t keyno; - uint8_t key[24]; - uint8_t keylen; - } PACKED payload; + + mfdes_authinput_t payload; payload.keylen = keylen; memcpy(payload.key, key, keylen); payload.mode = MFDES_AUTH_PICC; @@ -1496,7 +1489,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParserInit("hf mfdes auth", "Authenticates Mifare DESFire using Key", "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=2K3DES, 4=3K3DES, 5=AES)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" - "Example:\n\thf mfdes auth -m 3 -t 5 -a 018380 -n 0 -k 00000000000000000000000000000000\n" + "Example:\n\thf mfdes auth -m 3 -t 5 -a 838001 -n 0 -k 00000000000000000000000000000000\n" ); void *argtable[] = { @@ -1516,7 +1509,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { int aidlength = 3; uint8_t aid[3] = {0}; CLIGetHexWithReturn(3, aid, &aidlength); - swap16(aid); + swap24(aid); uint8_t cmdKeyNo = arg_get_int_def(4, 0); uint8_t key[24] = {0}; @@ -1526,43 +1519,43 @@ static int CmdHF14ADesAuth(const char *Cmd) { if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); - return PM3_SNONCES; + return PM3_EINVARG; } // AID if (aidlength != 3) { PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_SNONCES; + return PM3_EINVARG; } switch (cmdAuthMode) { case MFDES_AUTH_DES: if (cmdAuthAlgo != MFDES_ALGO_DES && cmdAuthAlgo != MFDES_ALGO_3DES) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth des mode"); - return PM3_SNONCES; + return PM3_EINVARG; } break; case MFDES_AUTH_ISO: if (cmdAuthAlgo != MFDES_ALGO_2K3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); - return PM3_SNONCES; + return PM3_EINVARG; } break; case MFDES_AUTH_AES: if (cmdAuthAlgo != MFDES_ALGO_AES) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth aes mode"); - return PM3_SNONCES; + return PM3_EINVARG; } break; case MFDES_AUTH_PICC: if (cmdAuthAlgo != MFDES_AUTH_DES) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); - return PM3_SNONCES; + return PM3_EINVARG; } break; default: PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - return PM3_SNONCES; + return PM3_EINVARG; } switch (cmdAuthAlgo) { @@ -1592,7 +1585,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { // KEY if (keylen != keylength) { PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); - return PM3_SNONCES; + return PM3_EINVARG; } @@ -1606,13 +1599,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { if (res != PM3_SUCCESS) return res; } - struct { - uint8_t mode; - uint8_t algo; - uint8_t keyno; - uint8_t key[24]; - uint8_t keylen; - } PACKED payload; + mfdes_authinput_t payload; payload.keylen = keylength; memcpy(payload.key, key, keylength); payload.mode = cmdAuthMode; @@ -1630,15 +1617,9 @@ static int CmdHF14ADesAuth(const char *Cmd) { uint8_t isOK = (resp.status == PM3_SUCCESS); if (isOK) { - struct r { - uint8_t sessionkeylen; - uint8_t sessionkey[24]; - } PACKED; - - struct r *rpayload = (struct r *)&resp.data.asBytes; - uint8_t *session_key = rpayload->sessionkey; + struct mfdes_auth_res *rpayload = (struct mfdes_auth_res *)&resp.data.asBytes; PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); - PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(session_key, keylength)); + PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload->sessionkey, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); } else { PrintAndLogEx(WARNING, _RED_("Auth command failed, reason: %d."), resp.status); diff --git a/include/mifare.h b/include/mifare.h index b8df9a2ec..5cca91cbc 100644 --- a/include/mifare.h +++ b/include/mifare.h @@ -80,6 +80,22 @@ typedef enum DESFIRE_COMMAND { BAR = 0x10, } desfire_command_t; +typedef enum { + MFDES_AUTH_DES = 1, + MFDES_AUTH_ISO = 2, + MFDES_AUTH_AES = 3, + MFDES_AUTH_PICC = 4 +} mifare_des_authmode_t; + +typedef enum { + MFDES_ALGO_DES = 1, + MFDES_ALGO_3DES = 2, + MFDES_ALGO_2K3DES = 3, + MFDES_ALGO_3K3DES = 4, + MFDES_ALGO_AES = 5 +} mifare_des_authalgo_t; + + //----------------------------------------------------------------------------- // ISO 14443B //----------------------------------------------------------------------------- From 0c407504b3adcc831b2f11b8e9fa7549d4c61009 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 11 Apr 2020 13:14:16 +0200 Subject: [PATCH 60/66] Fix file ids handling --- client/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 6259ac422..357d82e65 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -1434,7 +1434,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t filesettings[20] = {0}; int fileset_len = 0; - int res = get_desfire_filesettings(j, filesettings, &fileset_len); + int res = get_desfire_filesettings(file_ids[j], filesettings, &fileset_len); int maclen = 0; // To be implemented if (res == PM3_SUCCESS) { if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) { From 309020c64c25b416e84fc10ab4006707ddbebd5e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 11 Apr 2020 20:41:05 +0200 Subject: [PATCH 61/66] more error messages when failing parsing --- client/cliparser/cliparser.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/client/cliparser/cliparser.c b/client/cliparser/cliparser.c index 02746c0f4..4e0fb4d9c 100644 --- a/client/cliparser/cliparser.c +++ b/client/cliparser/cliparser.c @@ -38,6 +38,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("ERROR: Insufficient memory\n"); + fflush(stdout); return 2; } /* Parse the command line as defined by argtable[] */ @@ -54,6 +55,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable if (programHelp) printf("%s \n", programHelp); + fflush(stdout); return 1; } @@ -62,7 +64,7 @@ int CLIParserParseArg(int argc, char **argv, void *vargtable[], size_t vargtable /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, ((struct arg_end *)argtable[vargtableLen - 1]), programName); printf("Try '%s --help' for more information.\n", programName); - + fflush(stdout); return 3; } @@ -155,18 +157,24 @@ int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int int ibuf = 0; uint8_t tmp_buf[256] = {0}; int res = CLIParamStrToBuf(argstr, tmp_buf, maxdatalen * 2, &ibuf); // *2 because here HEX - if (res || !ibuf) + if (res || !ibuf){ + printf("Parameter error: buffer overflow.\n"); + fflush(stdout); return res; - + } + switch (param_gethex_to_eol((char *)tmp_buf, 0, data, maxdatalen, datalen)) { case 1: printf("Parameter error: Invalid HEX value.\n"); + fflush(stdout); return 1; case 2: printf("Parameter error: parameter too large.\n"); + fflush(stdout); return 2; case 3: printf("Parameter error: Hex string must have even number of digits.\n"); + fflush(stdout); return 3; } From c9bd43c4b67264eaa0e996ed8cb3d7d1e58b0cd4 Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Sun, 12 Apr 2020 13:07:25 +1000 Subject: [PATCH 62/66] Edit and Updates Changed from settings to preferences. Added UTF8 Banner support Added Show/Edit draft --- client/Makefile | 2 +- client/cmdmain.c | 7 + client/fileutils.c | 6 +- client/preferences.c | 563 +++++++++++++++++++++++++++ client/{settings.h => preferences.h} | 15 +- client/proxguiqt.cpp | 6 +- client/proxmark3.c | 71 +++- client/settings.c | 211 ---------- client/ui.h | 2 +- 9 files changed, 646 insertions(+), 237 deletions(-) create mode 100644 client/preferences.c rename client/{settings.h => preferences.h} (67%) delete mode 100644 client/settings.c diff --git a/client/Makefile b/client/Makefile index 87cf03a19..e46e51eb2 100644 --- a/client/Makefile +++ b/client/Makefile @@ -253,7 +253,7 @@ CMDSRCS = crapto1/crapto1.c \ wiegand_formats.c \ wiegand_formatutils.c \ cardhelper.c \ - settings.c + preferences.c cpu_arch = $(shell uname -m) ifneq ($(findstring 86, $(cpu_arch)), ) diff --git a/client/cmdmain.c b/client/cmdmain.c index 8d4b1c8b7..906a354f6 100644 --- a/client/cmdmain.c +++ b/client/cmdmain.c @@ -37,6 +37,7 @@ #include "ui.h" #include "util_posix.h" #include "commonutil.h" // ARRAYLEN +#include "preferences.h" static int CmdHelp(const char *Cmd); @@ -241,6 +242,11 @@ static int CmdRev(const char *Cmd) { return PM3_SUCCESS; } +static int CmdPref(const char *Cmd) { + CmdPreferences(Cmd); + return PM3_SUCCESS; +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help. Use ' help' for details of a particular command."}, {"auto", CmdAuto, IfPm3Present, "Automated detection process for unknown tags"}, @@ -259,6 +265,7 @@ static command_t CommandTable[] = { {"wiegand", CmdWiegand, AlwaysAvailable, "{ Wiegand format manipulation... }"}, {"", CmdHelp, AlwaysAvailable, ""}, {"hints", CmdHints, AlwaysAvailable, "Turn hints on / off"}, + {"pref", CmdPref, AlwaysAvailable, "Edit preferences"}, {"msleep", CmdMsleep, AlwaysAvailable, "Add a pause in milliseconds"}, {"rem", CmdRem, AlwaysAvailable, "Add a text line in log file"}, {"quit", CmdQuit, AlwaysAvailable, ""}, diff --git a/client/fileutils.c b/client/fileutils.c index 05a7e8949..1eb82e57c 100644 --- a/client/fileutils.c +++ b/client/fileutils.c @@ -38,7 +38,7 @@ // this define is needed for scandir/alphasort to work #define _GNU_SOURCE #include "fileutils.h" -#include "settings.h" +#include "preferences.h" #include #include @@ -427,7 +427,7 @@ int saveFileJSON(const char *preferredName, JSONFileType ftype, uint8_t *data, s } break; case jsfSettings: - settings_save_callback (root); + preferences_save_callback (root); break; default: break; @@ -868,7 +868,7 @@ int loadFileJSON(const char *preferredName, void *data, size_t maxdatalen, size_ *datalen = sptr; } if (!strcmp(ctype,"settings")) { - settings_load_callback (root); + preferences_load_callback (root); } PrintAndLogEx(SUCCESS, "loaded from JSON file " _YELLOW_("%s"), fileName); out: diff --git a/client/preferences.c b/client/preferences.c new file mode 100644 index 000000000..18882e912 --- /dev/null +++ b/client/preferences.c @@ -0,0 +1,563 @@ +/***************************************************************************** + * WARNING + * + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * + ***************************************************************************** + * + * This file is part of loclass. It is a reconstructon of the cipher engine + * used in iClass, and RFID techology. + * + * The implementation is based on the work performed by + * Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and + * Milosch Meriac in the paper "Dismantling IClass". + * + * Copyright (C) 2014 Martin Holst Swende + * + * This is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation, or, at your option, any later version. + * + * This file is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with loclass. If not, see . + * + * + ****************************************************************************/ + +//----------------------------------------------------------------------------- +// Preferences Functions +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Notes +// To add a new setting +// Add the new setting to the session_arg_t; in ui.h +// Add the default value for the setting in the settings_load page below +// Update the preferences_load_callback to load your setting into the stucture +// Update the preferences_save_callback to enusre your setting gets saved when needed. +// use the preference as needed : session. +// Can use (session.preferences_loaded) to check if json settings file was used +//----------------------------------------------------------------------------- + +#include "preferences.h" +#include "comms.h" +#include "emv/emvjson.h" +#include +#include "cmdparser.h" +#include + +static int CmdHelp(const char *Cmd); + +// Load all settings into memory (struct) +int preferences_load (void) { + + // Set all defaults + session.client_debug_level = OFF; + session.window_plot_xpos = 10; + session.window_plot_ypos = 30; + session.window_plot_hsize = 400; + session.window_plot_wsize = 800; + session.window_overlay_xpos = session.window_plot_xpos; + session.window_overlay_ypos = 60+session.window_plot_ypos + session.window_plot_hsize; + session.window_overlay_hsize = 200; + session.window_overlay_wsize = session.window_plot_wsize; + session.emoji_mode = ALIAS; + session.show_hints = false; + session.supports_colors = false; + + // loadFileJson wants these, so pass in place holder values, though not used + // in settings load; + uint8_t dummyData = 0x00; + size_t dummyDL = 0x00; + + if (loadFileJSON(preferencesFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { + session.preferences_loaded = true; + } + // Note, if session.settings_loaded == false then the settings_save + // will be called in main () to save settings as set in defaults and main() checks. + + return PM3_SUCCESS; +} + +// Save all settings from memory (struct) to file +int preferences_save (void) { + // Note sure if backup has value ? + char backupFilename[500]; + + snprintf (backupFilename,sizeof(backupFilename),"%s.bak",preferencesFilename); + + if (fileExists (backupFilename)) { + if (remove (backupFilename) != 0) { + PrintAndLogEx (FAILED, "Error - could not delete old settings backup file \"%s\"",backupFilename); + return PM3_ESOFT; + } + } + + if (fileExists (preferencesFilename)) { + if (rename (preferencesFilename,backupFilename) != 0) { + PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",preferencesFilename,backupFilename); + return PM3_ESOFT; + } + } + + uint8_t dummyData = 0x00; + size_t dummyDL = 0x00; + + if (saveFileJSON(preferencesFilename, jsfSettings, &dummyData, dummyDL) != PM3_SUCCESS) + PrintAndLogEx (ERR, "Error saving preferences to \"%s\"",preferencesFilename); + + return PM3_SUCCESS; +} + +void preferences_save_callback (json_t *root) { + + JsonSaveStr (root,"FileType","settings"); + + // Log level, convert to text + switch (session.client_debug_level) { + case OFF: JsonSaveStr (root,"client.debug.level","off"); break; + case SIMPLE: JsonSaveStr (root,"client.debug.level","simple"); break; + case FULL: JsonSaveStr (root,"client.debug.level","full"); break; + default: + JsonSaveStr (root,"logging.level","NORMAL"); + } + + // Plot window + JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); + JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); + JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); + JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); + + // Overlay/Slider window + JsonSaveInt (root,"window.overlay.xpos",session.window_overlay_xpos); + JsonSaveInt (root,"window.overlay.ypos",session.window_overlay_ypos); + JsonSaveInt (root,"window.overlay.hsize",session.window_overlay_hsize); + JsonSaveInt (root,"window.overlay.wsize",session.window_overlay_wsize); + + // Emoji + switch (session.emoji_mode) { + case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; + case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; + case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; + case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; + default: + JsonSaveStr (root,"show.emoji","ALIAS"); + } + + JsonSaveBoolean (root,"show.hints",session.show_hints); + + JsonSaveBoolean (root,"os.supports.colors",session.supports_colors); +} + +void preferences_load_callback (json_t *root) { + json_error_t up_error = {0}; + bool b1; + int i1; + const char *s1; + char tempStr [500]; // to use str_lower() since json unpack uses const char * + + // Logging Level + if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"off",3) == 0) session.client_debug_level = OFF; + if (strncmp (tempStr,"simple",6) == 0) session.client_debug_level = SIMPLE; + if (strncmp (tempStr,"full",4) == 0) session.client_debug_level = FULL; + } + + // window plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) + session.window_plot_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) + session.window_plot_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) + session.window_plot_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) + session.window_plot_wsize = i1; + + // overlay/slider plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.xpos",&i1) == 0) + session.window_overlay_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.ypos",&i1) == 0) + session.window_overlay_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.hsize",&i1) == 0) + session.window_overlay_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.wsize",&i1) == 0) + session.window_overlay_wsize = i1; + + // show options + if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"alias",5) == 0) session.emoji_mode = ALIAS; + if (strncmp (tempStr,"emoji",5) == 0) session.emoji_mode = EMOJI; + if (strncmp (tempStr,"alttext",7) == 0) session.emoji_mode = ALTTEXT; + if (strncmp (tempStr,"erase",5) == 0) session.emoji_mode = ERASE; + } + + if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) + session.show_hints = b1; + + if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.supports.colors",&b1) == 0) + session.supports_colors = b1; + +} + +// Help Functions +static int usage_pref_set() { + PrintAndLogEx(NORMAL, "Usage: pref set [(h)elp] [(e)moji ...] [(c)olor ...] [(hi)nts ...] [debug ...]"); + PrintAndLogEx(NORMAL, " [(p)lot ...] [(o)verlay ...]"); + PrintAndLogEx(NORMAL, "Options:"); + PrintAndLogEx(NORMAL, " help - This help"); + PrintAndLogEx(NORMAL, " emoji <(ali)as | (em)oji | (alt)text | (er)ase> - Set the level of emoji support"); + PrintAndLogEx(NORMAL, " alias : show alias"); + PrintAndLogEx(NORMAL, " emoji : show emoji"); + PrintAndLogEx(NORMAL, " alttext : show alternative text"); + PrintAndLogEx(NORMAL, " erase : dont show any emoji"); + + PrintAndLogEx(NORMAL, " color <(o)ff|(a)nsi> - Color support level"); + PrintAndLogEx(NORMAL, " off : dont use color"); + PrintAndLogEx(NORMAL, " ansi : use ansi color (linux, mac, windows terminal)"); + + PrintAndLogEx(NORMAL, " hints <(of)f | on> - Show hints on/off"); + + PrintAndLogEx(NORMAL, " debug <(o)ff | (s)imple | (f)ull> - Client debug level"); + PrintAndLogEx(NORMAL, " off : no debug output"); + PrintAndLogEx(NORMAL, " simple : information level debug"); + PrintAndLogEx(NORMAL, " full : full debug information"); + + PrintAndLogEx(NORMAL, " plot [x ] [y ] [h ] [w ] - Position the plot window"); + PrintAndLogEx(NORMAL, " overlay [x ] [y ] [h ] [w ] - Position the overlay/slider window"); + + return PM3_SUCCESS; +} + +static int usage_pref_show() { + PrintAndLogEx(NORMAL, "Usage: pref show [help] [emoji|color]"); + PrintAndLogEx(NORMAL, "Options:"); + PrintAndLogEx(NORMAL, " help - This help"); + PrintAndLogEx(NORMAL, " emoji - show current settings for emoji"); + PrintAndLogEx(NORMAL, " color - show current settings for color"); + + return PM3_SUCCESS; +} + +// Preference Processing Functions +typedef enum preferenceId {prefNONE,prefHELP,prefEMOJI,prefCOLOR,prefPLOT,prefOVERLAY,prefHINTS,prefCLIENTDEBUG} preferenceId_t; + +// Enumerate text to ID +preferenceId_t prefGetID (char* cmdOpt) +{ + str_lower (cmdOpt); + + if (strncmp (cmdOpt,"hi",2) == 0) return prefHINTS; + if (strncmp (cmdOpt,"h",1) == 0) return prefHELP; + if (strncmp (cmdOpt,"e",1) == 0) return prefEMOJI; + if (strncmp (cmdOpt,"c",1) == 0) return prefCOLOR; + if (strncmp (cmdOpt,"p",1) == 0) return prefPLOT; + if (strncmp (cmdOpt,"o",1) == 0) return prefOVERLAY; + if (strncmp (cmdOpt,"d",1) == 0) return prefCLIENTDEBUG; + + return NONE; +} + +void showEmojiState (void) { + switch (session.emoji_mode) { + case ALIAS: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show alias")); + break; + case EMOJI: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show emoji")); + break; + case ALTTEXT: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("show alt text")); + break; + case ERASE: PrintAndLogEx(NORMAL, " emoji.................. "_GREEN_("dont show emoji")); + break; + default: + PrintAndLogEx(NORMAL, " emoji.................. "_RED_("unknown")); + } +} + +void showColorState (void) { +/* + switch (session.supports_colors) { + case false: PrintAndLogEx(NORMAL, "Color : "_GREEN_("off")); + break; + case true: PrintAndLogEx(NORMAL, "Color : "_GREEN_("ansi")); + break; + default: + PrintAndLogEx(NORMAL, "Color support set to : "_RED_("unknown")); + } +*/ + // this will change to 1 of a set from bool + if (session.supports_colors) + PrintAndLogEx(NORMAL, " color.................. "_GREEN_("ansi")); + else + PrintAndLogEx(NORMAL, " color.................. "_GREEN_("off")); +} + +void showClientDebugState (void) { + switch (session.client_debug_level) { + case OFF: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("off")); + break; + case SIMPLE: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("simple")); + break; + case FULL: PrintAndLogEx (NORMAL," client debug........... "_GREEN_("full")); + break; + default: + PrintAndLogEx(NORMAL, " client debug........... "_RED_("unknown")); + } +} + +void showPlotPosState (void){ + PrintAndLogEx (NORMAL," Plot window............ X "_GREEN_("%4d")" Y "_GREEN_("%4d")" H "_GREEN_("%4d")" W "_GREEN_("%4d"), + session.window_plot_xpos,session.window_plot_ypos,session.window_plot_hsize,session.window_plot_wsize); +} + +void showOverlayPosState (void){ + PrintAndLogEx (NORMAL," Slider/Overlay window.. X "_GREEN_("%4d")" Y "_GREEN_("%4d")" H "_GREEN_("%4d")" W "_GREEN_("%4d"), + session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_hsize,session.window_overlay_wsize); +} + +void showHintsState (void){ + if (session.show_hints) + PrintAndLogEx (NORMAL," Hints.................. "_GREEN_("on")); + else + PrintAndLogEx (NORMAL," Hints.................. "_GREEN_("off")); +} + +static int CmdPrefShow (const char *Cmd) { + uint8_t cmdp = 0; + preferenceId_t CmdPref; + bool errors = false; + char strOpt[50]; + + PrintAndLogEx(NORMAL,""); + PrintAndLogEx(NORMAL,_BLUE_("Preferences")); + + if (!session. preferences_loaded) { + PrintAndLogEx (ERR,"Preferneces not loaded"); + return PM3_ESOFT; + } + + if (param_getchar(Cmd, cmdp) == 0x00) { // No options - Show all + showEmojiState (); + showColorState (); + showPlotPosState (); + showOverlayPosState (); + showClientDebugState(); + showHintsState (); + } + else { + + while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) { + + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + CmdPref = prefGetID(strOpt); + } + else + CmdPref = prefNONE; + + switch (CmdPref) { + case prefHELP: + return usage_pref_show(); + case prefEMOJI: + showEmojiState (); + break; + case prefCOLOR: // color + showColorState (); + break; + case prefPLOT: + showPlotPosState (); + break; + case prefOVERLAY: + showOverlayPosState (); + break; + case prefCLIENTDEBUG: + showClientDebugState(); + break; + case prefHINTS: + showHintsState(); + break; + case prefNONE: + PrintAndLogEx (ERR,"Invalid option supplied"); + errors = true; + break; + // errors + } + cmdp ++; + } + } + PrintAndLogEx(NORMAL,""); + return PM3_SUCCESS; +} + +static int CmdPrefSet (const char *Cmd) +{ + uint8_t cmdp = 0; + preferenceId_t CmdPref; + bool errors = false; + // char charOpt; + char strOpt[50]; + int x,y,h,w; + + if (param_getchar(Cmd, cmdp) == 0x00) + return usage_pref_set(); + + while ((param_getchar(Cmd, cmdp) != 0x00) && !errors) { + + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + CmdPref = prefGetID(strOpt); + } + else + CmdPref = prefNONE; + + switch (CmdPref) { + case prefHELP: + return usage_pref_set(); + case prefEMOJI: + showEmojiState (); + cmdp++; + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + str_lower(strOpt); + if (strncmp (strOpt,"ali",3) == 0) { session.emoji_mode = ALIAS; showEmojiState (); break; } + if (strncmp (strOpt,"em",2) == 0) { session.emoji_mode = EMOJI; showEmojiState (); break; } + if (strncmp (strOpt,"alt",3) == 0) { session.emoji_mode = ALTTEXT; showEmojiState (); break; } + if (strncmp (strOpt,"er",2) == 0) { session.emoji_mode = ERASE; showEmojiState (); break; } + // if we get this far, then an error in the mode + PrintAndLogEx(ERR,"Invalid emoji option"); + errors = true; + } + else + errors = true; + break; + case prefCOLOR: // color + showColorState (); + cmdp++; + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + str_lower(strOpt); + if (strncmp(strOpt,"a",1) == 0) { session.supports_colors = true; showColorState (); break; } + if (strncmp(strOpt,"o",1) == 0) { session.supports_colors = false; showColorState (); break; } + // if we get this far, then an error in the mode + PrintAndLogEx(ERR,"Invalid color option"); + errors = true; + } + else + errors = true; + break; + case prefPLOT: + showPlotPosState (); + cmdp++; + x = y = h = w = -99999; // Some invalid value + for (int i = 0; i < 4; i++) { // upto 4 values X, Y, H, WARNING + if (param_getchar(Cmd, cmdp) != 0){ + switch (tolower(param_getchar(Cmd, cmdp++))) { + case 'x': x = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'y': y = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'h': h = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'w': w = param_get32ex(Cmd,cmdp++,-99999,10); break; + default: + errors = true; + } + } + } + if (x != -99999) session.window_plot_xpos = x; + if (y != -99999) session.window_plot_ypos = y; + if (h != -99999) session.window_plot_hsize = h; + if (w != -99999) session.window_plot_wsize = w; + // Need to work out how to change live.... + // calling data plot seems to work + + showPlotPosState (); + break; + case prefOVERLAY: + showOverlayPosState (); + cmdp++; + x = y = h = w = -99999; // Some invalid value + for (int i = 0; i < 4; i++) { // upto 4 values X, Y, H, WARNING + if (param_getchar(Cmd, cmdp) != 0){ + switch (tolower(param_getchar(Cmd, cmdp++))) { + case 'x': x = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'y': y = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'h': h = param_get32ex(Cmd,cmdp++,-99999,10); break; + case 'w': w = param_get32ex(Cmd,cmdp++,-99999,10); break; + default: + errors = true; + } + } + } + if (x != -99999) session.window_overlay_xpos = x; + if (y != -99999) session.window_overlay_ypos = y; + if (h != -99999) session.window_overlay_hsize = h; + if (w != -99999) session.window_overlay_wsize = w; + showOverlayPosState (); + // Need to work out how to change live.... + break; + case prefCLIENTDEBUG: + showClientDebugState(); + cmdp++; + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + str_lower(strOpt); + if (strncmp(strOpt,"o",1) == 0) { session.client_debug_level = OFF; g_debugMode = OFF; showClientDebugState(); break; } + if (strncmp(strOpt,"s",1) == 0) { session.client_debug_level = SIMPLE; g_debugMode = SIMPLE; showClientDebugState(); break; } + if (strncmp(strOpt,"f",1) == 0) { session.client_debug_level = FULL; g_debugMode = FULL; showClientDebugState(); break; } + // if we get this far, then an error in the mode + PrintAndLogEx(ERR,"Invalid client debug option"); + errors = true; + } + else + errors = true; + break; + case prefHINTS: + showHintsState (); + cmdp++; + if (param_getstr(Cmd, cmdp, strOpt, sizeof(strOpt)) != 0) { + str_lower(strOpt); + if (strncmp(strOpt,"on",2) == 0) { session.show_hints = true; showHintsState (); break; } + if (strncmp(strOpt,"of",2) == 0) { session.show_hints = false; showHintsState (); break; } + // if we get this far, then an error in the mode + PrintAndLogEx(ERR,"Invalid hint option"); + errors = true; + } + else + errors = true; + break; + case prefNONE: + PrintAndLogEx (ERR,"Invalid option supplied"); + errors = true; + break; + } + cmdp ++; + } + preferences_save(); + return PM3_SUCCESS; +} + +static command_t CommandTable[] = { + {"help", CmdHelp, AlwaysAvailable, "This help"}, + {"set", CmdPrefSet, AlwaysAvailable, "Set a preference"}, + {"show", CmdPrefShow, AlwaysAvailable, "Show (a preference)"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelp(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + CmdsHelp(CommandTable); + + return PM3_SUCCESS; +} + +int CmdPreferences (const char *Cmd) +{ + clearCommandBuffer(); + + return CmdsParse(CommandTable, Cmd); +} \ No newline at end of file diff --git a/client/settings.h b/client/preferences.h similarity index 67% rename from client/settings.h rename to client/preferences.h index c404a82e2..7dce07fc6 100644 --- a/client/settings.h +++ b/client/preferences.h @@ -8,17 +8,18 @@ //----------------------------------------------------------------------------- // Settings Functions //----------------------------------------------------------------------------- -#ifndef SETTINGS_H_ -#define SETTINGS_H_ +#ifndef PREFERENCES_H_ +#define PREFERENCES_H_ #include "fileutils.h" -#define settingsFilename "settings.json" +#define preferencesFilename "preferences.json" -int settings_load (void); -int settings_save (void); +int CmdPreferences (const char *Cmd); +int preferences_load (void); +int preferences_save (void); -void settings_save_callback (json_t *root); -void settings_load_callback (json_t *root); +void preferences_save_callback (json_t *root); +void preferences_load_callback (json_t *root); #endif diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index 4e2c9299f..cbe4ade8d 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -170,7 +170,7 @@ void ProxWidget::vchange_dthr_down(int v) { ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { this->master = master; // Set the initail postion and size from settings - if (session.settings_loaded) + if (session.preferences_loaded) setGeometry (session.window_plot_xpos,session.window_plot_ypos,session.window_plot_wsize,session.window_plot_hsize); else resize(800, 400); @@ -210,14 +210,14 @@ ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { // shows plot window on the screen. show(); - if (session.settings_loaded) + if (session.preferences_loaded) controlWidget->setGeometry (session.window_overlay_xpos,session.window_overlay_ypos,session.window_overlay_wsize,session.window_overlay_hsize); else { // Move controller widget below plot controlWidget->move(x(), y() + frameSize().height()); controlWidget->resize(size().width(), 200); } - + // Olverlays / slider window title QString ct = QString("[*]Slider [ %1 ]").arg((char *)gui_serial_port_name); controlWidget->setWindowTitle(ct); diff --git a/client/proxmark3.c b/client/proxmark3.c index c5176dd64..bfc7b6212 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -27,13 +27,58 @@ #include "comms.h" #include "fileutils.h" #include "flash.h" -#include "settings.h" +#include "preferences.h" -// Used to enable/disable use of settings json file -#define USE_SETTING_FILE +// Used to enable/disable use of preferences json file +// #define USE_PREFERENCE_FILE +#ifdef _WIN32 + +static void utf8_showBanner (void) { + + char sq[] = { 0xE2,0x96,0x88,0x00 }; // square block + char tr[] = { 0xE2,0x95,0x97,0x00 }; // top rigth corner + char tl[] = { 0xE2,0x95,0x94,0x00 }; // top left corner + char br[] = { 0xE2,0x95,0x9D,0x00 }; // bottom right corner + char bl[] = { 0xE2,0x95,0x9A,0x00 }; // bottom left corner + char hl[] = { 0xE2,0x95,0x90,0x00 }; // horiz line + char vl[] = { 0xE2,0x95,0x91,0x00 }; // vert line + char msg1 [60]; + char msg2 [60]; + char msg3 [60]; + + strcpy (msg1," :snowflake: iceman@icesql.net :coffee:"); + strcpy (msg2," https://github.com/rfidresearchgroup/proxmark3/"); + strcpy (msg3,"pre-release v4.0"); + + g_printAndLog = PRINTANDLOG_PRINT; + + PrintAndLogEx(NORMAL, "\n"); + + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s %s%s%s%s %s%s%s%s%s "),sq,sq,sq,sq,sq,sq,tr,sq,sq,sq,tr,sq,sq,sq,tr,sq,sq,sq,sq,tr); + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s %s%s%s%s"),sq,sq,tl,hl,hl,sq,sq,tr,sq,sq,sq,sq,tr,sq,sq,sq,sq,vl,hl,hl,sq,vl); + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s%s"),sq,sq,sq,sq,sq,sq,tl,br,sq,sq,tl,sq,sq,sq,sq,tl,sq,sq,vl,sq,sq,sq,sq,tl,br); + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s%s%s%s%s%s%s%s %s%s%s%s")"%s",sq,sq,tr,hl,hl,hl,br,sq,sq,vl,bl,sq,sq,tl,br,sq,sq,vl,hl,hl,sq,vl,msg1); + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s %s%s%s%s%s%s")"%s",sq,sq,vl,sq,sq,vl,bl,hl,br,sq,sq,vl,sq,sq,sq,sq,tl,br,msg2); + PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s%s%s ")"%s",bl,hl,br,bl,hl,br,bl,hl,br,bl,hl,hl,hl,br,msg3); + + PrintAndLogEx(NORMAL, ""); + fflush(stdout); + g_printAndLog = PRINTANDLOG_PRINT | PRINTANDLOG_LOG; +} + +#endif static void showBanner(void) { + +#ifdef _WIN32 + // If on windows and using UTF-8 then we need utf-8 ascii art for banner. + if (GetConsoleCP() == 65001) { + utf8_showBanner (); + return; + } +#endif + g_printAndLog = PRINTANDLOG_PRINT; PrintAndLogEx(NORMAL, "\n"); @@ -60,6 +105,7 @@ static void showBanner(void) { g_printAndLog = PRINTANDLOG_PRINT | PRINTANDLOG_LOG; } + static int check_comm(void) { // If communications thread goes down. Device disconnected then this should hook up PM3 again. if (IsCommunicationThreadDead() && session.pm3_present) { @@ -493,7 +539,7 @@ finish2: return ret; } -#ifndef USE_SETTING_FILE +#ifndef USE_PREFERENCE_FILE // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] @@ -591,11 +637,14 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); -#ifdef USE_SETTING_FILE +#ifdef USE_PREFERENCE_FILE // Load Settings and assign // This will allow the command line to override the settings.json values - settings_load (); - + preferences_load (); + // Change height/width (Rows,Cols) - Testing + // printf ("\e[8;50;100t"); + // printf ("\e[3;50;50t"); // x,y + //printf ("Path : %s \n",my_user_directory); // quick patch for debug level g_debugMode = session.client_debug_level; // settings_save (); @@ -780,7 +829,7 @@ int main(int argc, char *argv[]) { return 1; } -#ifndef USE_SETTING_FILE +#ifndef USE_PREFERENCE_FILE // comment next 2 lines to use session values set from settings_load session.supports_colors = DetectWindowsAnsiSupport(); session.emoji_mode = ALTTEXT; @@ -854,12 +903,12 @@ int main(int argc, char *argv[]) { if (!script_cmds_file && !script_cmd && session.stdinOnTTY && session.stdoutOnTTY && !flash_mode) showBanner(); -#ifdef USE_SETTING_FILE +#ifdef USE_PREFERENCE_FILE // Save settings if not load from settings json file. // Doing this here will ensure other checks and updates are saved to over rule default // e.g. Linux color use check - if (!session.settings_loaded) - settings_save (); + if (!session.preferences_loaded) + preferences_save (); #endif #ifdef HAVE_GUI diff --git a/client/settings.c b/client/settings.c deleted file mode 100644 index 4d59382e2..000000000 --- a/client/settings.c +++ /dev/null @@ -1,211 +0,0 @@ -/***************************************************************************** - * WARNING - * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. - * - ***************************************************************************** - * - * This file is part of loclass. It is a reconstructon of the cipher engine - * used in iClass, and RFID techology. - * - * The implementation is based on the work performed by - * Flavio D. Garcia, Gerhard de Koning Gans, Roel Verdult and - * Milosch Meriac in the paper "Dismantling IClass". - * - * Copyright (C) 2014 Martin Holst Swende - * - * This is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. - * - * This file is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with loclass. If not, see . - * - * - ****************************************************************************/ - -//----------------------------------------------------------------------------- -// Settings Functions -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Notes -// To add a new setting -// Add the new setting to the session_arg_t; in ui.h -// Add the default value for the setting in the settings_load page below -// Update the settings_load_callback to load your setting into the stucture -// Update the settings_save_callback to enusre your setting gets saved when needed. -// use the setting as needed : session. -// Can use (session.settings_loaded) to check if json settings file was used -//----------------------------------------------------------------------------- - -#include "settings.h" -#include "comms.h" -#include "emv/emvjson.h" -#include - -// Load all settings into memory (struct) -int settings_load (void) { - - // Set all defaults - session.client_debug_level = OFF; - session.window_plot_xpos = 10; - session.window_plot_ypos = 30; - session.window_plot_hsize = 400; - session.window_plot_wsize = 800; - session.window_overlay_xpos = session.window_plot_xpos; - session.window_overlay_ypos = 20+session.window_plot_ypos + session.window_plot_hsize; - session.window_overlay_hsize = 200; - session.window_overlay_wsize = session.window_plot_wsize; - session.emoji_mode = ALIAS; - session.show_hints = false; - session.supports_colors = false; - - // loadFileJson wants these, so pass in place holder values, though not used - // in settings load; - uint8_t dummyData = 0x00; - size_t dummyDL = 0x00; - - if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { - session.settings_loaded = true; - } - // Note, if session.settings_loaded == false then the settings_save - // will be called in main () to save settings as set in defaults and main() checks. - - return PM3_SUCCESS; -} - -// Save all settings from memory (struct) to file -int settings_save (void) { - // Note sure if backup has value ? - char backupFilename[500]; - - snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); - - if (fileExists (backupFilename)) { - if (remove (backupFilename) != 0) { - PrintAndLogEx (FAILED, "Error - could not delete old settings backup file \"%s\"",backupFilename); - return PM3_ESOFT; - } - } - - if (fileExists (settingsFilename)) { - if (rename (settingsFilename,backupFilename) != 0) { - PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",settingsFilename,backupFilename); - return PM3_ESOFT; - } - } - - uint8_t dummyData = 0x00; - size_t dummyDL = 0x00; - - if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) - PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); - - return PM3_SUCCESS; -} - -void settings_save_callback (json_t *root) { - - JsonSaveStr (root,"FileType","settings"); - - // Log level, convert to text - switch (session.client_debug_level) { - case OFF: JsonSaveStr (root,"client.debug.level","off"); break; - case SIMPLE: JsonSaveStr (root,"client.debug.level","simple"); break; - case FULL: JsonSaveStr (root,"client.debug.level","full"); break; - default: - JsonSaveStr (root,"logging.level","NORMAL"); - } - - // Plot window - JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); - JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); - JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); - JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); - - // Overlay/Slider window - JsonSaveInt (root,"window.overlay.xpos",session.window_overlay_xpos); - JsonSaveInt (root,"window.overlay.ypos",session.window_overlay_ypos); - JsonSaveInt (root,"window.overlay.hsize",session.window_overlay_hsize); - JsonSaveInt (root,"window.overlay.wsize",session.window_overlay_wsize); - - // Emoji - switch (session.emoji_mode) { - case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; - case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; - case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; - case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; - default: - JsonSaveStr (root,"show.emoji","ALIAS"); - } - - JsonSaveBoolean (root,"show.hints",session.show_hints); - - JsonSaveBoolean (root,"os.supports.colors",session.supports_colors); -} - -void settings_load_callback (json_t *root) { - json_error_t up_error = {0}; - bool b1; - int i1; - const char *s1; - char tempStr [500]; // to use str_lower() since json unpack uses const char * - - // Logging Level - if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { - strncpy (tempStr,s1,sizeof(tempStr)-1); - str_lower (tempStr); - if (strncmp (tempStr,"off",3) == 0) session.client_debug_level = OFF; - if (strncmp (tempStr,"simple",6) == 0) session.client_debug_level = SIMPLE; - if (strncmp (tempStr,"full",4) == 0) session.client_debug_level = FULL; - } - - // window plot - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) - session.window_plot_xpos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) - session.window_plot_ypos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) - session.window_plot_hsize = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) - session.window_plot_wsize = i1; - - // overlay/slider plot - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.xpos",&i1) == 0) - session.window_overlay_xpos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.ypos",&i1) == 0) - session.window_overlay_ypos = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.hsize",&i1) == 0) - session.window_overlay_hsize = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.overlay.wsize",&i1) == 0) - session.window_overlay_wsize = i1; - - // show options - if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { - strncpy (tempStr,s1,sizeof(tempStr)-1); - str_lower (tempStr); - if (strncmp (tempStr,"alias",5) == 0) session.emoji_mode = ALIAS; - if (strncmp (tempStr,"emoji",5) == 0) session.emoji_mode = EMOJI; - if (strncmp (tempStr,"alttext",7) == 0) session.emoji_mode = ALTTEXT; - if (strncmp (tempStr,"erase",5) == 0) session.emoji_mode = ERASE; - } - - if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) - session.show_hints = b1; - - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.supports.colors",&b1) == 0) - session.supports_colors = b1; - -} diff --git a/client/ui.h b/client/ui.h index e5048e751..3875c27c8 100644 --- a/client/ui.h +++ b/client/ui.h @@ -22,7 +22,7 @@ typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; typedef enum clientdebugLevel {OFF,SIMPLE,FULL} clientdebugLevel_t; typedef struct { - bool settings_loaded; + bool preferences_loaded; bool stdinOnTTY; bool stdoutOnTTY; bool supports_colors; From ac8c1398676f0e5c5e71b0ff8da89258d651313e Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Sun, 12 Apr 2020 13:08:02 +1000 Subject: [PATCH 63/66] Update preferences.c --- client/preferences.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/preferences.c b/client/preferences.c index 18882e912..21c38fb2e 100644 --- a/client/preferences.c +++ b/client/preferences.c @@ -7,6 +7,7 @@ * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * From 6d08936f04c8fc02a1347739f7ac6cede576417b Mon Sep 17 00:00:00 2001 From: mwalker33 Date: Sun, 12 Apr 2020 17:56:29 +1000 Subject: [PATCH 64/66] Update cmdhfmf.c key table format fix. (extra space) --- client/cmdhfmf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index e43461591..8d2614ea7 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -3564,7 +3564,7 @@ void printKeyTableEx(uint8_t sectorscnt, sector_t *e_sector, uint8_t start_secto snprintf(strB, sizeof(strB), "%012" PRIx64, e_sector[i].Key[1]); if (e_sector[i].foundKey[0] > 1) { - PrintAndLogEx(SUCCESS, "| "_YELLOW_("%03d")"| " _GREEN_("%s")" | " _YELLOW_("%c")"| " _GREEN_("%s")" | " _YELLOW_("%c")"|" + PrintAndLogEx(SUCCESS, "| "_YELLOW_("%03d")"| " _GREEN_("%s")" | " _YELLOW_("%c")"| " _GREEN_("%s")" | " _YELLOW_("%c")"|" , i , strA, e_sector[i].foundKey[0] , strB, e_sector[i].foundKey[1] From 3454076901bce22204c18119c22f033d86dfc351 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 12 Apr 2020 11:07:20 +0200 Subject: [PATCH 65/66] chg: make which key to use more promenent --- client/cmdhficlass.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index c3042d874..8d82ed32c 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -2096,9 +2096,9 @@ static void HFiClassCalcNewKey(uint8_t *CSN, uint8_t *OLDKEY, uint8_t *NEWKEY, u xor_div_key[i] = old_div_key[i] ^ new_div_key[i]; } if (verbose) { - PrintAndLogEx(SUCCESS, "Old div key : %s\n", sprint_hex(old_div_key, 8)); - PrintAndLogEx(SUCCESS, "New div key : %s\n", sprint_hex(new_div_key, 8)); - PrintAndLogEx(SUCCESS, "Xor div key : %s\n", sprint_hex(xor_div_key, 8)); + PrintAndLogEx(SUCCESS, "Old div key : %s", sprint_hex(old_div_key, 8)); + PrintAndLogEx(SUCCESS, "New div key : %s", sprint_hex(new_div_key, 8)); + PrintAndLogEx(SUCCESS, "Xor div key : " _YELLOW_("%s") "\n", sprint_hex(xor_div_key, 8)); } } @@ -2111,7 +2111,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) { uint8_t dataLen = 0; char tempStr[50] = {0}; bool givenCSN = false; - bool oldElite = false; + bool old_elite = false; bool elite = false; bool errors = false; uint8_t cmdp = 0; @@ -2122,7 +2122,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) { case 'e': dataLen = param_getstr(Cmd, cmdp, tempStr, sizeof(tempStr)); if (dataLen == 2) - oldElite = true; + old_elite = true; elite = true; cmdp++; break; @@ -2184,7 +2184,7 @@ static int CmdHFiClassCalcNewKey(const char *Cmd) { } } - HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, oldElite, true); + HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, old_elite, true); return PM3_SUCCESS; } From 682bded18abdee81a6064f5ef4dbc69c1f38de09 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 12 Apr 2020 11:14:10 +0200 Subject: [PATCH 66/66] starting with a application id file for desfire, for known application id:s. --- client/resources/aid_desfire.json | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 client/resources/aid_desfire.json diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json new file mode 100644 index 000000000..56caf14b6 --- /dev/null +++ b/client/resources/aid_desfire.json @@ -0,0 +1,18 @@ +[ + { + "AID": "D3494F", + "Vendor": "HID", + "Country": "United States", + "Name": "SIO DESFire Ev1", + "Description": "", + "Type": "" + }, + { + "AID": "4F5931", + "Vendor": "Transport of London", + "Country": "UK", + "Name": "Oyster Card", + "Description": "", + "Type": "" + }, +] \ No newline at end of file