From 3eee351f4fc5643bdc42338e2ae3f4664553136b Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Tue, 28 Apr 2020 18:16:52 +0200 Subject: [PATCH 01/26] Return PM3_SUCCESS if iso df names not supported --- client/src/cmdhfmfdes.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 65b02b5f8..d8185e96b 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -1268,6 +1268,7 @@ static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { // --- GET DF NAMES static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + *dfname_count=0; if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); @@ -1277,8 +1278,11 @@ static int handler_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) + if (res != PM3_SUCCESS){ + if (sw == status(MFDES_E_ILLEGAL_COMMAND_CODE)) return PM3_SUCCESS; return res; + } + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; *dfname_count = recv_len; From cdbe6bc35ba57fa5f42a8fa6750294c760238f08 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 09:27:55 +0200 Subject: [PATCH 02/26] fix: "emv scan" - now dont save in execution folder --- client/src/emv/cmdemv.c | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/client/src/emv/cmdemv.c b/client/src/emv/cmdemv.c index 65c9cafb2..c5b01e450 100644 --- a/client/src/emv/cmdemv.c +++ b/client/src/emv/cmdemv.c @@ -26,6 +26,7 @@ #include "dol.h" #include "ui.h" #include "emv_tags.h" +#include "fileutils.h" static int CmdHelp(const char *Cmd); @@ -1426,15 +1427,19 @@ static int CmdEMVScan(const char *Cmd) { bool GenACGPO = arg_get_lit(ctx, 9); bool MergeJSON = arg_get_lit(ctx, 10); + EMVCommandChannel channel = ECC_CONTACTLESS; if (arg_get_lit(ctx, 11)) channel = ECC_CONTACT; + PrintChannel(channel); + uint8_t psenum = (channel == ECC_CONTACT) ? 1 : 2; - uint8_t relfname[250] = {0}; - char *crelfname = (char *)relfname; - int relfnamelen = 0; - CLIGetStrWithReturn(ctx, 12, relfname, &relfnamelen); + + uint8_t filename[FILE_PATH_SIZE] = {0}; + int filenamelen = 0; + CLIGetStrWithReturn(ctx, 12, filename, &filenamelen); + CLIParserFree(ctx); if (!IfPm3Smartcard()) { @@ -1447,22 +1452,23 @@ static int CmdEMVScan(const char *Cmd) { SetAPDULogging(showAPDU); // current path + file name - if (!strstr(crelfname, ".json")) - strcat(crelfname, ".json"); + char *fname = newfilenamemcopy((char*)filename, ".json"); + if (fname == NULL) { + return PM3_EMALLOC; + } - char fname[strlen(get_my_executable_directory()) + strlen(crelfname) + 1]; - strcpy(fname, get_my_executable_directory()); - strcat(fname, crelfname); if (MergeJSON) { root = json_load_file(fname, 0, &error); if (!root) { PrintAndLogEx(ERR, "Json error on line %d: %s", error.line, error.text); + free(fname); return PM3_EFILE; } if (!json_is_object(root)) { PrintAndLogEx(ERR, "Invalid json format. root must be an object"); + free(fname); return PM3_EFILE; } } else { @@ -1480,6 +1486,7 @@ static int CmdEMVScan(const char *Cmd) { iso14a_card_select_t card; if (Hf14443_4aGetCardData(&card)) { + free(fname); return PM3_ERFTRANS; } @@ -1495,6 +1502,7 @@ static int CmdEMVScan(const char *Cmd) { smart_select(true, &card); if (!card.atr_len) { PrintAndLogEx(ERR, "Can't get ATR from a smart card."); + free(fname); return PM3_ERFTRANS; } @@ -1538,6 +1546,7 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't found any of EMV AID, exiting..."); tlvdb_free(tlvSelect); DropFieldEx(channel); + free(fname); return PM3_ERFTRANS; } @@ -1554,6 +1563,7 @@ static int CmdEMVScan(const char *Cmd) { if (!AIDlen) { PrintAndLogEx(INFO, "Can't select AID. EMV AID not found, exiting..."); DropFieldEx(channel); + free(fname); return PM3_ERFTRANS; } @@ -1573,6 +1583,7 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't select AID (%d), exiting...", res); tlvdb_free(tlvRoot); DropFieldEx(channel); + free(fname); return PM3_ERFTRANS; } @@ -1589,6 +1600,7 @@ static int CmdEMVScan(const char *Cmd) { JsonSaveTLVTree(root, root, "$.Application.FCITemplate", fci); else JsonSaveTLVTreeElm(root, "$.Application.FCITemplate", fci, true, true, false); + tlvdb_free(fci); // create transaction parameters @@ -1601,6 +1613,7 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't create PDOL TLV"); tlvdb_free(tlvRoot); DropFieldEx(channel); + free(fname); return PM3_ESOFT; } @@ -1611,6 +1624,7 @@ static int CmdEMVScan(const char *Cmd) { tlvdb_free(tlvRoot); free(pdol_data_tlv); DropFieldEx(channel); + free(fname); return PM3_ESOFT; } PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); @@ -1625,6 +1639,7 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "GPO error(%d): %4x, exiting...", res, sw); tlvdb_free(tlvRoot); DropFieldEx(channel); + free(fname); return PM3_ERFTRANS; } ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV); @@ -1749,9 +1764,12 @@ static int CmdEMVScan(const char *Cmd) { res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { PrintAndLogEx(ERR, "Can't save the file: %s", fname); + free(fname); return PM3_EFILE; } + PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", fname); + free(fname); // free json object json_decref(root); From 9ba03aec741c11ec9c56a99783a0c0e36310686f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 09:44:50 +0200 Subject: [PATCH 03/26] fix: "emv scan" - better fix for filename --- client/src/emv/cmdemv.c | 43 ++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/client/src/emv/cmdemv.c b/client/src/emv/cmdemv.c index c5b01e450..2f754ffc4 100644 --- a/client/src/emv/cmdemv.c +++ b/client/src/emv/cmdemv.c @@ -1384,8 +1384,6 @@ static int CmdEMVScan(const char *Cmd) { size_t ODAI_listlen = 0; uint16_t sw = 0; int res; - json_t *root; - json_error_t error; CLIParserContext *ctx; CLIParserInit(&ctx, "emv scan", @@ -1451,24 +1449,20 @@ static int CmdEMVScan(const char *Cmd) { SetAPDULogging(showAPDU); + json_t *root; + json_error_t error; + // current path + file name - char *fname = newfilenamemcopy((char*)filename, ".json"); - if (fname == NULL) { - return PM3_EMALLOC; - } - - if (MergeJSON) { - root = json_load_file(fname, 0, &error); + + root = json_load_file( (char*)filename, 0, &error); if (!root) { PrintAndLogEx(ERR, "Json error on line %d: %s", error.line, error.text); - free(fname); return PM3_EFILE; } if (!json_is_object(root)) { PrintAndLogEx(ERR, "Invalid json format. root must be an object"); - free(fname); return PM3_EFILE; } } else { @@ -1486,7 +1480,6 @@ static int CmdEMVScan(const char *Cmd) { iso14a_card_select_t card; if (Hf14443_4aGetCardData(&card)) { - free(fname); return PM3_ERFTRANS; } @@ -1502,7 +1495,6 @@ static int CmdEMVScan(const char *Cmd) { smart_select(true, &card); if (!card.atr_len) { PrintAndLogEx(ERR, "Can't get ATR from a smart card."); - free(fname); return PM3_ERFTRANS; } @@ -1546,7 +1538,6 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't found any of EMV AID, exiting..."); tlvdb_free(tlvSelect); DropFieldEx(channel); - free(fname); return PM3_ERFTRANS; } @@ -1563,7 +1554,6 @@ static int CmdEMVScan(const char *Cmd) { if (!AIDlen) { PrintAndLogEx(INFO, "Can't select AID. EMV AID not found, exiting..."); DropFieldEx(channel); - free(fname); return PM3_ERFTRANS; } @@ -1583,7 +1573,6 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't select AID (%d), exiting...", res); tlvdb_free(tlvRoot); DropFieldEx(channel); - free(fname); return PM3_ERFTRANS; } @@ -1613,7 +1602,6 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "Can't create PDOL TLV"); tlvdb_free(tlvRoot); DropFieldEx(channel); - free(fname); return PM3_ESOFT; } @@ -1624,7 +1612,6 @@ static int CmdEMVScan(const char *Cmd) { tlvdb_free(tlvRoot); free(pdol_data_tlv); DropFieldEx(channel); - free(fname); return PM3_ESOFT; } PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); @@ -1639,7 +1626,6 @@ static int CmdEMVScan(const char *Cmd) { PrintAndLogEx(ERR, "GPO error(%d): %4x, exiting...", res, sw); tlvdb_free(tlvRoot); DropFieldEx(channel); - free(fname); return PM3_ERFTRANS; } ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV); @@ -1761,15 +1747,24 @@ static int CmdEMVScan(const char *Cmd) { DropFieldEx(channel); - res = json_dump_file(root, fname, JSON_INDENT(2)); - if (res) { - PrintAndLogEx(ERR, "Can't save the file: %s", fname); + + if (MergeJSON == false) { + // create unique new name + char *fname = newfilenamemcopy((char*)filename, ".json"); + if (fname == NULL) { + return PM3_EMALLOC; + } + strcpy((char*)filename, fname); free(fname); + } + + res = json_dump_file(root, (char*)filename, JSON_INDENT(2)); + if (res) { + PrintAndLogEx(ERR, "Can't save the file: %s", filename); return PM3_EFILE; } - PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", fname); - free(fname); + PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", filename); // free json object json_decref(root); From 09188221a8239f1eac4d62fc1be7f06fda5c7f31 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 09:51:24 +0200 Subject: [PATCH 04/26] textual --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3975e12cb..494f1c01b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +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] + - Fix `emv scan` - now saves in current folder and uses unique names (@iceman1001) + - Fix pm3.sh - parse COM ports larger than one digit (@doegox) - Fix stack size and automatically use available space for BigBuf. Stack is now 5K (@slurdge) - Added Mifare MAD Card Holder Information decoding (@lukaskuzmiak) - Change Better precision for HF and LF voltage measurements and Add theremin.py script (@rosco) From 60c47a7e7d75d56c7f3a9bf7e6464a160d0241f3 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 17:29:34 +0200 Subject: [PATCH 05/26] textual --- client/src/ui.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/client/src/ui.c b/client/src/ui.c index 68f0eab24..05172c789 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -44,6 +44,7 @@ session_arg_t session; double CursorScaleFactor = 1; int PlotGridX = 0, PlotGridY = 0, PlotGridXdefault = 64, PlotGridYdefault = 64; uint32_t CursorCPos = 0, CursorDPos = 0; +double GraphPixelsPerPoint = 1.f; // How many visual pixels are between each sample point (x axis) static bool flushAfterWrite = 0; int GridOffset = 0; bool GridLocked = false; @@ -201,34 +202,34 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) { switch (level) { case ERR: if (session.emoji_mode == EMOJI) - strncpy(prefix, _RED_("[!!]") " :rotating_light: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("!!") "] :rotating_light: ", sizeof(prefix) - 1); else - strncpy(prefix, _RED_("[!!] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("!!") "] ", sizeof(prefix) - 1); stream = stderr; break; case FAILED: if (session.emoji_mode == EMOJI) - strncpy(prefix, _RED_("[-]") " :no_entry: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("-") "] :no_entry: ", sizeof(prefix) - 1); else - strncpy(prefix, _RED_("[-] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("-") "] ", sizeof(prefix) - 1); break; case DEBUG: - strncpy(prefix, _BLUE_("[#] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _BLUE_("#") "] ", sizeof(prefix) - 1); break; case HINT: - strncpy(prefix, _YELLOW_("[?] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _YELLOW_("?") "] ", sizeof(prefix) - 1); break; case SUCCESS: - strncpy(prefix, _GREEN_("[+] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _GREEN_("+") "] ", sizeof(prefix) - 1); break; case WARNING: if (session.emoji_mode == EMOJI) - strncpy(prefix, _CYAN_("[!]") " :warning: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _CYAN_("!") "] :warning: ", sizeof(prefix) - 1); else - strncpy(prefix, _CYAN_("[!] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _CYAN_("!") "] ", sizeof(prefix) - 1); break; case INFO: - strncpy(prefix, _YELLOW_("[=] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _YELLOW_("=") "] ", sizeof(prefix) - 1); break; case INPLACE: if (session.emoji_mode == EMOJI) { From 20c46d1af5c398e637b9164a9a48f590cee0c59d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 17:49:52 +0200 Subject: [PATCH 06/26] chg: in order to be able to upgrade fw on smartcard it must be available --- client/src/cmdmain.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdmain.c b/client/src/cmdmain.c index 1e9c8d257..2664ed3a1 100644 --- a/client/src/cmdmain.c +++ b/client/src/cmdmain.c @@ -258,7 +258,7 @@ static command_t CommandTable[] = { {"lf", CmdLF, AlwaysAvailable, "{ Low frequency commands... }"}, {"mem", CmdFlashMem, IfPm3Flash, "{ Flash Memory manipulation... }"}, {"reveng", CmdRev, AlwaysAvailable, "{ CRC calculations from RevEng software }"}, - {"sc", CmdSmartcard, IfPm3Smartcard, "{ Smart card ISO-7816 commands... }"}, + {"sc", CmdSmartcard, AlwaysAvailable, "{ Smart card ISO-7816 commands... }"}, {"script", CmdScript, AlwaysAvailable, "{ Scripting commands }"}, {"trace", CmdTrace, AlwaysAvailable, "{ Trace manipulation... }"}, {"usart", CmdUsart, IfPm3FpcUsartFromUsb, "{ USART commands... }"}, From e71e70bd9d9c3abf675e9a7a8cd325501b077df1 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 17:50:11 +0200 Subject: [PATCH 07/26] minor --- armsrc/i2c.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/armsrc/i2c.c b/armsrc/i2c.c index 7e7ba4605..82b4fdb10 100644 --- a/armsrc/i2c.c +++ b/armsrc/i2c.c @@ -626,9 +626,8 @@ int I2C_get_version(uint8_t *maj, uint8_t *min) { *maj = resp[0]; *min = resp[1]; return PM3_SUCCESS; - } else { - return PM3_EDEVNOTSUPP; } + return PM3_EDEVNOTSUPP; } // Will read response from smart card module, retries 3 times to get the data. From ce61b67910f216b7402dc0178decfb3ab0960a32 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 12 Jun 2020 18:01:06 +0200 Subject: [PATCH 08/26] Remove spurious color --- client/src/ui.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/ui.c b/client/src/ui.c index 05172c789..815d4a9d7 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -328,7 +328,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) { if (session.supports_colors) { printf(_YELLOW_("[=]") " Session log " _YELLOW_("%s") "\n", my_logfile_path); } else { - printf(_YELLOW_("[=]") " Session log %s\n", my_logfile_path); + printf("[=] Session log %s\n", my_logfile_path); } } From bb5c5889355bb8316cedcfa910fb18587628b333 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 12 Jun 2020 18:17:39 +0200 Subject: [PATCH 09/26] Fix colors detection under Windows (when no ref & when redirected IOs) --- client/src/proxmark3.c | 35 +++++++---------------------------- 1 file changed, 7 insertions(+), 28 deletions(-) diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index eea1718c3..621b09d22 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -32,9 +32,6 @@ #include "flash.h" #include "preferences.h" -// Used to enable/disable use of preferences json file -#define USE_PREFERENCE_FILE - #define BANNERMSG1 " :snowflake: iceman@icesql.net" #define BANNERMSG2 " https://github.com/rfidresearchgroup/proxmark3/" #define BANNERMSG3 " bleeding edge :coffee:" @@ -632,8 +629,7 @@ finish2: return ret; } -#ifndef USE_PREFERENCE_FILE - +/* // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] // "VirtualTerminalLevel"=dword:00000001 @@ -688,8 +684,7 @@ static bool DetectWindowsAnsiSupport(void) { #endif return ret; } - -#endif +*/ int main(int argc, char *argv[]) { srand(time(0)); @@ -912,7 +907,6 @@ int main(int argc, char *argv[]) { return 1; } -#ifdef USE_PREFERENCE_FILE // Load Settings and assign // This will allow the command line to override the settings.json values preferences_load(); @@ -921,28 +915,24 @@ int main(int argc, char *argv[]) { g_debugMode = session.client_debug_level; // settings_save (); // End Settings -#endif - -#ifndef USE_PREFERENCE_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); -#if defined(__linux__) || defined(__APPLE__) // it's okay to use color if: // * Linux or OSX // * Not redirected to a file but printed to term // For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb": // struct stat tmp_stat; // if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO)) -#ifdef USE_PREFERENCE_FILE if (!session.preferences_loaded) { if (session.stdinOnTTY && session.stdoutOnTTY) { +#if defined(__linux__) || defined(__APPLE__) session.supports_colors = true; session.emoji_mode = EMOJI; +#else + session.supports_colors = DetectWindowsAnsiSupport(); + session.emoji_mode = ALTTEXT; +#endif } } else { // even if prefs, we disable colors if stdin or stdout is not a TTY @@ -951,14 +941,7 @@ int main(int argc, char *argv[]) { session.emoji_mode = ALTTEXT; } } -#else - if (session.stdinOnTTY && session.stdoutOnTTY) { - session.supports_colors = true; - session.emoji_mode = EMOJI; - } -#endif -#endif // Let's take a baudrate ok for real UART, USB-CDC & BT don't use that info anyway if (speed == 0) speed = USART_BAUD_RATE; @@ -1013,7 +996,6 @@ int main(int argc, char *argv[]) { if (!script_cmds_file && !script_cmd && session.stdinOnTTY && session.stdoutOnTTY && !flash_mode) showBanner(); -#ifdef USE_PREFERENCE_FILE // Save settings if not loaded 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 @@ -1034,7 +1016,6 @@ int main(int argc, char *argv[]) { PrintAndLogEx(WARNING,"Proxmark3 not ready to set debug level"); } */ -#endif #ifdef HAVE_GUI @@ -1061,9 +1042,7 @@ int main(int argc, char *argv[]) { CloseProxmark(); } -#ifdef USE_PREFERENCE_FILE if (session.window_changed) // Plot/Overlay moved or resized preferences_save(); -#endif exit(EXIT_SUCCESS); } From 30c0345c31dc93d9f3f5d47f6dc81f57f5d0f888 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 12 Jun 2020 18:21:03 +0200 Subject: [PATCH 10/26] Fix fix colors --- client/src/proxmark3.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index 621b09d22..8228429b0 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -629,7 +629,6 @@ finish2: return ret; } -/* // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] // "VirtualTerminalLevel"=dword:00000001 @@ -637,9 +636,9 @@ finish2: // [HKEY_CURRENT_USER\Console] // "ForceV2"=dword:00000001 +#if defined(_WIN32) static bool DetectWindowsAnsiSupport(void) { bool ret = false; -#if defined(_WIN32) HKEY hKey = NULL; bool virtualTerminalLevelSet = false; bool forceV2Set = false; @@ -681,10 +680,9 @@ static bool DetectWindowsAnsiSupport(void) { } // If both VirtualTerminalLevel and ForceV2 is set, AnsiColor should work ret = virtualTerminalLevelSet && forceV2Set; -#endif return ret; } -*/ +#endif int main(int argc, char *argv[]) { srand(time(0)); @@ -929,9 +927,12 @@ int main(int argc, char *argv[]) { #if defined(__linux__) || defined(__APPLE__) session.supports_colors = true; session.emoji_mode = EMOJI; -#else +#elif defined(_WIN32) session.supports_colors = DetectWindowsAnsiSupport(); session.emoji_mode = ALTTEXT; +#else + session.supports_colors = false; + session.emoji_mode = ALTTEXT; #endif } } else { From 8c5be2678fdb5de384181e38e04c8dc812712a7f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 12 Jun 2020 19:45:18 +0200 Subject: [PATCH 11/26] Yet another color management, settings autodetection done earlier --- client/src/preferences.c | 2 -- client/src/proxmark3.c | 53 ++++++++++++++++++++-------------------- 2 files changed, 26 insertions(+), 29 deletions(-) diff --git a/client/src/preferences.c b/client/src/preferences.c index 4313c9456..8ddd0f150 100644 --- a/client/src/preferences.c +++ b/client/src/preferences.c @@ -52,9 +52,7 @@ int preferences_load(void) { session.overlay.y = 60 + session.plot.y + session.plot.h; session.overlay.h = 200; session.overlay.w = session.plot.w; - session.emoji_mode = ALIAS; session.show_hints = false; - session.supports_colors = false; // setDefaultPath (spDefault, ""); // setDefaultPath (spDump, ""); diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index 8228429b0..e13c79591 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -726,6 +726,28 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); + // color management: + // 1. default = no color + // 2. enable colors if OS seems to support colors and if stdin/stdout aren't redirected + // 3. load prefs if available, overwrite colors choice if needed + // 4. disable colors anyway if stdin/stdout are redirected + // + // For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb": + // struct stat tmp_stat; + // if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO)) + session.stdinOnTTY = isatty(STDIN_FILENO); + session.stdoutOnTTY = isatty(STDOUT_FILENO); + session.supports_colors = false; + session.emoji_mode = ALTTEXT; + if (session.stdinOnTTY && session.stdoutOnTTY) { +#if defined(__linux__) || defined(__APPLE__) + session.supports_colors = true; + session.emoji_mode = EMOJI; +#elif defined(_WIN32) + session.supports_colors = DetectWindowsAnsiSupport(); + session.emoji_mode = ALTTEXT; +#endif + } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { @@ -914,33 +936,10 @@ int main(int argc, char *argv[]) { // settings_save (); // End Settings - session.stdinOnTTY = isatty(STDIN_FILENO); - session.stdoutOnTTY = isatty(STDOUT_FILENO); - // it's okay to use color if: - // * Linux or OSX - // * Not redirected to a file but printed to term - // For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb": - // struct stat tmp_stat; - // if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO)) - if (!session.preferences_loaded) { - if (session.stdinOnTTY && session.stdoutOnTTY) { -#if defined(__linux__) || defined(__APPLE__) - session.supports_colors = true; - session.emoji_mode = EMOJI; -#elif defined(_WIN32) - session.supports_colors = DetectWindowsAnsiSupport(); - session.emoji_mode = ALTTEXT; -#else - session.supports_colors = false; - session.emoji_mode = ALTTEXT; -#endif - } - } else { - // even if prefs, we disable colors if stdin or stdout is not a TTY - if ((! session.stdinOnTTY) || (! session.stdoutOnTTY)) { - session.supports_colors = false; - session.emoji_mode = ALTTEXT; - } + // even if prefs, we disable colors if stdin or stdout is not a TTY + if ((! session.stdinOnTTY) || (! session.stdoutOnTTY)) { + session.supports_colors = false; + session.emoji_mode = ALTTEXT; } // Let's take a baudrate ok for real UART, USB-CDC & BT don't use that info anyway From 020c6882ce42440ef49e5fe48010469f44f3b0d8 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 12 Jun 2020 19:52:13 +0200 Subject: [PATCH 12/26] colors --- client/src/ui.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/ui.c b/client/src/ui.c index 815d4a9d7..04e002950 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -326,7 +326,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) { } else { if (session.supports_colors) { - printf(_YELLOW_("[=]") " Session log " _YELLOW_("%s") "\n", my_logfile_path); + printf("["_YELLOW_("=")"] Session log " _YELLOW_("%s") "\n", my_logfile_path); } else { printf("[=] Session log %s\n", my_logfile_path); } From 9c6ce5be50f78992ca317219011f01a9386c279e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 22:35:08 +0200 Subject: [PATCH 13/26] chg: "hf mf cwipe" - speed up using backdoor wipe cmd --- client/src/mifare/mifarehost.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 8e15cb509..393495152 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -865,7 +865,7 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_ int mfCWipe(uint8_t *uid, uint8_t *atqa, uint8_t *sak) { uint8_t block0[16] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBE, 0xAF}; - uint8_t blockD[16] = {0x00}; + //uint8_t blockD[16] = {0x00}; uint8_t blockK[16] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x08, 0x77, 0x8F, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; uint8_t params = MAGIC_SINGLE; @@ -891,8 +891,8 @@ int mfCWipe(uint8_t *uid, uint8_t *atqa, uint8_t *sak) { } else { if (mfIsSectorTrailer(blockNo)) res = mfCSetBlock(blockNo, blockK, NULL, params); - else - res = mfCSetBlock(blockNo, blockD, NULL, params); +// else +// res = mfCSetBlock(blockNo, blockD, NULL, params); } if (res == PM3_SUCCESS) From 94403bee598407eca83c900a525548cc6499e1cf Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 12 Jun 2020 22:49:42 +0200 Subject: [PATCH 14/26] textual --- client/src/emv/emv_pk.c | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/client/src/emv/emv_pk.c b/client/src/emv/emv_pk.c index 3331e50a5..ee354e24d 100644 --- a/client/src/emv/emv_pk.c +++ b/client/src/emv/emv_pk.c @@ -32,8 +32,7 @@ #include "fileutils.h" #include "pm3_cmd.h" -#define BCD(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : \ - -1) +#define BCD(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : -1) #define HEX(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : \ ((c) >= 'A' && (c) <= 'F') ? ((c) - 'A' + 10) : \ @@ -93,7 +92,6 @@ static ssize_t emv_pk_read_ymv(char *buf, size_t buflen, unsigned *ymv) { if (buf == NULL) return 0; - int i; unsigned char temp[3]; char *p = buf; @@ -102,7 +100,7 @@ static ssize_t emv_pk_read_ymv(char *buf, size_t buflen, unsigned *ymv) { while ((*p == ' ') && (p < (buf + buflen - 1))) p++; - for (i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) { int c1, c2; c1 = BCD(*p); if (c1 == -1) @@ -164,7 +162,6 @@ static ssize_t emv_pk_read_string(char *buf, size_t buflen, char *str, size_t si return (p - buf); } - struct emv_pk *emv_pk_parse_pk(char *buf, size_t buflen) { struct emv_pk *r = calloc(1, sizeof(*r)); ssize_t l; @@ -264,22 +261,22 @@ static size_t emv_pk_write_str(char *out, size_t outlen, const char *str) { } char *emv_pk_dump_pk(const struct emv_pk *pk) { + size_t outpos = 0; size_t outsize = 1024; /* should be enough */ char *out = malloc(outsize); /* should be enough */ - size_t outpos = 0; - size_t rc; - if (!out) return NULL; - rc = emv_pk_write_bin(out + outpos, outsize - outpos, pk->rid, 5); + size_t rc = emv_pk_write_bin(out + outpos, outsize - outpos, pk->rid, 5); if (rc == 0) goto err; + outpos += rc; rc = emv_pk_write_bin(out + outpos, outsize - outpos, &pk->index, 1); if (rc == 0) goto err; + outpos += rc; if (outpos + 7 > outsize) @@ -504,21 +501,23 @@ struct emv_pk *emv_pk_get_ca_pk(const unsigned char *rid, unsigned char idx) { if (!pk) return NULL; - printf("Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zu bits...", + bool isok = emv_pk_verify(pk); + + PrintAndLogEx(INFO, "Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zu bits. ( %s )", pk->rid[0], pk->rid[1], pk->rid[2], pk->rid[3], pk->rid[4], pk->index, - pk->mlen * 8); + pk->mlen * 8, + (isok) ? _GREEN_("ok") : _RED_("failed") + ); - if (emv_pk_verify(pk)) { - printf("OK\n"); + if (isok) { return pk; - } + } - printf("Failed!\n"); emv_pk_free(pk); return NULL; } From 25fb6df229bc3a34cfd20ab092f510c200f5c25f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 11 Jun 2020 12:38:07 +0200 Subject: [PATCH 15/26] Android cross-compilation to client cmake --- CHANGELOG.md | 1 + client/CMakeLists.txt | 84 ++++++++++++++++++++++++++++++++++++++--- client/src/cmdhflegic.c | 2 +- 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 494f1c01b..7f3d8c886 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] + - Add Android cross-compilation to client cmake (@dxl, @doegox) - Fix `emv scan` - now saves in current folder and uses unique names (@iceman1001) - Fix pm3.sh - parse COM ports larger than one digit (@doegox) - Fix stack size and automatically use available space for BigBuf. Stack is now 5K (@slurdge) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 8db8ebf9c..0de34d58f 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -4,6 +4,13 @@ # On Proxspace 3.3 or less, you need to install cmake: # pacman -S mingw-w64-x86_64-cmake # /mingw64/bin/cmake -G"MSYS Makefiles" .. +# +# Android cross-compilation: +# cmake \ +# -DCMAKE_TOOLCHAIN_FILE=/build/cmake/android.toolchain.cmake \ +# -DANDROID_ABI=armeabi-v7a \ +# -DANDROID_NATIVE_API_LEVEL=android-19 \ +# -DSKIPBT=1 -DSKIPPYTHON=1 -DSKIPPTHREAD=1 .. cmake_minimum_required(VERSION 3.10) project(proxmark3) @@ -49,21 +56,75 @@ if (NOT SKIPPYTHON EQUAL 1) pkg_search_module(PYTHON3EMBED QUIET python3-embed) endif (NOT SKIPPYTHON EQUAL 1) +# If build on android cross, we need to init source and build. +if (ANDROID) + set(CFLAGS_EXTERNAL_LIB CFLAGS=--target=${CMAKE_C_COMPILER_TARGET}) + include(ExternalProject) +endif (ANDROID) + if (NOT SKIPREADLINE EQUAL 1) if (APPLE) find_path(READLINE_INCLUDE_DIRS readline/readline.h /usr/local/opt/readline/include /opt/local/include /opt/include /usr/local/include /usr/include NO_DEFAULT_PATH) - endif (APPLE) - find_path(READLINE_INCLUDE_DIRS readline/readline.h) - - if (APPLE) find_library(READLINE_LIBRARIES readline /usr/local/opt/readline/lib /opt/local/lib /opt/lib /usr/local/lib /usr/lib NO_DEFAULT_PATH) endif (APPLE) - find_library(READLINE_LIBRARIES readline) + if (ANDROID) + ExternalProject_Add(ncurses + URL http://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.0.tar.gz + PREFIX deps/ncurses + DOWNLOAD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/ncurses + CONFIGURE_COMMAND ./configure CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} --host=arm + BUILD_IN_SOURCE ON + BUILD_COMMAND make -j2 libs + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(ncurses configure build install) + + ExternalProject_Add(readline + URL ftp://ftp.gnu.org/gnu/readline/readline-7.0.tar.gz + PREFIX deps/readline + DOWNLOAD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/readline + CONFIGURE_COMMAND ./configure CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} --host=arm --enable-static + BUILD_IN_SOURCE ON + BUILD_COMMAND make -j2 + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(readline configure build install) + set(READLINE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/deps/readline/src/) + set(READLINE_LIBRARIES ${CMAKE_CURRENT_BINARY_DIR}/deps/readline/src/readline/libreadline.a ${CMAKE_CURRENT_BINARY_DIR}/deps/ncurses/src/ncurses/lib/libncurses.a) + else (ANDROID) + find_path(READLINE_INCLUDE_DIRS readline/readline.h) + find_library(READLINE_LIBRARIES readline) + endif (ANDROID) if (READLINE_INCLUDE_DIRS AND READLINE_LIBRARIES) set(READLINE_FOUND ON) endif (READLINE_INCLUDE_DIRS AND READLINE_LIBRARIES) endif (NOT SKIPREADLINE EQUAL 1) +if(ANDROID) + set(BZIP2_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2) + ExternalProject_Add(bzip2 + GIT_REPOSITORY https://android.googlesource.com/platform/external/bzip2 + GIT_TAG platform-tools-30.0.2 + PREFIX deps/bzip2 + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/bzip2 + CONFIGURE_COMMAND mkdir -p ${BZIP2_BUILD_DIR} && git archive --format tar HEAD | tar -C ${BZIP2_BUILD_DIR} -x + BUILD_IN_SOURCE ON + BUILD_COMMAND make -C ${BZIP2_BUILD_DIR} -j4 CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} libbz2.a + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(bzip2 configure build install) + set(BZIP2_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2) + set(BZIP2_LIBRARIES ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2/libbz2.a) +else() + set(BZIP2_LIBRARIES bz2) +endif(ANDROID) +if (BZIP2_LIBRARIES) + set(BZIP2_FOUND ON) +endif (BZIP2_LIBRARIES) + add_subdirectory(${PM3_ROOT}/client/deps deps) set (TARGET_SOURCES @@ -268,6 +329,12 @@ if (NOT SKIPREADLINE EQUAL 1) set(ADDITIONAL_LNK ${READLINE_LIBRARIES} ${ADDITIONAL_LNK}) endif (READLINE_FOUND) endif(NOT SKIPREADLINE EQUAL 1) +if (BZIP2_FOUND) + set(ADDITIONAL_DIRS ${BZIP2_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) + set(ADDITIONAL_LNK ${BZIP2_LIBRARIES} ${ADDITIONAL_LNK}) +else (BZIP2_FOUND) + message(FATAL_ERROR "Bzip2 not found") +endif (BZIP2_FOUND) message("===================================================================") if (SKIPQT EQUAL 1) @@ -320,6 +387,12 @@ add_executable(proxmark3 ) target_compile_options(proxmark3 PUBLIC -Wall -Werror -O3) +if (ANDROID) + if (NOT SKIPREADLINE EQUAL 1) + add_dependencies(proxmark3 ncurses readline) + endif (NOT SKIPREADLINE EQUAL 1) + add_dependencies(proxmark3 bzip2) +endif (ANDROID) if (MINGW) # Mingw uses by default Microsoft printf, we want the GNU printf (e.g. for %z) @@ -357,7 +430,6 @@ find_library(pm3rrg_rdv4_hardnested REQUIRED) find_library(pm3rrg_rdv4_whereami REQUIRED) target_link_libraries(proxmark3 PRIVATE - bz2 m pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index f5ba787ad..a91c1a418 100644 --- a/client/src/cmdhflegic.c +++ b/client/src/cmdhflegic.c @@ -12,7 +12,7 @@ #include // for Mingw readline #include // tolower -#ifndef ANDROID +#ifdef HAVE_READLINE #include #endif From e8c88d47ef69d2975cf161a06d2145f9adb9bf74 Mon Sep 17 00:00:00 2001 From: Conlan Date: Fri, 12 Jun 2020 20:01:55 -0400 Subject: [PATCH 16/26] Additional CharlieCard Key --- client/dictionaries/mfc_default_keys.dic | 1 + 1 file changed, 1 insertion(+) diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index 26f1f938e..cc68b0d88 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -605,6 +605,7 @@ d58023ba2bdc # charlie 62ced42a6d87 # charlie 2548a443df28 # charlie 2ed3b15e7c0f # charlie +f66224ee1e89 # charlie # 60012e9ba3fa # From 5adc8e876a0d3e3f5b69ac228430a01cc510eab9 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 14:19:21 +0200 Subject: [PATCH 17/26] Fix DES authentification and format picc --- client/src/cmdhfmfdes.c | 1424 +++++++++++++++++----------- client/src/mifare/desfire_crypto.c | 84 +- client/src/mifare/desfire_crypto.h | 6 +- include/protocols.h | 1 + 4 files changed, 967 insertions(+), 548 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index d8185e96b..520a73fe6 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -7,6 +7,8 @@ //----------------------------------------------------------------------------- // High frequency MIFARE Desfire commands //----------------------------------------------------------------------------- +// Code heavily modified by B.Kerler :) + #include "cmdhfmfdes.h" #include @@ -32,13 +34,22 @@ #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 -struct desfire_key defaultkey = {0}; -static desfirekey_t sessionkey = &defaultkey; +struct desfire_key default_key = {0}; -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 }; +uint8_t desdefaultkeys[3][8]= {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, //Official + {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47}, + {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07}}; + +uint8_t aesdefaultkeys[5][16]= {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, //Official, TRF7970A + {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}, // TRF7970A + {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, // TRF7970A + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f}}; + +uint8_t k3kdefaultkeys[1][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}}; + +struct desfire_tag mf_state={.session_key=NULL,.authentication_scheme=AS_LEGACY,.authenticated_key_no=NOT_YET_AUTHENTICATED,.crypto_buffer=NULL,.crypto_buffer_size=0,.selected_application=0}; +static desfiretag_t tag=&mf_state; typedef struct { uint8_t mode; @@ -48,6 +59,8 @@ typedef struct { uint8_t key[24]; } PACKED mfdes_authinput_t; +static mfdes_authinput_t currentauth[0xF]={{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1}}; + typedef struct mfdes_auth_res { uint8_t sessionkeylen; uint8_t sessionkey[24]; @@ -557,10 +570,6 @@ 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) { - PrintAndLogEx(DEBUG, "DEST=NULL"); - return PM3_EINVARG; - }*/ if (sw == NULL) { PrintAndLogEx(DEBUG, "SW=NULL"); return PM3_EINVARG; @@ -642,10 +651,12 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { return DESFIRE_UNKNOWN; } -int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool defaultkey) { +int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) { // 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 + tag->authenticated_key_no=NOT_YET_AUTHENTICATED; + tag->session_key = NULL; mbedtls_aes_context ctx; @@ -669,27 +680,8 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, value = prng_successor(ng, 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 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}; - - // Part 1 - if (defaultkey) { - if (payload->algo == MFDES_AUTH_DES) { - memcpy(keybytes, PICC_MASTER_KEY8, 8); - } 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); - } + memcpy(keybytes, payload->key, payload->keylen); struct desfire_key dkey = {0}; desfirekey_t key = &dkey; @@ -706,11 +698,17 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, } uint8_t subcommand = MFDES_AUTHENTICATE; + tag->authentication_scheme=AS_LEGACY; if (payload->mode == MFDES_AUTH_AES) + { subcommand = MFDES_AUTHENTICATE_AES; - else if (payload->mode == MFDES_AUTH_ISO) + tag->authentication_scheme=AS_NEW; + } + else if (payload->mode == MFDES_AUTH_ISO) { subcommand = MFDES_AUTHENTICATE_ISO; + tag->authentication_scheme = AS_NEW; + } int recv_len = 0; uint16_t sw = 0; @@ -756,7 +754,6 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, memcpy(encRndB, recv_data + 2, rndlen); } - // Part 3 if (payload->algo == MFDES_ALGO_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { @@ -875,7 +872,8 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, } // Part 4 - Desfire_session_key_new(RndA, RndB, key, sessionkey); + tag->session_key=&default_key; + Desfire_session_key_new(RndA, RndB, key, tag->session_key); if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndA, recv_data, rndlen); @@ -909,7 +907,12 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, } rpayload->sessionkeylen = payload->keylen; - memcpy(rpayload->sessionkey, sessionkey->data, rpayload->sessionkeylen); + memcpy(rpayload->sessionkey, tag->session_key->data, rpayload->sessionkeylen); + memset(tag->ivect, 0, MAX_CRYPTO_BLOCK_SIZE); + tag->authenticated_key_no=payload->keyno; + if (tag->authentication_scheme==AS_NEW) { + cmac_generate_subkeys(tag->session_key); + } return PM3_SUCCESS; } @@ -952,6 +955,8 @@ void AuthToError(int error) { break; } } + + // -- test if card supports 0x0A static int test_desfire_authenticate() { uint8_t data[] = {0x00}; @@ -1012,11 +1017,19 @@ static int handler_desfire_freemem(uint32_t *free_mem) { uint16_t sw = 0; uint8_t fmem[4] = {0}; + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) return res; + size_t dlen=recv_len; + p=mifare_cryto_postprocess_data(tag, apdu.data, &dlen, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; @@ -1024,6 +1037,121 @@ static int handler_desfire_freemem(uint32_t *free_mem) { return res; } +static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_algo, uint8_t* old_key, int old_algo, int aes_version) +{ + key_no &= 0x0F; + + /* + * Because new crypto methods can be setup only at application creation, + * changing the card master key to one of them require a key_no tweak. + */ + if (0x000000 == tag->selected_application) { + switch (new_algo) { + case MFDES_ALGO_DES: + break; + case MFDES_ALGO_3K3DES: + key_no |= 0x40; + break; + case MFDES_ALGO_AES: + key_no |= 0x80; + break; + } + } + + uint8_t data[24*4] = {key_no}; + sAPDU apdu = {0x90, MFDES_CHANGE_KEY, 0x00, 0x00, 0x01, data}; // 0xC4 + + int new_key_length; + switch (new_algo) { + case MFDES_ALGO_DES: + case MFDES_ALGO_AES: + new_key_length = 16; + break; + case MFDES_ALGO_3K3DES: + new_key_length = 24; + break; + } + + int __cmd_n=0; + memcpy(data + __cmd_n + 1, new_key, new_key_length); + + if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { + if (old_key) { + for (int n = 0; n < new_key_length; n++) { + data[__cmd_n + 1 + n] ^= old_key[n]; + } + } + } + + __cmd_n += new_key_length; + + if (new_algo == MFDES_ALGO_AES){ + data[__cmd_n+1] = aes_version; + __cmd_n+=1; + } + + if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { + switch (tag->authentication_scheme) { + case AS_LEGACY: + iso14443a_crc_append(data + 1, __cmd_n); + __cmd_n += 2; + iso14443a_crc(new_key, new_key_length, data + __cmd_n); + __cmd_n += 2; + break; + case AS_NEW: + desfire_crc32_append(data+1, __cmd_n); + __cmd_n += 4; + + desfire_crc32(new_key, new_key_length, data + __cmd_n); + __cmd_n += 4; + break; + } + } else { + switch (tag->authentication_scheme) { + case AS_LEGACY: + iso14443a_crc_append(data + 1, __cmd_n); + __cmd_n += 2; + break; + case AS_NEW: + desfire_crc32_append(data, __cmd_n); + __cmd_n += 4; + break; + } + } + + uint8_t *p = mifare_cryto_preprocess_data(tag, data+1, (size_t*)&__cmd_n, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); + apdu.Lc=(uint8_t)__cmd_n+1; + apdu.data=p; + + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS) + { + PrintAndLogEx(WARNING, _RED_(" Can't change key -> %s"),GetErrorString(res, &sw)); + DropField(); + return res; + } + + size_t sn = recv_len; + p = mifare_cryto_postprocess_data(tag, data, &sn, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); + + if (!p) + return PM3_ESOFT; + + /* + * If we changed the current authenticated key, we are not authenticated + * anymore. + */ + if (key_no == tag->authenticated_key_no) { + free(tag->session_key); + tag->session_key = NULL; + } + + return 0; +} + // --- GET SIGNATURE static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, nxp_cardtype_t card_type) { (void)card_type; @@ -1098,6 +1226,7 @@ static int handler_desfire_signature(uint8_t *signature, size_t *signature_len) 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); @@ -1114,24 +1243,16 @@ static int handler_desfire_signature(uint8_t *signature, size_t *signature_len) } // --- KEY SETTING -static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { +static int desfire_print_keysetting(uint8_t key_settings, mifare_des_authalgo_t algo) { PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); // 2 MSB denotes const char *str = " Max key number and type : %d, " _YELLOW_("%s"); - switch (num_keys >> 6) { - case 0: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "(3)DES"); - break; - case 1: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "3K3DES"); - break; - case 2: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "AES"); - break; - default: - break; - } + + if (algo==MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo==MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo==MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); + //PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys & 0x3F); PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(SUCCESS, " Changekey Access rights"); @@ -1160,7 +1281,7 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { return PM3_SUCCESS; } -static int handler_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { +static int handler_desfire_getkeysettings(uint8_t *key_settings, uint8_t *num_keys) { if (key_settings == NULL) { PrintAndLogEx(DEBUG, "KEY_SETTINGS=NULL"); return PM3_EINVARG; @@ -1170,6 +1291,7 @@ static int handler_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) 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}; @@ -1210,6 +1332,25 @@ static int handler_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { return res; } +static int handler_desfire_getuid(uint8_t *uid) { + if (uid == NULL) { + PrintAndLogEx(DEBUG, "UID=NULL"); + return PM3_EINVARG; + } + sAPDU apdu = {0x90, MFDES_GET_UID, 0x00, 0x00, 0x00, NULL}; //0x51 + int recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, false, uid, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + + return res; +} + static int handler_desfire_commit_transaction() { sAPDU apdu = {0x90, MFDES_COMMIT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xC7 int recv_len = 0; @@ -1303,10 +1444,32 @@ static int handler_desfire_select_application(uint8_t *aid) { DropField(); return res; } + memcpy(&tag->selected_application,aid,3); return PM3_SUCCESS; } -// none, verified +static int key_setting_to_algo(uint8_t aid[3],uint8_t* key_setting, mifare_des_authalgo_t* algo){ + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + + uint8_t num_keys = 0; + res = handler_desfire_getkeysettings(key_setting, &num_keys); + if (res==PM3_SUCCESS){ + switch (num_keys >> 6){ + case 0: + *algo=MFDES_ALGO_DES; + break; + case 1: + *algo=MFDES_ALGO_3K3DES; + break; + case 2: + *algo=MFDES_ALGO_AES; + break; + } + } + return res; +} + static int handler_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); @@ -1399,10 +1562,16 @@ static int handler_desfire_deleteapp(uint8_t *aid) { return res; } -static int handler_desfire_credit(mfdes_value_t *value) { +static int handler_desfire_credit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x0C uint16_t sw = 0; int recvlen = 0; + + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't credit value -> %s"), GetErrorString(res, &sw)); @@ -1412,10 +1581,16 @@ static int handler_desfire_credit(mfdes_value_t *value) { return res; } -static int handler_desfire_limitedcredit(mfdes_value_t *value) { +static int handler_desfire_limitedcredit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_LIMITED_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x1C uint16_t sw = 0; int recvlen = 0; + + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't credit limited value -> %s"), GetErrorString(res, &sw)); @@ -1425,10 +1600,16 @@ static int handler_desfire_limitedcredit(mfdes_value_t *value) { return res; } -static int handler_desfire_debit(mfdes_value_t *value) { +static int handler_desfire_debit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_DEBIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0xDC uint16_t sw = 0; int recvlen = 0; + + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't debit value -> %s"), GetErrorString(res, &sw)); @@ -1438,42 +1619,59 @@ static int handler_desfire_debit(mfdes_value_t *value) { return res; } -static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) { +static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint8_t cs) { if (data->fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_READ_DATA, 0x00, 0x00, 1 + 3 + 3, (uint8_t *)data}; // 0xBD if (type == MFDES_RECORD_FILE) apdu.INS = MFDES_READ_RECORDS; //0xBB uint16_t sw = 0; int resplen = 0; + + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, false, data->data, &resplen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't read data -> %s"), GetErrorString(res, &sw)); DropField(); return res; } - data->length[2] = (uint8_t)(resplen & 0xFF); - data->length[1] = (uint8_t)((resplen >> 8) & 0xFF); - data->length[0] = (uint8_t)((resplen >> 16) & 0xFF); + + size_t dlen=resplen; + p=mifare_cryto_postprocess_data(tag, data->data, &dlen, cs|CMAC_COMMAND|CMAC_VERIFY|MAC_VERIFY); + if (dlen!=-1) resplen=dlen; memcpy(data->length, &resplen, 3); + + return res; } -static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen) { +static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen, uint8_t cs) { if (value->fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_VALUE, 0x00, 0x00, 0x01, &value->fileno}; // 0xBD uint16_t sw = 0; *resplen = 0; + + size_t plen=apdu.Lc; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); + apdu.Lc=(uint8_t)plen; + apdu.data=p; + int res = send_desfire_cmd(&apdu, false, value->value, resplen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't read data -> %s"), GetErrorString(res, &sw)); DropField(); return res; } + size_t dlen=(size_t)resplen; + p=mifare_cryto_postprocess_data(tag, value->value, &dlen, cs|CMAC_COMMAND|CMAC_VERIFY|MAC_VERIFY); return res; } -static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) { +static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint8_t cs) { /* LC FN OF OF OF LN LN LN DD DD DD 90 3d 00 00 16 01 00 00 00 0f 00 00 00 0f 20 00 3b 00 34 04 06 e1 04 0f fe 00 00 00 90 3d 00 00 09 02 00 00 00 02 00 00 00 00 00 @@ -1507,9 +1705,15 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) tmp[5] = (datasize >> 8) & 0xFF; tmp[6] = (datasize >> 16) & 0xFF; - memcpy(&tmp[7], &data->data[pos], datasize); + + size_t plen=datasize; + uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)&data->data[pos],&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + if (plen!=-1) datasize=(uint8_t)plen; + memcpy(&tmp[7], p, datasize); + apdu.Lc = datasize + 1 + 3 + 3; + res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't write data -> %s"), GetErrorString(res, &sw)); @@ -1653,13 +1857,13 @@ int getKeySettings(uint8_t *aid) { // CARD MASTER KEY //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + mifare_des_authalgo_t algo; + res=key_setting_to_algo(aid,&key_setting,&algo); + if (res == PM3_SUCCESS) { // number of Master keys (0x01) PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); @@ -1674,20 +1878,9 @@ int getKeySettings(uint8_t *aid) { 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; - } + if (algo==MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo==MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo==MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); uint8_t cmk_num_versions = 0; if (handler_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { @@ -1720,9 +1913,10 @@ int getKeySettings(uint8_t *aid) { // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + mifare_des_authalgo_t algo; + res=key_setting_to_algo(aid,&key_setting,&algo); if (res == PM3_SUCCESS) { - desfire_print_keysetting(key_setting, num_keys); + desfire_print_keysetting(key_setting, algo); } else { PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); } @@ -1778,6 +1972,129 @@ static void swap16(uint8_t *data) { data[1] = tmp; }; +int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t* aid, uint8_t* key, int cmdKeyNo, mfdes_auth_res_t* rpayload) +{ + 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_EINVARG; + } + break; + case MFDES_AUTH_ISO: + if (cmdAuthAlgo != MFDES_ALGO_3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); + 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_EINVARG; + } + break; + case MFDES_AUTH_PICC: + if (cmdAuthAlgo != MFDES_AUTH_DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); + return PM3_EINVARG; + } + break; + default: + PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); + return PM3_EINVARG; + } + + int keylength=16; + + switch (cmdAuthAlgo) { + case MFDES_ALGO_3DES: + keylength = 16; + break; + case MFDES_ALGO_3K3DES: + keylength = 24; + break; + case MFDES_ALGO_AES: + keylength = 16; + break; + default: + cmdAuthAlgo = MFDES_ALGO_DES; + keylength = 8; + break; + } + + // KEY + int res = handler_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 = handler_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; + } + + mfdes_authinput_t payload; + payload.keylen = keylength; + memcpy(payload.key, key, keylength); + payload.mode = cmdAuthMode; + payload.algo = cmdAuthAlgo; + payload.keyno = cmdKeyNo; + + int error = handler_desfire_auth(&payload, rpayload); + if (error == PM3_SUCCESS) { + memcpy(¤tauth[payload.keyno], &payload, sizeof(mfdes_authinput_t)); + } + return error; +} + +static int CmdHF14ADesGetUID(const char *Cmd) { + (void)Cmd; + + uint8_t uid[16]={0}; + int res = handler_desfire_getuid(uid); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Error on getting uid."); + return res; + } + PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(uid, sizeof(uid))); + return res; +} + +static int CmdHF14ADesSelectApp(const char *Cmd) { + CLIParserInit("hf mfdes selectaid", + "Select Application ID", + "Usage:\n\thf mfdes selectaid -a 123456\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, false); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIParserFree(); + + swap24(aid); + + if (aidlength != 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length"); + return PM3_EINVARG; + } + + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Error on selecting aid."); + return res; + } + PrintAndLogEx(SUCCESS, "Successfully selected aid."); + return res; +} + static int CmdHF14ADesCreateApp(const char *Cmd) { CLIParserInit("hf mfdes createaid", @@ -1848,7 +2165,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return PM3_EINVARG; } - if (fidlength != 2) { + if (fidlength != 2 && fidlength!=0) { PrintAndLogEx(ERR, "FID must have 2 bytes length"); return PM3_EINVARG; } @@ -1902,6 +2219,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { res = handler_desfire_createapp(&aidhdr, usename, usefid); DropField(); + PrintAndLogEx(SUCCESS, "Successfully created aid."); return res; } @@ -1938,6 +2256,36 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { if (res != PM3_SUCCESS) { DropField(); return res;} res = handler_desfire_deleteapp(aid); DropField(); + PrintAndLogEx(SUCCESS, "Successfully deleted aid."); + return res; +} + +static int selectfile(uint8_t* aid, int fileno, uint8_t* cs){ + if (handler_desfire_select_application(aid)!=PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Couldn't select aid.")); + return PM3_ESOFT; + } + + uint8_t filesettings[20] = {0}; + int fileset_len = 0; + int res = handler_desfire_filesettings(fileno, filesettings, &fileset_len); + + if (tag->session_key!=NULL) + { + mfdes_auth_res_t rpayload; + int keyno=(filesettings[0]>>4)&0xF; + if (keyno!=0xE && currentauth[keyno].keyno==keyno) { + if (handler_desfire_auth(¤tauth[keyno], &rpayload) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Couldn't authenticate key.")); + return PM3_ESOFT; + } + } else if (keyno!=0xE) + { + PrintAndLogEx(ERR, _RED_(" Please authenticate first.")); + return PM3_ESOFT; + } + } + *cs=filesettings[1]; return res; } @@ -1946,27 +2294,25 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { CLIParserInit("hf mfdes clearrecord", "Clear record file", "Usage:\n\t" - "hf mfdes clearrecord -a 123456 -n 01\n" + "hf mfdes clearrecord -n 01\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); - - int fidlength = 0; - uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(3), fid, 2, &fidlength); + CLIGetHexWithReturn(1, fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(2, aid, &aidlength); + swap24(aid); CLIParserFree(); if (filenolen != 1) { @@ -1979,20 +2325,24 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); } - swap24(aid); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; + uint8_t cs=0; + if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - res = handler_desfire_clearrecordfile(fileno[0]); + int res = handler_desfire_clearrecordfile(fileno[0]); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully cleared record file."); } else { @@ -2006,27 +2356,24 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { CLIParserInit("hf mfdes deletefile", "Delete File", "Usage:\n\t" - "hf mfdes deletefile -a 123456 -n 01\n" + "hf mfdes deletefile -n 01\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); - - int fidlength = 0; - uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(3), fid, 2, &fidlength); + CLIGetHexWithReturn(1, fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(2, aid, &aidlength); + swap24(aid); CLIParserFree(); if (filenolen != 1) { @@ -2039,20 +2386,24 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); } - swap24(aid); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; + uint8_t cs=0; + if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - res = handler_desfire_deletefile(fileno[0]); + int res = handler_desfire_deletefile(fileno[0]); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully deleted file.."); } else { @@ -2066,46 +2417,45 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { CLIParserInit("hf mfdes createfile", "Create Standard/Backup File", "Usage:" - "\n\thf mfdes createfile -a 123456 -f 1111 -n 01 -c 0 -r EEEE -s 000100\n" + "\n\thf mfdes createfile -f 0001 -n 01 -c 0 -r EEEE -s 000100 -a 123456\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("fF", "fileid", "", "ISO FID (2 hex bytes, big endian)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("sS", "filesize", "", "File size (3 hex bytes, big endian)"), arg_lit0("bB", "backup", "Create backupfile instead of standard file"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); int fidlength = 0; uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(3), fid, 2, &fidlength); + CLIParamHexToBuf(arg_get_str(2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(4); + uint8_t comset = arg_get_int(3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(5, ar, &arlength); + CLIGetHexWithReturn(4, ar, &arlength); int fsizelen = 0; uint8_t filesize[3] = {0}; - CLIGetHexWithReturn(6, filesize, &fsizelen); + CLIGetHexWithReturn(5, filesize, &fsizelen); - bool isbackup = arg_get_lit(7); + bool isbackup = arg_get_lit(6); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(7, aid, &aidlength); + swap24(aid); CLIParserFree(); - swap24(aid); swap16(fid); swap24(filesize); @@ -2138,19 +2488,6 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_file_t ft; memcpy(ft.fid, fid, 2); memcpy(ft.filesize, filesize, 3); @@ -2158,6 +2495,27 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { ft.comset = comset; memcpy(ft.access_rights, ar, 2); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + DropField(); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + DropField(); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + + int res=handler_desfire_select_application(aid); + if (res!=PM3_SUCCESS){ + PrintAndLogEx(ERR, "Couldn't select aid. Error %d", res); + DropField(); + return res; + } + + if (isbackup) res = handler_desfire_create_backup_file(&ft); else res = handler_desfire_create_std_file(&ft); @@ -2174,24 +2532,26 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { CLIParserInit("hf mfdes getvalue", "Get value from value file", "Usage:" - "\n\thf mfdes getvalue -a 123456 -n 03\n" + "\n\thf mfdes getvalue -n 03\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(2, aid, &aidlength); + swap24(aid); + CLIParserFree(); if (filenolen != 1) { @@ -2204,25 +2564,28 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - swap24(aid); - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } mfdes_value_t value; value.fileno = fileno[0]; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + uint8_t cs=0; + if (selectfile(aid,value.fileno,&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + int len = 0; - res = handler_desfire_getvalue(&value, &len); + int res = handler_desfire_getvalue(&value, &len, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read value from File %u:", fileno[0]); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); @@ -2242,36 +2605,40 @@ static int CmdHF14ADesReadData(const char *Cmd) { CLIParserInit("hf mfdes readdata", "Read data from File", "Usage:" - "\n\thf mfdes readdata -a 123456 -n 01 -t 0 -o 000000 -l 000000\n" - ); + "\n\thf mfdes readdata -n 01 -t 0 -o 000000 -l 000000 -a 123456\n" + "\thf mfdes readdata -n 01 -t 0 (Read all data from standard file, fileno 01)\n" + "Make sure to select aid or authenticate aid before running this command.\n" + ); void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), - arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), - arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), - arg_strx0("lL", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), - arg_int0("type", "type", "", "File Type (0=Standard/Backup, 1=Record)"), - arg_param_end + arg_param_begin, + arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), + arg_strx0("lL", "length", "", + "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), + arg_int0("tT", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); int offsetlength = 0; uint8_t offset[3] = {0}; - CLIParamHexToBuf(arg_get_str(3), offset, 3, &offsetlength); + CLIParamHexToBuf(arg_get_str(2), offset, 3, &offsetlength); int flength = 0; uint8_t filesize[3] = {0}; - CLIParamHexToBuf(arg_get_str(4), filesize, 3, &flength); + CLIParamHexToBuf(arg_get_str(3), filesize, 3, &flength); - int type = arg_get_int(5); + int type = arg_get_int(4); + + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(5, aid, &aidlength); + swap24(aid); CLIParserFree(); if (type > 1) { @@ -2294,23 +2661,9 @@ static int CmdHF14ADesReadData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - swap24(aid); swap24(filesize); swap24(offset); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_data_t ft; memcpy(ft.offset, offset, 3); memcpy(ft.length, filesize, 3); @@ -2320,20 +2673,41 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (bytestoread == 0) bytestoread = 0xFFFFFF; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + uint8_t cs=0; + if (selectfile(aid,ft.fileno,&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + uint8_t *data = (uint8_t *)calloc(bytestoread, sizeof(uint8_t)); + int res=PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_readdata(&ft, type); + res = handler_desfire_readdata(&ft, type,cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read data from file %d:", ft.fileno); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); int len = le24toh(ft.length); for (int i = 0; i < len; i += 16) { - PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&ft.data[i], len > 16 ? 16 : len), sprint_ascii(&ft.data[i], len > 16 ? 16 : len)); + int l=len-i; + PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&ft.data[i], l > 16 ? 16 : l), sprint_ascii(&ft.data[i], l > 16 ? 16 : l)); } } else { PrintAndLogEx(ERR, "Couldn't read data. Error %d", res); + DropField(); + return res; } free(data); } @@ -2345,37 +2719,38 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { CLIParserInit("hf mfdes changevalue", "Change value (credit/limitedcredit/debit)", "Usage:" - "\n\thf mfdes changevalue -a 123456 -n 03 -m 0 -d 00000001\n" + "\n\thf mfdes changevalue -n 03 -m 0 -d 00000001\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("dD", "value", "", "Value to increase (4 hex bytes, big endian)"), arg_int0("mM", "mode", "", "Mode (0=Credit, 1=LimitedCredit, 2=Debit)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; mfdes_value_t value; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); value.fileno = fileno[0]; int vlength = 0x0; - CLIParamHexToBuf(arg_get_str(3), value.value, 4, &vlength); + CLIParamHexToBuf(arg_get_str(2), value.value, 4, &vlength); - int mode = arg_get_int(4); - CLIParserFree(); + int mode = arg_get_int(3); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(4, aid, &aidlength); swap24(aid); + CLIParserFree(); + if (mode > 2) { PrintAndLogEx(ERR, "Invalid mode (0=Credit, 1=LimitedCredit, 2=Debit)."); return PM3_EINVARG; @@ -2397,25 +2772,31 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + uint8_t cs=0; + if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } + int res=PM3_ESOFT; if (mode == 0) { - res = handler_desfire_credit(&value); + res = handler_desfire_credit(&value,cs); } else if (mode == 1) { - res = handler_desfire_limitedcredit(&value); + res = handler_desfire_limitedcredit(&value,cs); } else if (mode == 2) { - res = handler_desfire_debit(&value); + res = handler_desfire_debit(&value,cs); } if (res == PM3_SUCCESS) { @@ -2437,32 +2818,29 @@ static int CmdHF14ADesWriteData(const char *Cmd) { CLIParserInit("hf mfdes writedata", "Write data to File", "Usage:" - "\n\thf mfdes writedata -a 123456 -n 01 -t 0 -o 000000 -d 3132333435363738\n" + "\n\thf mfdes writedata -n 01 -t 0 -o 000000 -d 3132333435363738\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), arg_strx0("dD", "data", "", "Data to write (hex bytes, 0xFFFF bytes max.)"), arg_int0("type", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian, optional)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); int offsetlength = 0; uint8_t offset[3] = {0}; - CLIParamHexToBuf(arg_get_str(3), offset, 3, &offsetlength); + CLIParamHexToBuf(arg_get_str(2), offset, 3, &offsetlength); int dlength = 0xFFFF; uint8_t *data = (uint8_t *)calloc(0xFFFF, sizeof(uint8_t)); @@ -2470,13 +2848,16 @@ static int CmdHF14ADesWriteData(const char *Cmd) { PrintAndLogEx(ERR, "failed to allocate memory"); return PM3_EMALLOC; } - CLIParamHexToBuf(arg_get_str(4), data, 0xFFFF, &dlength); + CLIParamHexToBuf(arg_get_str(3), data, 0xFFFF, &dlength); - int type = arg_get_int(5); + int type = arg_get_int(4); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(5, aid, &aidlength); + swap24(aid); CLIParserFree(); - swap24(aid); swap24(offset); if (type < 0 || type > 1) { @@ -2509,30 +2890,33 @@ static int CmdHF14ADesWriteData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - if (data) free(data); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid"); - DropField(); - if (data) free(data); - return res; - } - mfdes_data_t ft; memcpy(ft.offset, offset, 3); htole24(dlength, ft.length); ft.fileno = fileno[0]; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + uint8_t cs=0; + if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + + int res=PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_writedata(&ft, type); + res = handler_desfire_writedata(&ft, type,cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully wrote data"); } else { @@ -2549,51 +2933,51 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { CLIParserInit("hf mfdes createrecordfile", "Create Linear/Cyclic Record File", "Usage:" - "\n\thf mfdes createrecordfile -a 123456 -f 1122 -n 02 -c 0 -r EEEE -s 000010 -m 000005\n" + "\n\thf mfdes createrecordfile -f 1122 -n 02 -c 0 -r EEEE -s 000010 -m 000005 -a 123456\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("fF", "fileid", "", "ISO FID (2 hex bytes, big endian)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("sS", "recordsize", "", "Record size (3 hex bytes, big endian, 000001 to FFFFFF)"), arg_strx0("mM", "maxnumrecord", "", "Max. Number of Records (3 hex bytes, big endian)"), arg_lit0("bB", "cyclic", "Create cyclic record file instead of linear record file"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); int fidlength = 0; uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(3), fid, 2, &fidlength); + CLIParamHexToBuf(arg_get_str(2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(4); + uint8_t comset = arg_get_int(3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(5, ar, &arlength); + CLIGetHexWithReturn(4, ar, &arlength); int rsizelen = 0; uint8_t recordsize[3] = {0}; - CLIGetHexWithReturn(6, recordsize, &rsizelen); + CLIGetHexWithReturn(5, recordsize, &rsizelen); int msizelen = 0; uint8_t maxnumrecords[3] = {0}; - CLIGetHexWithReturn(7, maxnumrecords, &msizelen); + CLIGetHexWithReturn(6, maxnumrecords, &msizelen); - bool cyclic = arg_get_lit(8); + bool cyclic = arg_get_lit(7); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(8, aid, &aidlength); + swap24(aid); CLIParserFree(); - swap24(aid); swap16(fid); swap24(recordsize); swap24(maxnumrecords); @@ -2638,19 +3022,6 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_linear_t ft; ft.fileno = fileno[0]; memcpy(ft.fid, fid, 2); @@ -2659,6 +3030,23 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { memcpy(ft.recordsize, recordsize, 3); memcpy(ft.maxnumrecords, maxnumrecords, 3); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + if (handler_desfire_select_application(aid)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); + return PM3_ESOFT; + } + + int res=PM3_SUCCESS; if (cyclic) res = handler_desfire_create_cyclicrecordfile(&ft); else res = handler_desfire_create_linearrecordfile(&ft); if (res == PM3_SUCCESS) { @@ -2674,54 +3062,53 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { CLIParserInit("hf mfdes createvaluefile", "Create Value File", "Usage:" - "\n\thf mfdes createvaluefile -a 123456 -n 03 -c 0 -r EEEE -l 00000000 -u 00002000 -v 00000001 -m 02\n" + "\n\thf mfdes createvaluefile -n 03 -c 0 -r EEEE -l 00000000 -u 00002000 -v 00000001 -m 02 -a 123456\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("lL", "lowerlimit", "", "Lower limit (4 hex bytes, big endian)"), arg_strx0("uU", "upperlimit", "", "Upper limit (4 hex bytes, big endian)"), arg_strx0("vV", "value", "", "Value (4 hex bytes, big endian)"), arg_strx0("mM", "limitcredit", "", "Limited Credit enabled (1 hex byte [Bit 0=LimitedCredit, 1=FreeValue])"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(1, aid, &aidlength); - int filenolen = 0; uint8_t fileno[1] = {0}; - CLIGetHexWithReturn(2, fileno, &filenolen); + CLIGetHexWithReturn(1, fileno, &filenolen); - uint8_t comset = arg_get_int(3); + uint8_t comset = arg_get_int(2); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(4, ar, &arlength); + CLIGetHexWithReturn(3, ar, &arlength); int lllen = 0; uint8_t lowerlimit[4] = {0}; - CLIGetHexWithReturn(5, lowerlimit, &lllen); + CLIGetHexWithReturn(4, lowerlimit, &lllen); int ullen = 0; uint8_t upperlimit[4] = {0}; - CLIGetHexWithReturn(6, upperlimit, &ullen); + CLIGetHexWithReturn(5, upperlimit, &ullen); int vllen = 0; uint8_t value[4] = {0}; - CLIGetHexWithReturn(7, value, &vllen); + CLIGetHexWithReturn(6, value, &vllen); int limitedlen = 0; uint8_t limited[1] = {0}; - CLIGetHexWithReturn(8, limited, &limitedlen); - + CLIGetHexWithReturn(7, limited, &limitedlen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(8, aid, &aidlength); + swap24(aid); CLIParserFree(); - swap24(aid); swap32(lowerlimit); swap32(upperlimit); swap32(value); @@ -2765,18 +3152,6 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { PrintAndLogEx(WARNING, "Limited Credit Enabled must have 1 hex byte"); return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } mfdes_value_file_t ft; ft.fileno = fileno[0]; @@ -2787,7 +3162,24 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { memcpy(ft.value, value, 4); ft.limitedcreditenabled = limited[0]; - res = handler_desfire_create_value_file(&ft); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid,(uint8_t *)&tag->selected_application,3); + } + + if (handler_desfire_select_application(aid)!=PM3_SUCCESS) + { + PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); + return PM3_ESOFT; + } + + int res = handler_desfire_create_value_file(&ft); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully created value file."); } else { @@ -2800,79 +3192,23 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { static int CmdHF14ADesFormatPICC(const char *Cmd) { 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" + "Usage:" + "\n\thf mfdes formatpicc\n" + "Make sure to authenticate picc before running this command.\n" ); - void *argtable[] = { - arg_param_begin, - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end - }; - CLIExecWithReturn(Cmd, argtable, false); - - 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"); - return PM3_EINVARG; - } - - DropField(); - uint8_t aid[3] = {0}; - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; - - mfdes_authinput_t 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)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); + sAPDU apdu = {0x90, MFDES_FORMAT_PICC, 0x00, 0x00, 0, NULL}; // 0xDF + uint16_t sw = 0; + int recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't format picc -> %s"), GetErrorString(res, &sw)); DropField(); - return PM3_ETIMEOUT; - } - - uint8_t isOK = (resp.status == PM3_SUCCESS); - if (isOK) { - struct { - uint8_t flags; - uint8_t datalen; - uint8_t datain[FRAME_PAYLOAD_SIZE]; - } PACKED payload_raw; - - payload_raw.datain[0] = 0xFC; - payload_raw.flags = NONE; - payload_raw.datalen = 1; - - SendCommandNG(CMD_HF_DESFIRE_COMMAND, (uint8_t *)&payload_raw, sizeof(payload_raw)); - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_COMMAND, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client reset command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - if (resp.status == PM3_SUCCESS) { - /*struct r { - uint8_t len; - uint8_t data[RECEIVE_SIZE]; - } PACKED; - struct r *rpayload = (struct r *)&resp.data.asBytes;*/ + return res; + } else { PrintAndLogEx(INFO, "Card successfully reset"); return PM3_SUCCESS; } - } else { - PrintAndLogEx(WARNING, _RED_("Auth command failed")); - } DropField(); return PM3_SUCCESS; } @@ -3183,7 +3519,7 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + res = handler_desfire_getkeysettings(&key_setting, &num_keys); if (res != PM3_SUCCESS) return res; res = handler_desfire_select_application(aid); @@ -3196,11 +3532,10 @@ static int CmdHF14ADesDump(const char *Cmd) { int fileset_len = 0; res = handler_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) { - if (fileset_len == 1 + 1 + 2 + 3 + maclen) { + if (fileset_len == 1 + 1 + 2 + 3) { int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; mfdes_data_t fdata; fdata.fileno = file_ids[j]; @@ -3210,7 +3545,7 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t *data = (uint8_t *)malloc(filesize); fdata.data = data; if (data) { - res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE); + res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE,filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3224,12 +3559,12 @@ static int CmdHF14ADesDump(const char *Cmd) { res = handler_desfire_select_application(aid); } } - } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) { + } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1) { PrintAndLogEx(NORMAL, "\n\nValue file: 0x%0x", file_ids[j]); mfdes_value_t value; value.fileno = file_ids[j]; int len = 0; - res = handler_desfire_getvalue(&value, &len); + res = handler_desfire_getvalue(&value, &len,filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3240,7 +3575,7 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(ERR, "Couldn't read value. Error %d", res); res = handler_desfire_select_application(aid); } - } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { + } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3) { int maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7]; int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; mfdes_data_t fdata; @@ -3256,7 +3591,7 @@ static int CmdHF14ADesDump(const char *Cmd) { fdata.offset[0] = offset & 0xFF; fdata.offset[1] = (offset >> 8) & 0xFF; fdata.offset[2] = (offset >> 16) & 0xFF; - res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE); + res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE,filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3390,12 +3725,104 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { return PM3_SUCCESS; } -// MIAFRE DESFire Authentication -// -#define BUFSIZE 256 -static int CmdHF14ADesAuth(const char *Cmd) { - int res = 0; - DropField(); +static int CmdHF14ADesChangeKey(const char *Cmd) { + //DropField(); + // NR DESC KEYLENGHT + // ------------------------ + // 1 = DES 8 + // 2 = 3DES 16 + // 3 = 3K 3DES 24 + // 4 = AES 16 + uint8_t keylength = 8; + uint8_t newkeylength = 8; + + CLIParserInit("hf mfdes changekey", + "Changes Mifare DESFire Key", + "Usage:" + "\n\thf mfdes changekey -n 0 -t 1 -k 0000000000000000 -u 1 -j 0102030405060708 (DES,keynumber 0)\n" + "Make sure to select aid or authenticate aid before running this command.\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("nN", "keyno", "", "Key number used for authentification"), + arg_int0("tT", "algo", "", "Current key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("kK", "key", "", "Current Key (HEX 8-24 bytes)"), + arg_int0("uU", "newalgo", "", "New key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("jJ", "newkey", "", "New Key (HEX 8-24 bytes)"), + arg_int0("vV", "aesversion", "", "Aes version (if aes is used)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, false); + + uint8_t cmdKeyNo = arg_get_int_def(1, 0); + uint8_t cmdAuthAlgo = arg_get_int_def(2, 0); + uint8_t key[24] = {0}; + int keylen = 0; + CLIParamHexToBuf(arg_get_str(3), key, 24, &keylen); + uint8_t newcmdAuthAlgo = arg_get_int_def(4, 0); + uint8_t newkey[24] = {0}; + int newkeylen = 0; + CLIParamHexToBuf(arg_get_str(5), newkey, 24, &newkeylen); + uint8_t aesversion = arg_get_int_def(6, 0); + CLIParserFree(); + + if (cmdAuthAlgo == MFDES_ALGO_AES) { + keylength=16; + } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + keylength=16; + } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + keylength=8; + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + keylength=24; + } + + if (newcmdAuthAlgo == MFDES_ALGO_AES) { + newkeylength=16; + } else if (newcmdAuthAlgo == MFDES_ALGO_3DES) { + newkeylength=16; + } else if (newcmdAuthAlgo == MFDES_ALGO_DES) { + newkeylength=8; + } else if (newcmdAuthAlgo == MFDES_ALGO_3K3DES) { + newkeylength=24; + } + + if ((keylen < 8) || (keylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); + return PM3_EINVARG; + } + + if ((newkeylen < 8) || (newkeylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have %d bytes length.", newkeylen); + return PM3_EINVARG; + } + + if (keylen != keylength) { + PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + + if (newkeylen != newkeylength) { + PrintAndLogEx(WARNING, "New key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + + int error=mifare_desfire_change_key(cmdKeyNo,newkey,newcmdAuthAlgo,key,cmdAuthAlgo,aesversion); + if (error==PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, " Successfully changed key."); + } else { + PrintAndLogEx(SUCCESS, " Error on changing key."); + return PM3_ESOFT; + } + return PM3_SUCCESS; +} + + +// MIAFRE DESFire Authentication +// +#define BUFSIZE 256 +static int CmdHF14ADesAuth(const char *Cmd) { + //DropField(); // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 @@ -3403,20 +3830,23 @@ static int CmdHF14ADesAuth(const char *Cmd) { // 3 = 3K 3DES 24 // 4 = AES 16 uint8_t keylength = 8; - bool usedefaultkey = false; CLIParserInit("hf mfdes auth", "Authenticates Mifare DESFire using Key", "Usage:" - "\n\thf mfdes auth -m 3 -t 4 -a 808301 -n 0 -k 00000000000000000000000000000000 (AES)" - "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 0 -k 00000000000000000000000000000000 (3DES)" - "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 0 -k 0000000000000000 (DES)" + "\n\thf mfdes auth -m 3 -t 4 -a 808301 -n 0 -k 00000000000000000000000000000000 (AES,keynumber 0, aid 0x803201)" + "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 1 -k 00000000000000000000000000000000 (3DES,keynumber 1, aid 0x000000)" + "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 2 -k 0000000000000000 (DES,keynumber 2, aid 0x000000)" + "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 0 (DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 0 (3DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 3 -t 4 -a 000000 -n 0 (3K3DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 3 -t 4 -a 000000 -n 0 (AES, defaultkey, aid 0x000000)" ); void *argtable[] = { arg_param_begin, - arg_int0("mM", "type", "", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)"), - arg_int0("tT", "algo", "", "Crypt algo (1=DES, 2=3DES(2K2DES), 4=3K3DES, 5=AES)"), + arg_int0("mM", "type", "", "Auth type (1=normal, 2=iso, 3=aes)"), + arg_int0("tT", "algo", "", "Crypt algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), arg_strx0("aA", "aid", "", "AID used for authentification (HEX 3 bytes)"), arg_int0("nN", "keyno", "", "Key number used for authentification"), arg_str0("kK", "key", "", "Key for checking (HEX 8-24 bytes)"), @@ -3438,105 +3868,48 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParamHexToBuf(arg_get_str(5), key, 24, &keylen); CLIParserFree(); + if (cmdAuthAlgo == MFDES_ALGO_AES) { + keylength=16; + } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + keylength=16; + } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + keylength=8; + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + keylength=24; + } if (keylen == 0) { - usedefaultkey = true; + if (cmdAuthAlgo == MFDES_ALGO_AES) { + keylen=16; + memcpy(key,aesdefaultkeys[0],keylen); + } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + keylen=16; + memcpy(key,aesdefaultkeys[0],keylen); + } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + keylen=8; + memcpy(key,desdefaultkeys[0],keylen); + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + keylen=24; + memcpy(key,k3kdefaultkeys[0],keylen); + } } else if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); return PM3_EINVARG; } + if (keylen != keylength) { + PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + // AID if (aidlength != 3) { PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); 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_EINVARG; - } - break; - case MFDES_AUTH_ISO: - if (cmdAuthAlgo != MFDES_ALGO_3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); - 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_EINVARG; - } - break; - case MFDES_AUTH_PICC: - if (cmdAuthAlgo != MFDES_AUTH_DES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); - return PM3_EINVARG; - } - break; - default: - PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - return PM3_EINVARG; - } - - switch (cmdAuthAlgo) { - case MFDES_ALGO_3DES: - keylength = 16; - PrintAndLogEx(NORMAL, "2 key 3DES selected"); - break; - case MFDES_ALGO_3K3DES: - keylength = 24; - PrintAndLogEx(NORMAL, "3 key 3DES selected"); - break; - case MFDES_ALGO_AES: - keylength = 16; - PrintAndLogEx(NORMAL, "AES selected"); - break; - default: - cmdAuthAlgo = MFDES_ALGO_DES; - keylength = 8; - PrintAndLogEx(NORMAL, "DES selected"); - break; - } - - // KEY - if (keylen != keylength) { - PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); - return PM3_EINVARG; - } - - - res = handler_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 = handler_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) return res; - } - - mfdes_authinput_t 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; - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - */ mfdes_auth_res_t rpayload; - int error = handler_desfire_auth(&payload, &rpayload, usedefaultkey); - if (error == PM3_SUCCESS) { + int error=desfire_authenticate(cmdAuthMode,cmdAuthAlgo,aid,key,cmdKeyNo,&rpayload); + if (error==PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload.sessionkey, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -3649,19 +4022,14 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ } else des = true; int error = PM3_SUCCESS; bool badlen = false; - mfdes_authinput_t payload; + uint32_t curaid = (aid[0] & 0xFF) + ((aid[1] & 0xFF) << 8) + ((aid[2] & 0xFF) << 16); if (des) { for (int keyno = 0; keyno < 0xE; keyno++) if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { for (int curkey = 0; curkey < deskeyListLen; curkey++) { - payload.keylen = 8; - memcpy(payload.key, deskeyList[curkey], 8); - payload.mode = MFDES_AUTH_DES; - payload.algo = MFDES_ALGO_DES; - payload.keyno = keyno; mfdes_auth_res_t rpayload; - error = handler_desfire_auth(&payload, &rpayload, false); + error=desfire_authenticate(MFDES_AUTH_DES,MFDES_ALGO_DES,aid,deskeyList[curkey],keyno,&rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); foundKeys[0][keyno][0] = 0x01; @@ -3689,13 +4057,9 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ for (int keyno = 0; keyno < 0xE; keyno++) if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { for (int curkey = 0; curkey < aeskeyListLen; curkey++) { - payload.keylen = 16; - memcpy(payload.key, aeskeyList[curkey], 16); - payload.mode = MFDES_AUTH_DES; - payload.algo = MFDES_ALGO_3DES; - payload.keyno = keyno; mfdes_auth_res_t rpayload; - error = handler_desfire_auth(&payload, &rpayload, false); + error=desfire_authenticate(MFDES_AUTH_DES,MFDES_ALGO_3DES,aid,aeskeyList[curkey],keyno,&rpayload); + if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); foundKeys[1][keyno][0] = 0x01; @@ -3724,13 +4088,8 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ for (int keyno = 0; keyno < 0xE; keyno++) if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { for (int curkey = 0; curkey < aeskeyListLen; curkey++) { - payload.keylen = 16; - memcpy(payload.key, aeskeyList[curkey], 16); - payload.mode = MFDES_AUTH_AES; - payload.algo = MFDES_ALGO_AES; - payload.keyno = keyno; mfdes_auth_res_t rpayload; - error = handler_desfire_auth(&payload, &rpayload, false); + error=desfire_authenticate(MFDES_AUTH_AES,MFDES_ALGO_AES,aid,aeskeyList[curkey],keyno,&rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); foundKeys[2][keyno][0] = 0x01; @@ -3759,13 +4118,8 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ for (int keyno = 0; keyno < 0xE; keyno++) if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { for (int curkey = 0; curkey < k3kkeyListLen; curkey++) { - payload.keylen = 24; - memcpy(payload.key, k3kkeyList[curkey], 24); - payload.mode = MFDES_AUTH_ISO; - payload.algo = MFDES_ALGO_3K3DES; - payload.keyno = keyno; mfdes_auth_res_t rpayload; - error = handler_desfire_auth(&payload, &rpayload, false); + error=desfire_authenticate(MFDES_AUTH_ISO,MFDES_ALGO_3K3DES,aid,k3kkeyList[curkey],keyno,&rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3K3 Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(k3kkeyList[curkey], 24)); foundKeys[3][keyno][0] = 0x01; @@ -4088,6 +4442,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"}, + {"getuid", CmdHF14ADesGetUID, IfPm3Iso14443a, "Get random uid"}, + {"selectaid", CmdHF14ADesSelectApp, IfPm3Iso14443a, "Select Application ID"}, {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, {"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"}, @@ -4099,31 +4455,10 @@ static command_t CommandTable[] = { {"writedata", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record file"}, {"getvalue", CmdHF14ADesGetValueData, IfPm3Iso14443a, "Get value of file"}, {"changevalue", CmdHF14ADesChangeValue, IfPm3Iso14443a, "Write value of a value file (credit/debit/clear)"}, + {"changekey", CmdHF14ADesChangeKey, IfPm3Iso14443a, "Change Key"}, {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, {"chk", CmdHF14aDesChk, IfPm3Iso14443a, "Check keys"}, - /* - ToDo: - - Native Cmds - ChangeKeySettings - ChangeKey - SetConfiguration - GetISOFileIDs - GetCardUID - ChangeFileSettings - Handling CMAC/Encryption after authorization - - 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} }; @@ -4137,3 +4472,26 @@ int CmdHFMFDes(const char *Cmd) { clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } + +/* + ToDo: + + Native Cmds + ----------- + ChangeKeySettings 0x5F + SetConfiguration + GetISOFileIDs + GetCardUID + ChangeFileSettings + + 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 +*/ diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c index a0e066b44..85270f57a 100644 --- a/client/src/mifare/desfire_crypto.c +++ b/client/src/mifare/desfire_crypto.c @@ -28,6 +28,7 @@ #include "desfire_crypto.h" #include #include +#include #include "commonutil.h" #include "mbedtls/aes.h" #include "mbedtls/des.h" @@ -406,6 +407,8 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, /* pass through */ case MDCM_MACED: + communication_settings|=NO_CRC; + switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: if (!(communication_settings & MAC_COMMAND)) @@ -508,6 +511,9 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings) { void *res = data; void *edata = NULL; + tag->crypto_buffer_size=*nbytes*2; + tag->crypto_buffer=(uint8_t*)malloc(tag->crypto_buffer_size); + uint8_t first_cmac_byte = 0x00; desfirekey_t key = DESFIRE(tag)->session_key; @@ -527,6 +533,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes /* pass through */ case MDCM_MACED: + communication_settings|=NO_CRC; switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: if (communication_settings & MAC_VERIFY) { @@ -540,18 +547,20 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes break; } - size_t edl = enciphered_data_length(tag, *nbytes - 1, communication_settings); + size_t edl = enciphered_data_length(tag, *nbytes, communication_settings); edata = malloc(edl); - memcpy(edata, data, *nbytes - 1); - memset((uint8_t *)edata + *nbytes - 1, 0, edl - *nbytes + 1); + memcpy(edata, data, *nbytes); + memset((uint8_t *)edata + *nbytes , 0, edl - *nbytes); mifare_cypher_blocks_chained(tag, NULL, NULL, edata, edl, MCD_SEND, MCO_ENCYPHER); - if (0 != memcmp((uint8_t *)data + *nbytes - 1, (uint8_t *)edata + edl - 8, 4)) { + if (0 != memcmp((uint8_t *)data + *nbytes, (uint8_t *)edata + edl - 8, 4)) { + PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data+*nbytes, key_macing_length(key))); + PrintAndLogEx(NORMAL, "Actual MAC %s", sprint_hex(edata + edl - 8, key_macing_length(key))); #ifdef WITH_DEBUG Dbprintf("MACing not verified"); - hexdump((uint8_t *)data + *nbytes - 1, key_macing_length(key), "Expect ", 0); + hexdump((uint8_t *)data + *nbytes, key_macing_length(key), "Expect ", 0); hexdump((uint8_t *)edata + edl - 8, key_macing_length(key), "Actual ", 0); #endif DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR; @@ -644,17 +653,19 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes case AS_NEW: /* Move status between payload and CRC */ res = DESFIRE(tag)->crypto_buffer; - memcpy(res, data, *nbytes); + if (res!=NULL) { + memcpy(res, data, *nbytes); - crc_pos = (*nbytes) - 16 - 3; - if (crc_pos < 0) { - /* Single block */ - crc_pos = 0; + crc_pos = (*nbytes) - 16 - 3; + if (crc_pos < 0) { + /* Single block */ + crc_pos = 0; + } + memcpy((uint8_t *) res + crc_pos + 1, (uint8_t *) res + crc_pos, *nbytes - crc_pos); + ((uint8_t *) res)[crc_pos] = 0x00; + crc_pos++; + *nbytes += 1; } - memcpy((uint8_t *)res + crc_pos + 1, (uint8_t *)res + crc_pos, *nbytes - crc_pos); - ((uint8_t *)res)[crc_pos] = 0x00; - crc_pos++; - *nbytes += 1; break; } @@ -725,6 +736,9 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes break; } + free(tag->crypto_buffer); + tag->crypto_buffer_size=0; + tag->crypto_buffer=NULL; return res; } @@ -854,3 +868,45 @@ void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *i offset += block_size; } } + +#define CRC32_PRESET 0xFFFFFFFF + +static void +desfire_crc32_byte(uint32_t *crc, const uint8_t value) +{ + /* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */ + const uint32_t poly = 0xEDB88320; + + *crc ^= value; + for (int current_bit = 7; current_bit >= 0; current_bit--) { + int bit_out = (*crc) & 0x00000001; + *crc >>= 1; + if (bit_out) + *crc ^= poly; + } +} + +void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) +{ + uint32_t desfire_crc = CRC32_PRESET; + for (size_t i = 0; i < len; i++) { + desfire_crc32_byte(&desfire_crc, data[i]); + } + + *((uint32_t *)(crc)) = htole32(desfire_crc); +} + +void desfire_crc32_append(uint8_t *data, const size_t len) +{ + desfire_crc32(data, len, data + len); +} + +void iso14443a_crc_append(uint8_t* data, size_t len) +{ + return compute_crc(CRC_14443_A, data, len, data+len, data+len+1); +} + +void iso14443a_crc(uint8_t* data, size_t len, uint8_t* pbtCrc) +{ + return compute_crc(CRC_14443_A, data, len, pbtCrc, pbtCrc+1); +} \ No newline at end of file diff --git a/client/src/mifare/desfire_crypto.h b/client/src/mifare/desfire_crypto.h index 1dc5316ae..2e044c11d 100644 --- a/client/src/mifare/desfire_crypto.h +++ b/client/src/mifare/desfire_crypto.h @@ -129,4 +129,8 @@ size_t enciphered_data_length(const desfiretag_t tag, const size_t nbytes, int c void cmac_generate_subkeys(desfirekey_t key); void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac); -#endif +void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc); +void desfire_crc32_append(uint8_t *data, const size_t len); +void iso14443a_crc_append(uint8_t* data, size_t len); +void iso14443a_crc(uint8_t* data, size_t len, uint8_t* pbtCrc); +#endif \ No newline at end of file diff --git a/include/protocols.h b/include/protocols.h index b927058b0..682f57eff 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -359,6 +359,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_READSIG 0x3C #define MFDES_WRITE_DATA 0x3D #define MFDES_GET_KEY_SETTINGS 0x45 +#define MFDES_GET_UID 0x51 #define MFDES_CHANGE_KEY_SETTINGS 0x54 #define MFDES_SELECT_APPLICATION 0x5A #define MFDES_CHANGE_FILE_SETTINGS 0x5F From e0bf636aafbbe314be286ef607a87b9a85e4c3ae Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 14:25:40 +0200 Subject: [PATCH 18/26] Make style --- client/src/cmdhfmfdes.c | 393 ++++++++++++++--------------- client/src/mifare/desfire_crypto.c | 41 ++- client/src/mifare/desfire_crypto.h | 6 +- 3 files changed, 211 insertions(+), 229 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 520a73fe6..f8536c38f 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -36,20 +36,22 @@ struct desfire_key default_key = {0}; -uint8_t desdefaultkeys[3][8]= {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, //Official - {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47}, - {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07}}; +uint8_t desdefaultkeys[3][8] = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, //Official + {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47}, + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} +}; -uint8_t aesdefaultkeys[5][16]= {{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, //Official, TRF7970A - {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}, // TRF7970A - {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, // TRF7970A - {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, - {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f}}; +uint8_t aesdefaultkeys[5][16] = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, //Official, TRF7970A + {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}, // TRF7970A + {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, // TRF7970A + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f} +}; -uint8_t k3kdefaultkeys[1][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 k3kdefaultkeys[1][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}}; -struct desfire_tag mf_state={.session_key=NULL,.authentication_scheme=AS_LEGACY,.authenticated_key_no=NOT_YET_AUTHENTICATED,.crypto_buffer=NULL,.crypto_buffer_size=0,.selected_application=0}; -static desfiretag_t tag=&mf_state; +struct desfire_tag mf_state = {.session_key = NULL, .authentication_scheme = AS_LEGACY, .authenticated_key_no = NOT_YET_AUTHENTICATED, .crypto_buffer = NULL, .crypto_buffer_size = 0, .selected_application = 0}; +static desfiretag_t tag = &mf_state; typedef struct { uint8_t mode; @@ -59,7 +61,7 @@ typedef struct { uint8_t key[24]; } PACKED mfdes_authinput_t; -static mfdes_authinput_t currentauth[0xF]={{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1},{.keyno=-1}}; +static mfdes_authinput_t currentauth[0xF] = {{.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}}; typedef struct mfdes_auth_res { uint8_t sessionkeylen; @@ -655,7 +657,7 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) // 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 - tag->authenticated_key_no=NOT_YET_AUTHENTICATED; + tag->authenticated_key_no = NOT_YET_AUTHENTICATED; tag->session_key = NULL; mbedtls_aes_context ctx; @@ -698,14 +700,12 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) } uint8_t subcommand = MFDES_AUTHENTICATE; - tag->authentication_scheme=AS_LEGACY; + tag->authentication_scheme = AS_LEGACY; - if (payload->mode == MFDES_AUTH_AES) - { + if (payload->mode == MFDES_AUTH_AES) { subcommand = MFDES_AUTHENTICATE_AES; - tag->authentication_scheme=AS_NEW; - } - else if (payload->mode == MFDES_AUTH_ISO) { + tag->authentication_scheme = AS_NEW; + } else if (payload->mode == MFDES_AUTH_ISO) { subcommand = MFDES_AUTHENTICATE_ISO; tag->authentication_scheme = AS_NEW; } @@ -872,7 +872,7 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) } // Part 4 - tag->session_key=&default_key; + tag->session_key = &default_key; Desfire_session_key_new(RndA, RndB, key, tag->session_key); if (payload->mode != MFDES_AUTH_PICC) { @@ -909,8 +909,8 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) rpayload->sessionkeylen = payload->keylen; memcpy(rpayload->sessionkey, tag->session_key->data, rpayload->sessionkeylen); memset(tag->ivect, 0, MAX_CRYPTO_BLOCK_SIZE); - tag->authenticated_key_no=payload->keyno; - if (tag->authentication_scheme==AS_NEW) { + tag->authenticated_key_no = payload->keyno; + if (tag->authentication_scheme == AS_NEW) { cmac_generate_subkeys(tag->session_key); } return PM3_SUCCESS; @@ -1017,18 +1017,18 @@ static int handler_desfire_freemem(uint32_t *free_mem) { uint16_t sw = 0; uint8_t fmem[4] = {0}; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) return res; - size_t dlen=recv_len; - p=mifare_cryto_postprocess_data(tag, apdu.data, &dlen, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); + size_t dlen = recv_len; + p = mifare_cryto_postprocess_data(tag, apdu.data, &dlen, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; @@ -1037,8 +1037,7 @@ static int handler_desfire_freemem(uint32_t *free_mem) { return res; } -static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_algo, uint8_t* old_key, int old_algo, int aes_version) -{ +static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, int new_algo, uint8_t *old_key, int old_algo, int aes_version) { key_no &= 0x0F; /* @@ -1058,7 +1057,7 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_a } } - uint8_t data[24*4] = {key_no}; + uint8_t data[24 * 4] = {key_no}; sAPDU apdu = {0x90, MFDES_CHANGE_KEY, 0x00, 0x00, 0x01, data}; // 0xC4 int new_key_length; @@ -1072,7 +1071,7 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_a break; } - int __cmd_n=0; + int __cmd_n = 0; memcpy(data + __cmd_n + 1, new_key, new_key_length); if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { @@ -1085,9 +1084,9 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_a __cmd_n += new_key_length; - if (new_algo == MFDES_ALGO_AES){ - data[__cmd_n+1] = aes_version; - __cmd_n+=1; + if (new_algo == MFDES_ALGO_AES) { + data[__cmd_n + 1] = aes_version; + __cmd_n += 1; } if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { @@ -1099,7 +1098,7 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_a __cmd_n += 2; break; case AS_NEW: - desfire_crc32_append(data+1, __cmd_n); + desfire_crc32_append(data + 1, __cmd_n); __cmd_n += 4; desfire_crc32(new_key, new_key_length, data + __cmd_n); @@ -1119,19 +1118,18 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t* new_key, int new_a } } - uint8_t *p = mifare_cryto_preprocess_data(tag, data+1, (size_t*)&__cmd_n, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); - apdu.Lc=(uint8_t)__cmd_n+1; - apdu.data=p; + uint8_t *p = mifare_cryto_preprocess_data(tag, data + 1, (size_t *)&__cmd_n, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); + apdu.Lc = (uint8_t)__cmd_n + 1; + apdu.data = p; int recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, true); - if (res != PM3_SUCCESS) - { - PrintAndLogEx(WARNING, _RED_(" Can't change key -> %s"),GetErrorString(res, &sw)); - DropField(); - return res; + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't change key -> %s"), GetErrorString(res, &sw)); + DropField(); + return res; } size_t sn = recv_len; @@ -1249,9 +1247,9 @@ static int desfire_print_keysetting(uint8_t key_settings, mifare_des_authalgo_t // 2 MSB denotes const char *str = " Max key number and type : %d, " _YELLOW_("%s"); - if (algo==MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); - else if (algo==MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); - else if (algo==MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); + if (algo == MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo == MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo == MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); //PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys & 0x3F); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -1409,7 +1407,7 @@ static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { // --- GET DF NAMES static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { - *dfname_count=0; + *dfname_count = 0; if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); @@ -1419,7 +1417,7 @@ static int handler_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){ + if (res != PM3_SUCCESS) { if (sw == status(MFDES_E_ILLEGAL_COMMAND_CODE)) return PM3_SUCCESS; return res; } @@ -1444,26 +1442,26 @@ static int handler_desfire_select_application(uint8_t *aid) { DropField(); return res; } - memcpy(&tag->selected_application,aid,3); + memcpy(&tag->selected_application, aid, 3); return PM3_SUCCESS; } -static int key_setting_to_algo(uint8_t aid[3],uint8_t* key_setting, mifare_des_authalgo_t* algo){ +static int key_setting_to_algo(uint8_t aid[3], uint8_t *key_setting, mifare_des_authalgo_t *algo) { int res = handler_desfire_select_application(aid); if (res != PM3_SUCCESS) return res; uint8_t num_keys = 0; res = handler_desfire_getkeysettings(key_setting, &num_keys); - if (res==PM3_SUCCESS){ - switch (num_keys >> 6){ + if (res == PM3_SUCCESS) { + switch (num_keys >> 6) { case 0: - *algo=MFDES_ALGO_DES; + *algo = MFDES_ALGO_DES; break; case 1: - *algo=MFDES_ALGO_3K3DES; + *algo = MFDES_ALGO_3K3DES; break; case 2: - *algo=MFDES_ALGO_AES; + *algo = MFDES_ALGO_AES; break; } } @@ -1567,10 +1565,10 @@ static int handler_desfire_credit(mfdes_value_t *value, uint8_t cs) { uint16_t sw = 0; int recvlen = 0; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { @@ -1586,10 +1584,10 @@ static int handler_desfire_limitedcredit(mfdes_value_t *value, uint8_t cs) { uint16_t sw = 0; int recvlen = 0; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { @@ -1605,10 +1603,10 @@ static int handler_desfire_debit(mfdes_value_t *value, uint8_t cs) { uint16_t sw = 0; int recvlen = 0; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { @@ -1627,10 +1625,10 @@ static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint16_t sw = 0; int resplen = 0; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, false, data->data, &resplen, &sw, 0, true); if (res != PM3_SUCCESS) { @@ -1639,9 +1637,9 @@ static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, return res; } - size_t dlen=resplen; - p=mifare_cryto_postprocess_data(tag, data->data, &dlen, cs|CMAC_COMMAND|CMAC_VERIFY|MAC_VERIFY); - if (dlen!=-1) resplen=dlen; + size_t dlen = resplen; + p = mifare_cryto_postprocess_data(tag, data->data, &dlen, cs | CMAC_COMMAND | CMAC_VERIFY | MAC_VERIFY); + if (dlen != -1) resplen = dlen; memcpy(data->length, &resplen, 3); @@ -1655,10 +1653,10 @@ static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen, uint8_t uint16_t sw = 0; *resplen = 0; - size_t plen=apdu.Lc; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)apdu.data,&plen,0,MDCM_PLAIN|CMAC_COMMAND); - apdu.Lc=(uint8_t)plen; - apdu.data=p; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; int res = send_desfire_cmd(&apdu, false, value->value, resplen, &sw, 0, true); if (res != PM3_SUCCESS) { @@ -1666,8 +1664,8 @@ static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen, uint8_t DropField(); return res; } - size_t dlen=(size_t)resplen; - p=mifare_cryto_postprocess_data(tag, value->value, &dlen, cs|CMAC_COMMAND|CMAC_VERIFY|MAC_VERIFY); + size_t dlen = (size_t)resplen; + p = mifare_cryto_postprocess_data(tag, value->value, &dlen, cs | CMAC_COMMAND | CMAC_VERIFY | MAC_VERIFY); return res; } @@ -1706,9 +1704,9 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, tmp[6] = (datasize >> 16) & 0xFF; - size_t plen=datasize; - uint8_t *p=mifare_cryto_preprocess_data(tag,(uint8_t *)&data->data[pos],&plen,0,cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); - if (plen!=-1) datasize=(uint8_t)plen; + size_t plen = datasize; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)&data->data[pos], &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + if (plen != -1) datasize = (uint8_t)plen; memcpy(&tmp[7], p, datasize); apdu.Lc = datasize + 1 + 3 + 3; @@ -1862,7 +1860,7 @@ int getKeySettings(uint8_t *aid) { uint8_t num_keys = 0; uint8_t key_setting = 0; mifare_des_authalgo_t algo; - res=key_setting_to_algo(aid,&key_setting,&algo); + res = key_setting_to_algo(aid, &key_setting, &algo); if (res == PM3_SUCCESS) { // number of Master keys (0x01) @@ -1878,9 +1876,9 @@ int getKeySettings(uint8_t *aid) { const char *str = " Operation of PICC master key : " _YELLOW_("%s"); - if (algo==MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); - else if (algo==MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); - else if (algo==MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); + if (algo == MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo == MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo == MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); uint8_t cmk_num_versions = 0; if (handler_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { @@ -1914,7 +1912,7 @@ int getKeySettings(uint8_t *aid) { uint8_t num_keys = 0; uint8_t key_setting = 0; mifare_des_authalgo_t algo; - res=key_setting_to_algo(aid,&key_setting,&algo); + res = key_setting_to_algo(aid, &key_setting, &algo); if (res == PM3_SUCCESS) { desfire_print_keysetting(key_setting, algo); } else { @@ -1972,8 +1970,7 @@ static void swap16(uint8_t *data) { data[1] = tmp; }; -int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t* aid, uint8_t* key, int cmdKeyNo, mfdes_auth_res_t* rpayload) -{ +int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t *aid, uint8_t *key, int cmdKeyNo, mfdes_auth_res_t *rpayload) { switch (cmdAuthMode) { case MFDES_AUTH_DES: if (cmdAuthAlgo != MFDES_ALGO_DES && cmdAuthAlgo != MFDES_ALGO_3DES) { @@ -2004,7 +2001,7 @@ int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t* aid, uint8_t return PM3_EINVARG; } - int keylength=16; + int keylength = 16; switch (cmdAuthAlgo) { case MFDES_ALGO_3DES: @@ -2050,7 +2047,7 @@ int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t* aid, uint8_t static int CmdHF14ADesGetUID(const char *Cmd) { (void)Cmd; - uint8_t uid[16]={0}; + uint8_t uid[16] = {0}; int res = handler_desfire_getuid(uid); if (res != PM3_SUCCESS) { DropField(); @@ -2065,12 +2062,12 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { CLIParserInit("hf mfdes selectaid", "Select Application ID", "Usage:\n\thf mfdes selectaid -a 123456\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), - arg_param_end + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); int aidlength = 3; @@ -2165,7 +2162,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return PM3_EINVARG; } - if (fidlength != 2 && fidlength!=0) { + if (fidlength != 2 && fidlength != 0) { PrintAndLogEx(ERR, "FID must have 2 bytes length"); return PM3_EINVARG; } @@ -2215,7 +2212,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { if (res != PM3_SUCCESS) { DropField(); return res; - } + } res = handler_desfire_createapp(&aidhdr, usename, usefid); DropField(); @@ -2260,8 +2257,8 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { return res; } -static int selectfile(uint8_t* aid, int fileno, uint8_t* cs){ - if (handler_desfire_select_application(aid)!=PM3_SUCCESS) { +static int selectfile(uint8_t *aid, int fileno, uint8_t *cs) { + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Couldn't select aid.")); return PM3_ESOFT; } @@ -2270,22 +2267,20 @@ static int selectfile(uint8_t* aid, int fileno, uint8_t* cs){ int fileset_len = 0; int res = handler_desfire_filesettings(fileno, filesettings, &fileset_len); - if (tag->session_key!=NULL) - { + if (tag->session_key != NULL) { mfdes_auth_res_t rpayload; - int keyno=(filesettings[0]>>4)&0xF; - if (keyno!=0xE && currentauth[keyno].keyno==keyno) { + int keyno = (filesettings[0] >> 4) & 0xF; + if (keyno != 0xE && currentauth[keyno].keyno == keyno) { if (handler_desfire_auth(¤tauth[keyno], &rpayload) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Couldn't authenticate key.")); return PM3_ESOFT; } - } else if (keyno!=0xE) - { + } else if (keyno != 0xE) { PrintAndLogEx(ERR, _RED_(" Please authenticate first.")); return PM3_ESOFT; } } - *cs=filesettings[1]; + *cs = filesettings[1]; return res; } @@ -2333,11 +2328,10 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, fileno[0], &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } @@ -2394,11 +2388,10 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, fileno[0], &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } @@ -2505,11 +2498,11 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { DropField(); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - int res=handler_desfire_select_application(aid); - if (res!=PM3_SUCCESS){ + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Couldn't select aid. Error %d", res); DropField(); return res; @@ -2575,11 +2568,10 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,value.fileno,&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, value.fileno, &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } @@ -2608,17 +2600,17 @@ static int CmdHF14ADesReadData(const char *Cmd) { "\n\thf mfdes readdata -n 01 -t 0 -o 000000 -l 000000 -a 123456\n" "\thf mfdes readdata -n 01 -t 0 (Read all data from standard file, fileno 01)\n" "Make sure to select aid or authenticate aid before running this command.\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), - arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), - arg_strx0("lL", "length", "", - "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), - arg_int0("tT", "type", "", "File Type (0=Standard/Backup, 1=Record)"), - arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), - arg_param_end + arg_param_begin, + arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), + arg_strx0("lL", "length", "", + "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), + arg_int0("tT", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); int filenolen = 0; @@ -2681,27 +2673,26 @@ static int CmdHF14ADesReadData(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,ft.fileno,&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, ft.fileno, &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } uint8_t *data = (uint8_t *)calloc(bytestoread, sizeof(uint8_t)); - int res=PM3_ESOFT; + int res = PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_readdata(&ft, type,cs); + res = handler_desfire_readdata(&ft, type, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read data from file %d:", ft.fileno); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); int len = le24toh(ft.length); for (int i = 0; i < len; i += 16) { - int l=len-i; + int l = len - i; PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&ft.data[i], l > 16 ? 16 : l), sprint_ascii(&ft.data[i], l > 16 ? 16 : l)); } } else { @@ -2780,23 +2771,22 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, fileno[0], &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } - int res=PM3_ESOFT; + int res = PM3_ESOFT; if (mode == 0) { - res = handler_desfire_credit(&value,cs); + res = handler_desfire_credit(&value, cs); } else if (mode == 1) { - res = handler_desfire_limitedcredit(&value,cs); + res = handler_desfire_limitedcredit(&value, cs); } else if (mode == 2) { - res = handler_desfire_debit(&value,cs); + res = handler_desfire_debit(&value, cs); } if (res == PM3_SUCCESS) { @@ -2904,19 +2894,18 @@ static int CmdHF14ADesWriteData(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - uint8_t cs=0; - if (selectfile(aid,fileno[0],&cs)!=PM3_SUCCESS) - { + uint8_t cs = 0; + if (selectfile(aid, fileno[0], &cs) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); return PM3_ESOFT; } - int res=PM3_ESOFT; + int res = PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_writedata(&ft, type,cs); + res = handler_desfire_writedata(&ft, type, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully wrote data"); } else { @@ -3038,15 +3027,14 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - if (handler_desfire_select_application(aid)!=PM3_SUCCESS) - { + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); return PM3_ESOFT; } - int res=PM3_SUCCESS; + int res = PM3_SUCCESS; if (cyclic) res = handler_desfire_create_cyclicrecordfile(&ft); else res = handler_desfire_create_linearrecordfile(&ft); if (res == PM3_SUCCESS) { @@ -3170,11 +3158,10 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); return PM3_ESOFT; } - memcpy(aid,(uint8_t *)&tag->selected_application,3); + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - if (handler_desfire_select_application(aid)!=PM3_SUCCESS) - { + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); return PM3_ESOFT; } @@ -3206,9 +3193,9 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { DropField(); return res; } else { - PrintAndLogEx(INFO, "Card successfully reset"); - return PM3_SUCCESS; - } + PrintAndLogEx(INFO, "Card successfully reset"); + return PM3_SUCCESS; + } DropField(); return PM3_SUCCESS; } @@ -3545,7 +3532,7 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t *data = (uint8_t *)malloc(filesize); fdata.data = data; if (data) { - res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE,filesettings[1]); + res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3564,7 +3551,7 @@ static int CmdHF14ADesDump(const char *Cmd) { mfdes_value_t value; value.fileno = file_ids[j]; int len = 0; - res = handler_desfire_getvalue(&value, &len,filesettings[1]); + res = handler_desfire_getvalue(&value, &len, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3591,7 +3578,7 @@ static int CmdHF14ADesDump(const char *Cmd) { fdata.offset[0] = offset & 0xFF; fdata.offset[1] = (offset >> 8) & 0xFF; fdata.offset[2] = (offset >> 16) & 0xFF; - res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE,filesettings[1]); + res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3741,17 +3728,17 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { "Usage:" "\n\thf mfdes changekey -n 0 -t 1 -k 0000000000000000 -u 1 -j 0102030405060708 (DES,keynumber 0)\n" "Make sure to select aid or authenticate aid before running this command.\n" - ); + ); void *argtable[] = { - arg_param_begin, - arg_int0("nN", "keyno", "", "Key number used for authentification"), - arg_int0("tT", "algo", "", "Current key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), - arg_str0("kK", "key", "", "Current Key (HEX 8-24 bytes)"), - arg_int0("uU", "newalgo", "", "New key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), - arg_str0("jJ", "newkey", "", "New Key (HEX 8-24 bytes)"), - arg_int0("vV", "aesversion", "", "Aes version (if aes is used)"), - arg_param_end + arg_param_begin, + arg_int0("nN", "keyno", "", "Key number used for authentification"), + arg_int0("tT", "algo", "", "Current key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("kK", "key", "", "Current Key (HEX 8-24 bytes)"), + arg_int0("uU", "newalgo", "", "New key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("jJ", "newkey", "", "New Key (HEX 8-24 bytes)"), + arg_int0("vV", "aesversion", "", "Aes version (if aes is used)"), + arg_param_end }; CLIExecWithReturn(Cmd, argtable, false); @@ -3768,23 +3755,23 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { CLIParserFree(); if (cmdAuthAlgo == MFDES_ALGO_AES) { - keylength=16; + keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { - keylength=16; + keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_DES) { - keylength=8; + keylength = 8; } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { - keylength=24; + keylength = 24; } if (newcmdAuthAlgo == MFDES_ALGO_AES) { - newkeylength=16; + newkeylength = 16; } else if (newcmdAuthAlgo == MFDES_ALGO_3DES) { - newkeylength=16; + newkeylength = 16; } else if (newcmdAuthAlgo == MFDES_ALGO_DES) { - newkeylength=8; + newkeylength = 8; } else if (newcmdAuthAlgo == MFDES_ALGO_3K3DES) { - newkeylength=24; + newkeylength = 24; } if ((keylen < 8) || (keylen > 24)) { @@ -3807,8 +3794,8 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { return PM3_EINVARG; } - int error=mifare_desfire_change_key(cmdKeyNo,newkey,newcmdAuthAlgo,key,cmdAuthAlgo,aesversion); - if (error==PM3_SUCCESS) { + int error = mifare_desfire_change_key(cmdKeyNo, newkey, newcmdAuthAlgo, key, cmdAuthAlgo, aesversion); + if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Successfully changed key."); } else { PrintAndLogEx(SUCCESS, " Error on changing key."); @@ -3869,27 +3856,27 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParserFree(); if (cmdAuthAlgo == MFDES_ALGO_AES) { - keylength=16; + keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { - keylength=16; + keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_DES) { - keylength=8; + keylength = 8; } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { - keylength=24; + keylength = 24; } if (keylen == 0) { if (cmdAuthAlgo == MFDES_ALGO_AES) { - keylen=16; - memcpy(key,aesdefaultkeys[0],keylen); + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { - keylen=16; - memcpy(key,aesdefaultkeys[0],keylen); + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); } else if (cmdAuthAlgo == MFDES_ALGO_DES) { - keylen=8; - memcpy(key,desdefaultkeys[0],keylen); + keylen = 8; + memcpy(key, desdefaultkeys[0], keylen); } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { - keylen=24; - memcpy(key,k3kdefaultkeys[0],keylen); + keylen = 24; + memcpy(key, k3kdefaultkeys[0], keylen); } } else if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); @@ -3908,8 +3895,8 @@ static int CmdHF14ADesAuth(const char *Cmd) { } mfdes_auth_res_t rpayload; - int error=desfire_authenticate(cmdAuthMode,cmdAuthAlgo,aid,key,cmdKeyNo,&rpayload); - if (error==PM3_SUCCESS) { + int error = desfire_authenticate(cmdAuthMode, cmdAuthAlgo, aid, key, cmdKeyNo, &rpayload); + if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload.sessionkey, keylength)); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -4029,7 +4016,7 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { for (int curkey = 0; curkey < deskeyListLen; curkey++) { mfdes_auth_res_t rpayload; - error=desfire_authenticate(MFDES_AUTH_DES,MFDES_ALGO_DES,aid,deskeyList[curkey],keyno,&rpayload); + error = desfire_authenticate(MFDES_AUTH_DES, MFDES_ALGO_DES, aid, deskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); foundKeys[0][keyno][0] = 0x01; @@ -4058,7 +4045,7 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { for (int curkey = 0; curkey < aeskeyListLen; curkey++) { mfdes_auth_res_t rpayload; - error=desfire_authenticate(MFDES_AUTH_DES,MFDES_ALGO_3DES,aid,aeskeyList[curkey],keyno,&rpayload); + error = desfire_authenticate(MFDES_AUTH_DES, MFDES_ALGO_3DES, aid, aeskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); @@ -4089,7 +4076,7 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { for (int curkey = 0; curkey < aeskeyListLen; curkey++) { mfdes_auth_res_t rpayload; - error=desfire_authenticate(MFDES_AUTH_AES,MFDES_ALGO_AES,aid,aeskeyList[curkey],keyno,&rpayload); + error = desfire_authenticate(MFDES_AUTH_AES, MFDES_ALGO_AES, aid, aeskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); foundKeys[2][keyno][0] = 0x01; @@ -4119,7 +4106,7 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][ if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { for (int curkey = 0; curkey < k3kkeyListLen; curkey++) { mfdes_auth_res_t rpayload; - error=desfire_authenticate(MFDES_AUTH_ISO,MFDES_ALGO_3K3DES,aid,k3kkeyList[curkey],keyno,&rpayload); + error = desfire_authenticate(MFDES_AUTH_ISO, MFDES_ALGO_3K3DES, aid, k3kkeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3K3 Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(k3kkeyList[curkey], 24)); foundKeys[3][keyno][0] = 0x01; diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c index 85270f57a..386fbbd4e 100644 --- a/client/src/mifare/desfire_crypto.c +++ b/client/src/mifare/desfire_crypto.c @@ -283,7 +283,7 @@ void cmac_generate_subkeys(desfirekey_t key) { void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac) { int kbs = key_block_size(key); if (kbs == 0) { - return; + return; } uint8_t *buffer = malloc(padded_data_length(len, kbs)); @@ -407,7 +407,7 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, /* pass through */ case MDCM_MACED: - communication_settings|=NO_CRC; + communication_settings |= NO_CRC; switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: @@ -511,8 +511,8 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings) { void *res = data; void *edata = NULL; - tag->crypto_buffer_size=*nbytes*2; - tag->crypto_buffer=(uint8_t*)malloc(tag->crypto_buffer_size); + tag->crypto_buffer_size = *nbytes * 2; + tag->crypto_buffer = (uint8_t *)malloc(tag->crypto_buffer_size); uint8_t first_cmac_byte = 0x00; @@ -533,7 +533,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes /* pass through */ case MDCM_MACED: - communication_settings|=NO_CRC; + communication_settings |= NO_CRC; switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: if (communication_settings & MAC_VERIFY) { @@ -551,12 +551,12 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes edata = malloc(edl); memcpy(edata, data, *nbytes); - memset((uint8_t *)edata + *nbytes , 0, edl - *nbytes); + memset((uint8_t *)edata + *nbytes, 0, edl - *nbytes); mifare_cypher_blocks_chained(tag, NULL, NULL, edata, edl, MCD_SEND, MCO_ENCYPHER); if (0 != memcmp((uint8_t *)data + *nbytes, (uint8_t *)edata + edl - 8, 4)) { - PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data+*nbytes, key_macing_length(key))); + PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data + *nbytes, key_macing_length(key))); PrintAndLogEx(NORMAL, "Actual MAC %s", sprint_hex(edata + edl - 8, key_macing_length(key))); #ifdef WITH_DEBUG Dbprintf("MACing not verified"); @@ -653,7 +653,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes case AS_NEW: /* Move status between payload and CRC */ res = DESFIRE(tag)->crypto_buffer; - if (res!=NULL) { + if (res != NULL) { memcpy(res, data, *nbytes); crc_pos = (*nbytes) - 16 - 3; @@ -737,8 +737,8 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes } free(tag->crypto_buffer); - tag->crypto_buffer_size=0; - tag->crypto_buffer=NULL; + tag->crypto_buffer_size = 0; + tag->crypto_buffer = NULL; return res; } @@ -872,8 +872,7 @@ void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *i #define CRC32_PRESET 0xFFFFFFFF static void -desfire_crc32_byte(uint32_t *crc, const uint8_t value) -{ +desfire_crc32_byte(uint32_t *crc, const uint8_t value) { /* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */ const uint32_t poly = 0xEDB88320; @@ -886,8 +885,7 @@ desfire_crc32_byte(uint32_t *crc, const uint8_t value) } } -void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) -{ +void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) { uint32_t desfire_crc = CRC32_PRESET; for (size_t i = 0; i < len; i++) { desfire_crc32_byte(&desfire_crc, data[i]); @@ -896,17 +894,14 @@ void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) *((uint32_t *)(crc)) = htole32(desfire_crc); } -void desfire_crc32_append(uint8_t *data, const size_t len) -{ +void desfire_crc32_append(uint8_t *data, const size_t len) { desfire_crc32(data, len, data + len); } -void iso14443a_crc_append(uint8_t* data, size_t len) -{ - return compute_crc(CRC_14443_A, data, len, data+len, data+len+1); +void iso14443a_crc_append(uint8_t *data, size_t len) { + return compute_crc(CRC_14443_A, data, len, data + len, data + len + 1); } -void iso14443a_crc(uint8_t* data, size_t len, uint8_t* pbtCrc) -{ - return compute_crc(CRC_14443_A, data, len, pbtCrc, pbtCrc+1); -} \ No newline at end of file +void iso14443a_crc(uint8_t *data, size_t len, uint8_t *pbtCrc) { + return compute_crc(CRC_14443_A, data, len, pbtCrc, pbtCrc + 1); +} diff --git a/client/src/mifare/desfire_crypto.h b/client/src/mifare/desfire_crypto.h index 2e044c11d..fb36ea991 100644 --- a/client/src/mifare/desfire_crypto.h +++ b/client/src/mifare/desfire_crypto.h @@ -131,6 +131,6 @@ void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t l void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc); void desfire_crc32_append(uint8_t *data, const size_t len); -void iso14443a_crc_append(uint8_t* data, size_t len); -void iso14443a_crc(uint8_t* data, size_t len, uint8_t* pbtCrc); -#endif \ No newline at end of file +void iso14443a_crc_append(uint8_t *data, size_t len); +void iso14443a_crc(uint8_t *data, size_t len, uint8_t *pbtCrc); +#endif From 797fa7d01a3e9e2405d3ef3ad86a730f4573f41f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 13 Jun 2020 14:41:34 +0200 Subject: [PATCH 19/26] Tolerate exit-like calls from embedded Python script Now sys.exit(0) is silently accepted, while quit() / raise SystemExit / sys.exit() / sys.exit(n) / exit() will output sth a warning such as "Script terminated by SystemExit -1" Still, don't call os._exit(0), it immediately exits. --- client/src/cmdscript.c | 75 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/client/src/cmdscript.c b/client/src/cmdscript.c index 24fd5ec37..4fb87cc27 100644 --- a/client/src/cmdscript.c +++ b/client/src/cmdscript.c @@ -19,7 +19,6 @@ #include #endif - #include "cmdparser.h" // command_t #include "scripting.h" #include "comms.h" @@ -33,6 +32,68 @@ #include "ui.h" #include "fileutils.h" +#ifdef HAVE_PYTHON +// Partly ripped from PyRun_SimpleFileExFlags +// but does not terminate client on sys.exit +// and print exit code only if != 0 +static int Pm3PyRun_SimpleFileNoExit(FILE *fp, const char *filename) +{ + PyObject *m, *d, *v; + int set_file_name = 0, ret = -1; + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + Py_INCREF(m); + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__file__") == NULL) { + PyObject *f; + f = PyUnicode_DecodeFSDefault(filename); + if (f == NULL) + goto done; + if (PyDict_SetItemString(d, "__file__", f) < 0) { + Py_DECREF(f); + goto done; + } + if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) { + Py_DECREF(f); + goto done; + } + set_file_name = 1; + Py_DECREF(f); + } + v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, 1, NULL); + if (v == NULL) { + Py_CLEAR(m); + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + // PyErr_Print() exists if SystemExit so we've to handle it ourselves + PyObject *ty = 0, *er = 0, *tr = 0; + PyErr_Fetch(&ty, &er, &tr); + long err = PyLong_AsLong(er); + if (err) { + PrintAndLogEx(WARNING, "\nScript terminated by " _YELLOW_("SystemExit %li"), err); + } else { + ret = 0; + } + Py_DECREF(ty); + Py_DECREF(er); + Py_DECREF(er); + PyErr_Clear(); + goto done; + } else { + PyErr_Print(); + } + goto done; + } + Py_DECREF(v); + ret = 0; + done: + if (set_file_name && PyDict_DelItemString(d, "__file__")) + PyErr_Clear(); + Py_XDECREF(m); + return ret; +} +#endif // HAVE_PYTHON + typedef enum { PM3_UNSPECIFIED, PM3_LUA, @@ -319,13 +380,17 @@ static int CmdScriptRun(const char *Cmd) { free(script_path); return PM3_ESOFT; } - - PyRun_SimpleFileExFlags(f, preferredName, 1, NULL); + int ret = Pm3PyRun_SimpleFileNoExit(f, preferredName); Py_Finalize(); PyMem_RawFree(program); free(script_path); - PrintAndLogEx(SUCCESS, "\nfinished " _YELLOW_("%s"), preferredName); - return PM3_SUCCESS; + if (ret) { + PrintAndLogEx(WARNING, "\nfinished " _YELLOW_("%s") " with exception", preferredName); + return PM3_ESOFT; + } else { + PrintAndLogEx(SUCCESS, "\nfinished " _YELLOW_("%s"), preferredName); + return PM3_SUCCESS; + } } #endif From b0d969da24cf8f330c7a829978be8ef79cb938f7 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 16:55:30 +0200 Subject: [PATCH 20/26] Fix unsigned vs. signed --- client/src/cmdhfmfdes.c | 348 ++++++++++++++++++++-------------------- 1 file changed, 175 insertions(+), 173 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 9c4fea49a..920fcaba8 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -340,8 +340,8 @@ 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); + uint16_t usize = 1 << (((uint16_t)fsize >> 1) + 1); + uint16_t lsize = 1 << ((uint16_t)fsize >> 1); // is LSB set? if (fsize & 1) @@ -390,7 +390,7 @@ static char *getVersionStr(uint8_t major, uint8_t minor) { } -static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { +static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) { *result_len = 0; if (sw) *sw = 0; @@ -417,7 +417,7 @@ static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, 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); + res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, (int *)result_len); if (res) { return res; } @@ -567,7 +567,7 @@ static const 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) { +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, uint32_t *recv_len, uint16_t *sw, uint32_t splitbysize, bool readalldata) { if (apdu == NULL) { PrintAndLogEx(DEBUG, "APDU=NULL"); return PM3_EINVARG; @@ -583,9 +583,9 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l *sw = 0; uint8_t data[255 * 5] = {0x00}; - int resplen = 0; - int pos = 0; - int i = 1; + uint32_t resplen = 0; + uint32_t pos = 0; + uint32_t i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); @@ -710,7 +710,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp tag->authentication_scheme = AS_NEW; } - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; uint8_t recv_data[256] = {0}; @@ -737,7 +737,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp return 3; } - int expectedlen = 8; + uint32_t expectedlen = 8; if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { expectedlen = 16; } @@ -745,7 +745,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp if (recv_len != expectedlen) { return 4; } - int rndlen = recv_len; + uint32_t rndlen = recv_len; // Part 2 if (payload->mode != MFDES_AUTH_PICC) { @@ -784,7 +784,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp des_decrypt(encRndA, RndA, key->data); memcpy(both, encRndA, rndlen); - for (int x = 0; x < rndlen; x++) { + for (uint32_t x = 0; x < rndlen; x++) { rotRndB[x] = rotRndB[x] ^ encRndA[x]; } @@ -835,7 +835,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } } - int bothlen = 16; + uint32_t bothlen = 16; if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { bothlen = 32; } @@ -896,7 +896,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } rol(RndA, rndlen); - for (int x = 0; x < rndlen; x++) { + for (uint32_t x = 0; x < rndlen; x++) { if (RndA[x] != encRndA[x]) { if (g_debugMode > 1) { PrintAndLogEx(INFO, "Expected_RndA : %s", sprint_hex(RndA, rndlen)); @@ -961,7 +961,7 @@ static void AuthToError(int error) { static int test_desfire_authenticate(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -976,7 +976,7 @@ static int test_desfire_authenticate(void) { static int test_desfire_authenticate_iso(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -991,7 +991,7 @@ static int test_desfire_authenticate_iso(void) { static int test_desfire_authenticate_aes(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -1013,7 +1013,7 @@ static int handler_desfire_freemem(uint32_t *free_mem) { sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E *free_mem = 0; - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; @@ -1037,7 +1037,7 @@ static int handler_desfire_freemem(uint32_t *free_mem) { return res; } -static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, int new_algo, uint8_t *old_key, int old_algo, int aes_version) { +static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, uint8_t new_algo, uint8_t *old_key, uint8_t old_algo, uint8_t aes_version) { key_no &= 0x0F; /* @@ -1060,7 +1060,7 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, int new_a uint8_t data[24 * 4] = {key_no}; sAPDU apdu = {0x90, MFDES_CHANGE_KEY, 0x00, 0x00, 0x01, data}; // 0xC4 - int new_key_length=16; + uint8_t new_key_length = 16; switch (new_algo) { case MFDES_ALGO_DES: case MFDES_ALGO_AES: @@ -1071,58 +1071,58 @@ static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, int new_a break; } - int __cmd_n = 0; - memcpy(data + __cmd_n + 1, new_key, new_key_length); + uint32_t cmdcnt = 0; + memcpy(data + cmdcnt + 1, new_key, new_key_length); if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { if (old_key) { - for (int n = 0; n < new_key_length; n++) { - data[__cmd_n + 1 + n] ^= old_key[n]; + for (uint32_t n = 0; n < new_key_length; n++) { + data[cmdcnt + 1 + n] ^= old_key[n]; } } } - __cmd_n += new_key_length; + cmdcnt += new_key_length; if (new_algo == MFDES_ALGO_AES) { - data[__cmd_n + 1] = aes_version; - __cmd_n += 1; + data[cmdcnt + 1] = aes_version; + cmdcnt += 1; } if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { switch (tag->authentication_scheme) { case AS_LEGACY: - iso14443a_crc_append(data + 1, __cmd_n); - __cmd_n += 2; - iso14443a_crc(new_key, new_key_length, data + __cmd_n); - __cmd_n += 2; + iso14443a_crc_append(data + 1, cmdcnt); + cmdcnt += 2; + iso14443a_crc(new_key, new_key_length, data + cmdcnt); + cmdcnt += 2; break; case AS_NEW: - desfire_crc32_append(data + 1, __cmd_n); - __cmd_n += 4; + desfire_crc32_append(data + 1, cmdcnt); + cmdcnt += 4; - desfire_crc32(new_key, new_key_length, data + __cmd_n); - __cmd_n += 4; + desfire_crc32(new_key, new_key_length, data + cmdcnt); + cmdcnt += 4; break; } } else { switch (tag->authentication_scheme) { case AS_LEGACY: - iso14443a_crc_append(data + 1, __cmd_n); - __cmd_n += 2; + iso14443a_crc_append(data + 1, cmdcnt); + cmdcnt += 2; break; case AS_NEW: - desfire_crc32_append(data, __cmd_n); - __cmd_n += 4; + desfire_crc32_append(data, cmdcnt); + cmdcnt += 4; break; } } - uint8_t *p = mifare_cryto_preprocess_data(tag, data + 1, (size_t *)&__cmd_n, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); - apdu.Lc = (uint8_t)__cmd_n + 1; + uint8_t *p = mifare_cryto_preprocess_data(tag, data + 1, (size_t *)&cmdcnt, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); + apdu.Lc = (uint8_t)cmdcnt + 1; apdu.data = p; - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, true); @@ -1175,7 +1175,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; - uint8_t i; + uint32_t i; bool is_valid = false; for (i = 0; i < ARRAYLEN(nxp_desfire_public_keys); i++) { @@ -1224,7 +1224,7 @@ static int handler_desfire_signature(uint8_t *signature, size_t *signature_len) uint8_t c[] = {0x00}; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, sizeof(c), c}; // 0x3C - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { @@ -1289,7 +1289,7 @@ static int handler_desfire_getkeysettings(uint8_t *key_settings, uint8_t *num_ke } sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 - int recv_len = 0; + uint32_t 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); @@ -1316,7 +1316,7 @@ static int handler_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { return PM3_EINVARG; } sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); @@ -1335,7 +1335,7 @@ static int handler_desfire_getuid(uint8_t *uid) { return PM3_EINVARG; } sAPDU apdu = {0x90, MFDES_GET_UID, 0x00, 0x00, 0x00, NULL}; //0x51 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, uid, &recv_len, &sw, 0, true); @@ -1350,7 +1350,7 @@ static int handler_desfire_getuid(uint8_t *uid) { static int handler_desfire_commit_transaction(void) { sAPDU apdu = {0x90, MFDES_COMMIT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xC7 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, true); @@ -1365,7 +1365,7 @@ static int handler_desfire_commit_transaction(void) { /*static int handler_desfire_abort_transaction(void) { sAPDU apdu = {0x90, MFDES_ABORT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xA7 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, true); @@ -1379,7 +1379,7 @@ static int handler_desfire_commit_transaction(void) { }*/ // --- GET APPIDS -static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { +static int handler_desfire_appids(uint8_t *dest, uint32_t *app_ids_len) { if (dest == NULL) { PrintAndLogEx(DEBUG, "DEST=NULL"); return PM3_EINVARG; @@ -1390,7 +1390,7 @@ static int handler_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; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); @@ -1400,7 +1400,7 @@ static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; - *app_ids_len = (uint8_t)recv_len & 0xFF; + *app_ids_len = (uint8_t)(recv_len & 0xFF); return res; } @@ -1417,11 +1417,10 @@ static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { *dfname_count = 0; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d - int recv_len = 0; + uint32_t 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) { - if (sw == status(MFDES_E_ILLEGAL_COMMAND_CODE)) return PM3_SUCCESS; return res; } @@ -1438,7 +1437,7 @@ static int handler_desfire_select_application(uint8_t *aid) { } if (aid == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a - int recv_len = 0; + uint32_t 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) { @@ -1472,14 +1471,14 @@ static int key_setting_to_algo(uint8_t aid[3], uint8_t *key_setting, mifare_des_ return res; } -static int handler_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { +static int handler_desfire_fileids(uint8_t *dest, uint32_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; + uint32_t recv_len = 0; uint16_t sw = 0; *file_ids_len = 0; int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0, true); @@ -1493,7 +1492,7 @@ static int handler_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { } // none, verified -static int handler_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { +static int handler_desfire_filesettings(uint8_t file_id, uint8_t *dest, uint32_t *destlen) { if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (destlen == NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); @@ -1538,7 +1537,7 @@ static int handler_desfire_createapp(aidhdr_t *aidhdr, bool usename, bool usefid } uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (data != NULL) free(data); if (res != PM3_SUCCESS) { @@ -1550,11 +1549,11 @@ static int handler_desfire_createapp(aidhdr_t *aidhdr, bool usename, bool usefid return res; } -static int handler_desfire_deleteapp(uint8_t *aid) { +static int handler_desfire_deleteapp(const uint8_t *aid) { if (aid == NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA + sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, (uint8_t *)aid}; // 0xDA uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; 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)); @@ -1567,7 +1566,7 @@ static int handler_desfire_deleteapp(uint8_t *aid) { static int handler_desfire_credit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x0C uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; size_t plen = apdu.Lc; uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); @@ -1586,7 +1585,7 @@ static int handler_desfire_credit(mfdes_value_t *value, uint8_t cs) { static int handler_desfire_limitedcredit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_LIMITED_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x1C uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; size_t plen = apdu.Lc; uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); @@ -1605,7 +1604,7 @@ static int handler_desfire_limitedcredit(mfdes_value_t *value, uint8_t cs) { static int handler_desfire_debit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_DEBIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0xDC uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; size_t plen = apdu.Lc; uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); @@ -1627,7 +1626,7 @@ static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, if (type == MFDES_RECORD_FILE) apdu.INS = MFDES_READ_RECORDS; //0xBB uint16_t sw = 0; - int resplen = 0; + uint32_t resplen = 0; size_t plen = apdu.Lc; uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); @@ -1651,7 +1650,7 @@ static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, } -static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen, uint8_t cs) { +static int handler_desfire_getvalue(mfdes_value_t *value, uint32_t *resplen, uint8_t cs) { if (value->fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_VALUE, 0x00, 0x00, 0x01, &value->fileno}; // 0xBD uint16_t sw = 0; @@ -1682,9 +1681,9 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, if (data->fileno > 0x1F) return PM3_EINVARG; uint32_t datatowrite = le24toh(data->length); uint32_t offset = le24toh(data->offset); - int datasize; - int pos = 0; - int recvlen = 0; + uint32_t datasize; + uint32_t pos = 0; + uint32_t recvlen = 0; int res = PM3_SUCCESS; uint16_t sw = 0; uint8_t tmp[59] = {0}; @@ -1742,7 +1741,7 @@ static int handler_desfire_deletefile(uint8_t fileno) { if (fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_DELETE_FILE, 0x00, 0x00, 1, &fileno}; // 0xDF uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't delete file -> %s"), GetErrorString(res, &sw)); @@ -1756,7 +1755,7 @@ static int handler_desfire_clearrecordfile(uint8_t fileno) { if (fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_CLEAR_RECORD_FILE, 0x00, 0x00, 1, &fileno}; // 0xEB uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't clear record file -> %s"), GetErrorString(res, &sw)); @@ -1779,7 +1778,7 @@ static int handler_desfire_create_value_file(mfdes_value_file_t *value) { sAPDU apdu = {0x90, MFDES_CREATE_VALUE_FILE, 0x00, 0x00, sizeof(mfdes_value_file_t), (uint8_t *)value}; // 0xCc uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create value -> %s"), GetErrorString(res, &sw)); @@ -1794,7 +1793,7 @@ static int handler_desfire_create_std_file(mfdes_file_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_STD_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCD uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create file -> %s"), GetErrorString(res, &sw)); @@ -1810,7 +1809,7 @@ static int handler_desfire_create_linearrecordfile(mfdes_linear_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_LINEAR_RECORD_FILE, 0x00, 0x00, sizeof(mfdes_linear_t), (uint8_t *)file}; // 0xC1 uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create linear record file -> %s"), GetErrorString(res, &sw)); @@ -1826,7 +1825,7 @@ static int handler_desfire_create_cyclicrecordfile(mfdes_linear_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_CYCLIC_RECORD_FILE, 0x00, 0x00, sizeof(mfdes_linear_t), (uint8_t *)file}; // 0xC0 uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create cyclic record file -> %s"), GetErrorString(res, &sw)); @@ -1842,7 +1841,7 @@ static int handler_desfire_create_backup_file(mfdes_file_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_BACKUP_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCB uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create backup file -> %s"), GetErrorString(res, &sw)); @@ -2030,7 +2029,7 @@ static int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t *aid, if (memcmp(aid, "\x00\x00\x00", 3) != 0) { uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; res = handler_desfire_fileids(file_ids, &file_ids_len); if (res != PM3_SUCCESS) return res; } @@ -2272,12 +2271,12 @@ static int selectfile(uint8_t *aid, uint32_t fileno, uint8_t *cs) { } uint8_t filesettings[20] = {0}; - int fileset_len = 0; + uint32_t fileset_len = 0; int res = handler_desfire_filesettings(fileno, filesettings, &fileset_len); if (tag->session_key != NULL) { mfdes_auth_res_t rpayload; - int keyno = (filesettings[0] >> 4) & 0xF; + uint8_t keyno = (uint8_t)((filesettings[0] >> 4) & 0xF); if (keyno != 0xE && currentauth[keyno].keyno == keyno) { if (handler_desfire_auth(¤tauth[keyno], &rpayload) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Couldn't authenticate key.")); @@ -2312,10 +2311,10 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx,1, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,2, aid, &aidlength); + CLIGetHexWithReturn(ctx, 2, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -2437,25 +2436,25 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { arg_param_end }; - CLIExecWithReturn(ctx,Cmd, argtable, false); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx,1, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int fidlength = 0; uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(ctx,2), fid, 2, &fidlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(ctx,3); + uint8_t comset = arg_get_int(ctx, 3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx,4, ar, &arlength); + CLIGetHexWithReturn(ctx, 4, ar, &arlength); int fsizelen = 0; uint8_t filesize[3] = {0}; - CLIGetHexWithReturn(ctx,5, filesize, &fsizelen); + CLIGetHexWithReturn(ctx, 5, filesize, &fsizelen); - bool isbackup = arg_get_lit(ctx,6); + bool isbackup = arg_get_lit(ctx, 6); int aidlength = 3; uint8_t aid[3] = {0}; CLIGetHexWithReturn(ctx, 7, aid, &aidlength); @@ -2591,13 +2590,13 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { return PM3_ESOFT; } - int len = 0; + uint32_t len = 0; int res = handler_desfire_getvalue(&value, &len, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read value from File %u:", _fileno[0]); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); - for (int i = 0; i < len; i += 16) { + for (uint32_t i = 0; i < len; i += 16) { PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&value.value[i], len > 16 ? 16 : len), sprint_ascii(&value.value[i], len > 16 ? 16 : len)); } } else { @@ -2628,24 +2627,24 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_param_end }; - CLIExecWithReturn(ctx,Cmd, argtable, false); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx,1, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int offsetlength = 0; uint8_t offset[3] = {0}; - CLIParamHexToBuf(arg_get_str(ctx,2), offset, 3, &offsetlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); int flength = 0; uint8_t filesize[3] = {0}; - CLIParamHexToBuf(arg_get_str(ctx,3), filesize, 3, &flength); + CLIParamHexToBuf(arg_get_str(ctx, 3), filesize, 3, &flength); - int type = arg_get_int(ctx,4); + int type = arg_get_int(ctx, 4); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,5, aid, &aidlength); + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -2677,7 +2676,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { memcpy(ft.length, filesize, 3); ft.fileno = _fileno[0]; - uint32_t bytestoread = le24toh(filesize); + uint32_t bytestoread = (uint32_t)le24toh(filesize); bytestoread &= 0xFFFFFF; if (bytestoread == 0) @@ -2748,16 +2747,16 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx,1, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); value.fileno = _fileno[0]; int vlength = 0x0; - CLIParamHexToBuf(arg_get_str(ctx,2), value.value, 4, &vlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), value.value, 4, &vlength); - int mode = arg_get_int(ctx,3); + int mode = arg_get_int(ctx, 3); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,4, aid, &aidlength); + CLIGetHexWithReturn(ctx, 4, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -2851,7 +2850,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { int offsetlength = 0; uint8_t offset[3] = {0}; - CLIParamHexToBuf(arg_get_str(ctx,2), offset, 3, &offsetlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); int dlength = 0xFFFF; uint8_t *data = (uint8_t *)calloc(dlength, sizeof(uint8_t)); @@ -2860,12 +2859,12 @@ static int CmdHF14ADesWriteData(const char *Cmd) { CLIParserFree(ctx); return PM3_EMALLOC; } - CLIParamHexToBuf(arg_get_str(ctx,3), data, 0xFFFF, &dlength); + CLIParamHexToBuf(arg_get_str(ctx, 3), data, 0xFFFF, &dlength); - int type = arg_get_int(ctx,4); + int type = arg_get_int(ctx, 4); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,5, aid, &aidlength); + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -2969,25 +2968,25 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { int fidlength = 0; uint8_t fid[2] = {0}; - CLIParamHexToBuf(arg_get_str(ctx,2), fid, 2, &fidlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(ctx,3); + uint8_t comset = arg_get_int(ctx, 3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx,4, ar, &arlength); + CLIGetHexWithReturn(ctx, 4, ar, &arlength); int rsizelen = 0; uint8_t recordsize[3] = {0}; - CLIGetHexWithReturn(ctx,5, recordsize, &rsizelen); + CLIGetHexWithReturn(ctx, 5, recordsize, &rsizelen); int msizelen = 0; uint8_t maxnumrecords[3] = {0}; - CLIGetHexWithReturn(ctx,6, maxnumrecords, &msizelen); + CLIGetHexWithReturn(ctx, 6, maxnumrecords, &msizelen); - bool cyclic = arg_get_lit(ctx,7); + bool cyclic = arg_get_lit(ctx, 7); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,8, aid, &aidlength); + CLIGetHexWithReturn(ctx, 8, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -3102,29 +3101,29 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { uint8_t _fileno[1] = {0}; CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); - uint8_t comset = arg_get_int(ctx,2); + uint8_t comset = arg_get_int(ctx, 2); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx,3, ar, &arlength); + CLIGetHexWithReturn(ctx, 3, ar, &arlength); int lllen = 0; uint8_t lowerlimit[4] = {0}; - CLIGetHexWithReturn(ctx,4, lowerlimit, &lllen); + CLIGetHexWithReturn(ctx, 4, lowerlimit, &lllen); int ullen = 0; uint8_t upperlimit[4] = {0}; - CLIGetHexWithReturn(ctx,5, upperlimit, &ullen); + CLIGetHexWithReturn(ctx, 5, upperlimit, &ullen); int vllen = 0; uint8_t value[4] = {0}; - CLIGetHexWithReturn(ctx,6, value, &vllen); + CLIGetHexWithReturn(ctx, 6, value, &vllen); int limitedlen = 0; uint8_t limited[1] = {0}; - CLIGetHexWithReturn(ctx,7, limited, &limitedlen); + CLIGetHexWithReturn(ctx, 7, limited, &limitedlen); int aidlength = 3; uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx,8, aid, &aidlength); + CLIGetHexWithReturn(ctx, 8, aid, &aidlength); swap24(aid); CLIParserFree(ctx); @@ -3219,7 +3218,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { sAPDU apdu = {0x90, MFDES_FORMAT_PICC, 0x00, 0x00, 0, NULL}; // 0xDF uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't format picc -> %s"), GetErrorString(res, &sw)); @@ -3491,9 +3490,9 @@ static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) { PrintAndLogEx(INFO, " Lower limit: %d (0x%X) - Upper limit: %d (0x%X) - limited credit value: %d (0x%X) - limited credit enabled: %d", lowerlimit, lowerlimit, upperlimit, upperlimit, limitcredvalue, limitcredvalue, limited_credit_enabled); return PM3_SUCCESS; } else if (src_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { - int recordsize = (src[6] << 16) + (src[5] << 8) + src[4]; - int maxrecords = (src[9] << 16) + (src[8] << 8) + src[7]; - int currentrecord = (src[12] << 16) + (src[11] << 8) + src[10]; + uint32_t recordsize = (src[6] << 16) + (src[5] << 8) + src[4]; + uint32_t maxrecords = (src[9] << 16) + (src[8] << 8) + src[7]; + uint32_t currentrecord = (src[12] << 16) + (src[11] << 8) + src[10]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); @@ -3509,10 +3508,10 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; dfname_t dfnames[255]; uint8_t dfname_count = 0; @@ -3533,7 +3532,7 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(INFO, "-- Mifare DESFire Dump ----------------------"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); - for (int i = 0; i < app_ids_len; i += 3) { + for (uint32_t i = 0; i < app_ids_len; i += 3) { aid[0] = app_ids[i]; aid[1] = app_ids[i + 1]; @@ -3542,7 +3541,7 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]); PrintAndLogEx(SUCCESS, " AID Function Cluster 0x%02X: " _YELLOW_("%s"), aid[2], cluster_to_text(aid[2])); - for (int m = 0; m < dfname_count; m++) { + for (uint8_t 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[1], dfnames[m].fid[0], dfnames[m].name); } @@ -3559,11 +3558,11 @@ static int CmdHF14ADesDump(const char *Cmd) { res = handler_desfire_fileids(file_ids, &file_ids_len); if (res != PM3_SUCCESS) continue; - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { PrintAndLogEx(SUCCESS, "\n\n Fileid %d (0x%02x)", file_ids[j], file_ids[j]); uint8_t filesettings[20] = {0}; - int fileset_len = 0; + uint32_t fileset_len = 0; res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res != PM3_SUCCESS) continue; @@ -3584,7 +3583,7 @@ static int CmdHF14ADesDump(const char *Cmd) { } fdata.data = data; - res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE,filesettings[1]); + res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3604,12 +3603,12 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(NORMAL, "\n\nValue file: 0x%0x", file_ids[j]); mfdes_value_t value; value.fileno = file_ids[j]; - int len = 0; - res = handler_desfire_getvalue(&value, &len,filesettings[1]); + uint32_t len = 0; + res = handler_desfire_getvalue(&value, &len, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); - for (int n = 0; n < len; n += 16) { + for (uint32_t n = 0; n < len; n += 16) { PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len)); } } else { @@ -3619,8 +3618,8 @@ static int CmdHF14ADesDump(const char *Cmd) { } } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { - int maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7]; - int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; + uint32_t maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7]; + uint32_t filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; mfdes_data_t fdata; fdata.fileno = file_ids[j]; memset(fdata.length, 0, 3); @@ -3631,13 +3630,13 @@ static int CmdHF14ADesDump(const char *Cmd) { } fdata.data = data; - for (int offset = 0; offset < maxrecords; offset++) { + for (uint32_t offset = 0; offset < maxrecords; offset++) { PrintAndLogEx(NORMAL, "\n\nRecord offset: %024x", offset); memset(data, 0, filesize); fdata.offset[0] = offset & 0xFF; fdata.offset[1] = (offset >> 8) & 0xFF; fdata.offset[2] = (offset >> 16) & 0xFF; - res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE,filesettings[1]); + res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3667,10 +3666,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; dfname_t dfnames[255]; uint8_t dfname_count = 0; @@ -3690,7 +3689,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { 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) { + for (uint32_t i = 0; i < app_ids_len; i += 3) { aid[0] = app_ids[i]; aid[1] = app_ids[i + 1]; @@ -3708,7 +3707,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]); PrintAndLogEx(SUCCESS, " AID Function Cluster 0x%02X: " _YELLOW_("%s"), aid[2], cluster_to_text(aid[2])); - for (int m = 0; m < dfname_count; m++) { + for (uint8_t 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[1], dfnames[m].fid[0], dfnames[m].name); } @@ -3724,12 +3723,12 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { if (res != PM3_SUCCESS) continue; PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") " file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); uint8_t filesettings[20] = {0}; - int fileset_len = 0; - int maclen = 0; // To be implemented + uint32_t fileset_len = 0; + uint32_t maclen = 0; // To be implemented res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res != PM3_SUCCESS) continue; @@ -3890,29 +3889,32 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIParserFree(ctx); if (cmdAuthAlgo == MFDES_ALGO_AES) { + if (keylen == 0) { + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); + } keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + if (keylen == 0) { + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); + } keylength = 16; } else if (cmdAuthAlgo == MFDES_ALGO_DES) { - keylength = 8; - } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { - keylength = 24; - } - if (keylen == 0) { - if (cmdAuthAlgo == MFDES_ALGO_AES) { - keylen = 16; - memcpy(key, aesdefaultkeys[0], keylen); - } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { - keylen = 16; - memcpy(key, aesdefaultkeys[0], keylen); - } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + if (keylen == 0) { keylen = 8; memcpy(key, desdefaultkeys[0], keylen); - } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + } + keylength = 8; + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + if (keylen == 0) { keylen = 24; memcpy(key, k3kdefaultkeys[0], keylen); } - } else if ((keylen < 8) || (keylen > 24)) { + keylength = 24; + } + + if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); return PM3_EINVARG; } @@ -4005,23 +4007,23 @@ static int AuthCheckDesfire(uint8_t *aid, if (memcmp(aid, "\x00\x00\x00", 3) != 0) { uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; // Get File IDs if (handler_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { uint8_t filesettings[20] = {0}; - int fileset_len = 0; + uint32_t fileset_len = 0; res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res == PM3_SUCCESS) { uint16_t accrights = (filesettings[3] << 8) + filesettings[2]; - 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; + uint8_t change_access_rights = accrights & 0xF; + uint8_t read_write_access = (accrights >> 4) & 0xF; + uint8_t write_access = (accrights >> 8) & 0xF; + uint8_t read_access = (accrights >> 12) & 0xF; if (change_access_rights == 0xE) change_access_rights = 0x0; if (read_write_access == 0xE) read_write_access = 0x0; @@ -4053,7 +4055,7 @@ static int AuthCheckDesfire(uint8_t *aid, } if (file_ids_len == 0) { - for (int z = 0; z < 0xE; z++) { + for (uint8_t z = 0; z < 0xE; z++) { usedkeys[z] = 1; des = true; tdes = true; @@ -4074,7 +4076,7 @@ static int AuthCheckDesfire(uint8_t *aid, for (uint8_t keyno = 0; keyno < 0xE; keyno++) { if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { - for (int curkey = 0; curkey < deskeyListLen; curkey++) { + for (uint32_t curkey = 0; curkey < deskeyListLen; curkey++) { mfdes_auth_res_t rpayload; error = desfire_authenticate(MFDES_AUTH_DES, MFDES_ALGO_DES, aid, deskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { @@ -4313,11 +4315,11 @@ static int CmdHF14aDesChk(const char *Cmd) { // 1-byte pattern search mode if (pattern1b) { - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(aeskeyList[i], i, 16); - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(deskeyList[i], i, 8); - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(k3kkeyList[i], i, 24); aeskeyListLen = 0x100; deskeyListLen = 0x100; @@ -4376,7 +4378,7 @@ static int CmdHF14aDesChk(const char *Cmd) { bool result = false; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; if (handler_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); @@ -4389,7 +4391,7 @@ static int CmdHF14aDesChk(const char *Cmd) { app_ids_len = 1; } - for (int x = 0; x < app_ids_len / 3; x++) { + for (uint32_t x = 0; x < app_ids_len / 3; x++) { uint32_t curaid = (app_ids[x * 3] & 0xFF) + ((app_ids[(x * 3) + 1] & 0xFF) << 8) + ((app_ids[(x * 3) + 2] & 0xFF) << 16); PrintAndLogEx(ERR, "Checking aid 0x%06X...", curaid); res = AuthCheckDesfire(&app_ids[x * 3], deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, foundKeys, &result); From 9a07c06596c1234fe2b7ff78d818f07546005de4 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 17:16:17 +0200 Subject: [PATCH 21/26] Fix htole32 issue --- client/src/mifare/desfire_crypto.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c index b9ccddf77..95784aaa7 100644 --- a/client/src/mifare/desfire_crypto.c +++ b/client/src/mifare/desfire_crypto.c @@ -560,7 +560,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data + *nbytes, key_macing_length(key))); PrintAndLogEx(NORMAL, "Actual MAC %s", sprint_hex(edata + edl - 8, key_macing_length(key))); #endif - #ifdef WITH_DEBUG +#ifdef WITH_DEBUG Dbprintf("MACing not verified"); hexdump((uint8_t *)data + *nbytes, key_macing_length(key), "Expect ", 0); hexdump((uint8_t *)edata + edl - 8, key_macing_length(key), "Actual ", 0); @@ -897,6 +897,10 @@ desfire_crc32_byte(uint32_t *crc, const uint8_t value) { } } +#ifndef htole32 + #define htole32(x) (x) +#endif + void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) { uint32_t desfire_crc = CRC32_PRESET; for (size_t i = 0; i < len; i++) { From 6f336832dabd9ca8b3137af45e42fe8a1b40f3c8 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 17:20:48 +0200 Subject: [PATCH 22/26] Add Changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f3d8c886..ce186a2b0 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] + - Fix `hf mfdes` authentification issues, DES working (@bkerler) - Add Android cross-compilation to client cmake (@dxl, @doegox) - Fix `emv scan` - now saves in current folder and uses unique names (@iceman1001) - Fix pm3.sh - parse COM ports larger than one digit (@doegox) From a9bfcb015c24443bdd9c8b45c2b1d5710df61921 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 13 Jun 2020 17:49:33 +0200 Subject: [PATCH 23/26] style --- client/src/fileutils.c | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 8528fa770..3e2f252cb 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -228,17 +228,20 @@ static char *filenamemcopy(const char *preferredName, const char *suffix) { char *newfilenamemcopy(const char *preferredName, const char *suffix) { if (preferredName == NULL) return NULL; if (suffix == NULL) return NULL; - uint16_t preferredNameLen = strlen(preferredName); + + uint16_t p_namelen = strlen(preferredName); if (str_endswith(preferredName, suffix)) - preferredNameLen -= strlen(suffix); - char *fileName = (char *) calloc(preferredNameLen + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename + p_namelen -= strlen(suffix); + + char *fileName = (char *) calloc(p_namelen + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename if (fileName == NULL) { return NULL; } + int num = 1; - sprintf(fileName, "%.*s%s", preferredNameLen, preferredName, suffix); + sprintf(fileName, "%.*s%s", p_namelen, preferredName, suffix); while (fileExists(fileName)) { - sprintf(fileName, "%.*s-%d%s", preferredNameLen, preferredName, num, suffix); + sprintf(fileName, "%.*s-%d%s", p_namelen, preferredName, num, suffix); num++; } return fileName; @@ -475,7 +478,7 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } break; } - case jsfMfPlusKeys: + case jsfMfPlusKeys: { JsonSaveStr(root, "FileType", "mfp"); JsonSaveBufAsHexCompact(root, "$.Card.UID", &data[0], 7); JsonSaveBufAsHexCompact(root, "$.Card.SAK", &data[10], 1); @@ -503,7 +506,8 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } } break; - case jsfMfDesfireKeys: + } + case jsfMfDesfireKeys: { JsonSaveStr(root, "FileType", "mfdes"); JsonSaveBufAsHexCompact(root, "$.Card.UID", &data[0], 7); JsonSaveBufAsHexCompact(root, "$.Card.SAK", &data[10], 1); @@ -541,9 +545,11 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } } break; - case jsfCustom: + } + case jsfCustom: { (*callback)(root); break; + } default: break; } From e7b2dbd5e84b46eb8794d6d911e7c83af23bc1d7 Mon Sep 17 00:00:00 2001 From: Bjoern Kerler Date: Sat, 13 Jun 2020 17:58:47 +0200 Subject: [PATCH 24/26] Remove unnecessary crc --- client/src/mifare/desfire_crypto.c | 29 ++--------------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c index 95784aaa7..0ec6bd70d 100644 --- a/client/src/mifare/desfire_crypto.c +++ b/client/src/mifare/desfire_crypto.c @@ -881,37 +881,12 @@ void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *i } } -#define CRC32_PRESET 0xFFFFFFFF - -static void -desfire_crc32_byte(uint32_t *crc, const uint8_t value) { - /* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */ - const uint32_t poly = 0xEDB88320; - - *crc ^= value; - for (int current_bit = 7; current_bit >= 0; current_bit--) { - int bit_out = (*crc) & 0x00000001; - *crc >>= 1; - if (bit_out) - *crc ^= poly; - } -} - -#ifndef htole32 - #define htole32(x) (x) -#endif - void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) { - uint32_t desfire_crc = CRC32_PRESET; - for (size_t i = 0; i < len; i++) { - desfire_crc32_byte(&desfire_crc, data[i]); - } - - *((uint32_t *)(crc)) = htole32(desfire_crc); + crc32_ex(data,len,crc); } void desfire_crc32_append(uint8_t *data, const size_t len) { - desfire_crc32(data, len, data + len); + crc32_ex(data, len, data + len); } void iso14443a_crc_append(uint8_t *data, size_t len) { From ae36cc6e1b10033ebf637c9993675d54b48125b7 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 13 Jun 2020 18:05:31 +0200 Subject: [PATCH 25/26] color document --- doc/colors_notes.md | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 doc/colors_notes.md diff --git a/doc/colors_notes.md b/doc/colors_notes.md new file mode 100644 index 000000000..7756addd9 --- /dev/null +++ b/doc/colors_notes.md @@ -0,0 +1,50 @@ + +# Notes on Color usage. + +## Table of Contents + * [style/color](#style_color) + * [Proxspace](#proxspace) + * [](#) + +The client should autodetect color support when starting. + +You can also use the command `pref show` to see and set your personal setting. + +Why use colors in the Proxmark client? When evertyhing is white it is hard to extract the important information fast. You also need new-lines for extra space to be easier to read. +We have gradually been introducing this color scheme into the client since we got decent color support on all systems: OSX, Linux, WSL, Proxspace. + + +## style/color +^[Top](#top) +The following definition has be crystalized out from these experiments. Its not set in stone yet so take this document as a guideline for how to create unified system scheme. + +### Definition +^[Top](#top) +- blue - system related headers, banner +- white - normal +- cyan - headers +- red - warning, error, catastrophic failures +- yellow - informative (to make things stick out from white blob) +- green - successful, (to make things stick out from white blob) +- magenta - device side messages + + +### Styled header +^[Top](#top) +``` + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); +``` +For more examples, see also all **-h** helptext now in the LUA scripts. +For the command help texts using _YELLOW_ for the example makes it very easy to see what is the command vs the description. + +### non styled header +^[Top](#top) +Most commands doesn't use a header yet. We added it to make it standout (ie: yellow, green) of the informative tidbits in the output of a command. + + +## Proxspace +^[Top](#top) +Proxspace has support for colors. + From 675da483ad5a25184cd08f0f4a0fbde93c8cc96b Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 13 Jun 2020 18:07:03 +0200 Subject: [PATCH 26/26] link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d69ba832..1a1a06699 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ |[Notes on external flash](/doc/ext_flash_notes.md)|[Notes on loclass](/doc/loclass_notes.md)|[Notes on Coverity Scan Config & Run](/doc/md/Development/Coverity-Scan-Config-%26-Run.md)| |[Notes on file formats used with Proxmark3](/doc/extensions_notes.md)|[Notes on MFU binary format](/doc/mfu_binary_format_notes.md)|[Notes on FPGA & ARM](/doc/fpga_arm_notes.md)| |[Developing standalone mode](/armsrc/Standalone/readme.md)|[Wiki about standalone mode](https://github.com/RfidResearchGroup/proxmark3/wiki/Standalone-mode)|| - +|[Notes on Color usage](/doc/colors_notes.md)|| ## Build for non-RDV4 Proxmark3 platforms