From 7e2fd2a9536cc21860f55a2860c6ed2301d7423e Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 15:37:30 +0300 Subject: [PATCH 01/37] move functions --- client/src/cmdhfmfdes.c | 428 ++++++++++++++++++++-------------------- 1 file changed, 214 insertions(+), 214 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 2689ea665..f7452beda 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -2073,219 +2073,6 @@ static int selectfile(uint8_t *aid, uint8_t fileno, uint8_t *cs) { return res; } -static int CmdHF14ADesReadData(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfdes read", - "Read data from File\n" - "Make sure to select aid or authenticate aid before running this command.", - "hf mfdes read -n 1 -t 0 -o 000000 -l 000000 -a 123456\n" - "hf mfdes read -n 1 -t 0 --> Read all data from standard file, fileno 1" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("n", "fileno", "", "File Number (0 - 31)"), - arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian)"), - arg_strx0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data)"), - arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), - arg_strx0("a", "aid", "", "App ID to select (3 hex bytes, big endian)"), - arg_param_end - }; - - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fno = arg_get_int_def(ctx, 1, 0); - - int offsetlength = 0; - uint8_t offset[3] = {0}; - int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); - - int flength = 0; - uint8_t filesize[3] = {0}; - int res_flen = CLIParamHexToBuf(arg_get_str(ctx, 3), filesize, 3, &flength); - - int type = arg_get_int(ctx, 4); - - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 5, aid, &aidlength); - swap24(aid); - CLIParserFree(ctx); - - if (type > 1) { - PrintAndLogEx(ERR, "Invalid file type (0 = Standard/Backup, 1 = Record)"); - return PM3_EINVARG; - } - - if (res_offset || (offsetlength != 3 && offsetlength != 0)) { - PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); - return PM3_EINVARG; - } - - if (fno > 0x1F) { - PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); - return PM3_EINVARG; - } - - if (res_flen) { - PrintAndLogEx(ERR, "File size input error"); - return PM3_EINVARG; - } - - swap24(filesize); - swap24(offset); - - mfdes_data_t ft; - memcpy(ft.offset, offset, 3); - memcpy(ft.length, filesize, 3); - ft.fileno = fno; - - uint32_t bytestoread = (uint32_t)le24toh(filesize); - bytestoread &= 0xFFFFFF; - - 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, cs); - if (res == PM3_SUCCESS) { - uint32_t len = le24toh(ft.length); - - PrintAndLogEx(SUCCESS, "Read %u bytes from file %d", ft.fileno, len); - PrintAndLogEx(INFO, "Offset | Data | Ascii"); - PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); - - for (uint32_t i = 0; i < len; i += 16) { - uint32_t l = len - i; - PrintAndLogEx(INFO, "%3d/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); - DropFieldDesfire(); - return res; - } - free(data); - } - DropFieldDesfire(); - return res; -} - -static int CmdHF14ADesWriteData(const char *Cmd) { - - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfdes write", - "Write data to file\n" - "Make sure to select aid or authenticate aid before running this command.", - "hf mfdes write -n 01 -t 0 -o 000000 -d 3132333435363738" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("n", "fileno", "", "File Number (0 - 31)"), - arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian), optional"), - arg_strx0("d", "data", "", "Data to write (hex bytes, 256 bytes max)"), - arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), - arg_strx0("a", "aid", "", "App ID to select as hex bytes (3 bytes, big endian)"), - arg_param_end - }; - - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fno = arg_get_int_def(ctx, 1, 0); - - int offsetlength = 0; - uint8_t offset[3] = {0}; - int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); - - // iceman: we only have a 1024 byte commandline input array. So this is pointlessly large. - // with 2char hex, 512bytes could be input. - // Instead large binary inputs should be BINARY files and written to card. - int dlength = 512; - uint8_t data[512] = {0}; - int res_data = CLIParamHexToBuf(arg_get_str(ctx, 3), data, 512, &dlength); - - int type = arg_get_int(ctx, 4); - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 5, aid, &aidlength); - swap24(aid); - - CLIParserFree(ctx); - - swap24(offset); - - if (type < 0 || type > 1) { - PrintAndLogEx(ERR, "Unknown type (0=Standard/Backup, 1=Record)"); - return PM3_EINVARG; - } - - if (res_data || dlength == 0) { - PrintAndLogEx(ERR, "Data needs some hex bytes to write"); - return PM3_EINVARG; - } - - if (res_offset || (offsetlength != 3 && offsetlength != 0)) { - PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); - return PM3_EINVARG; - } - - if (fno > 0x1F) { - PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); - return PM3_EINVARG; - } - - mfdes_data_t ft; - - memcpy(ft.offset, offset, 3); - htole24(dlength, ft.length); - ft.fileno = fno; - - 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, fno, &cs) != PM3_SUCCESS) { - PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); - DropFieldDesfire(); - return PM3_ESOFT; - } - - int res = PM3_ESOFT; - ft.data = data; - res = handler_desfire_writedata(&ft, type, cs); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "Successfully wrote data"); - } else { - PrintAndLogEx(ERR, "Couldn't read data. Error %d", res); - } - DropFieldDesfire(); - return res; -} - static int CmdHF14ADesInfo(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes info", @@ -6443,6 +6230,219 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { return PM3_SUCCESS; } +static int CmdHF14ADesReadData(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes read", + "Read data from File\n" + "Make sure to select aid or authenticate aid before running this command.", + "hf mfdes read -n 1 -t 0 -o 000000 -l 000000 -a 123456\n" + "hf mfdes read -n 1 -t 0 --> Read all data from standard file, fileno 1" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("n", "fileno", "", "File Number (0 - 31)"), + arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian)"), + arg_strx0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data)"), + arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), + arg_strx0("a", "aid", "", "App ID to select (3 hex bytes, big endian)"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, false); + int fno = arg_get_int_def(ctx, 1, 0); + + int offsetlength = 0; + uint8_t offset[3] = {0}; + int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); + + int flength = 0; + uint8_t filesize[3] = {0}; + int res_flen = CLIParamHexToBuf(arg_get_str(ctx, 3), filesize, 3, &flength); + + int type = arg_get_int(ctx, 4); + + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); + swap24(aid); + CLIParserFree(ctx); + + if (type > 1) { + PrintAndLogEx(ERR, "Invalid file type (0 = Standard/Backup, 1 = Record)"); + return PM3_EINVARG; + } + + if (res_offset || (offsetlength != 3 && offsetlength != 0)) { + PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); + return PM3_EINVARG; + } + + if (fno > 0x1F) { + PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); + return PM3_EINVARG; + } + + if (res_flen) { + PrintAndLogEx(ERR, "File size input error"); + return PM3_EINVARG; + } + + swap24(filesize); + swap24(offset); + + mfdes_data_t ft; + memcpy(ft.offset, offset, 3); + memcpy(ft.length, filesize, 3); + ft.fileno = fno; + + uint32_t bytestoread = (uint32_t)le24toh(filesize); + bytestoread &= 0xFFFFFF; + + 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, cs); + if (res == PM3_SUCCESS) { + uint32_t len = le24toh(ft.length); + + PrintAndLogEx(SUCCESS, "Read %u bytes from file %d", ft.fileno, len); + PrintAndLogEx(INFO, "Offset | Data | Ascii"); + PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); + + for (uint32_t i = 0; i < len; i += 16) { + uint32_t l = len - i; + PrintAndLogEx(INFO, "%3d/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); + DropFieldDesfire(); + return res; + } + free(data); + } + DropFieldDesfire(); + return res; +} + +static int CmdHF14ADesWriteData(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes write", + "Write data to file\n" + "Make sure to select aid or authenticate aid before running this command.", + "hf mfdes write -n 01 -t 0 -o 000000 -d 3132333435363738" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("n", "fileno", "", "File Number (0 - 31)"), + arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian), optional"), + arg_strx0("d", "data", "", "Data to write (hex bytes, 256 bytes max)"), + arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), + arg_strx0("a", "aid", "", "App ID to select as hex bytes (3 bytes, big endian)"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, false); + int fno = arg_get_int_def(ctx, 1, 0); + + int offsetlength = 0; + uint8_t offset[3] = {0}; + int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); + + // iceman: we only have a 1024 byte commandline input array. So this is pointlessly large. + // with 2char hex, 512bytes could be input. + // Instead large binary inputs should be BINARY files and written to card. + int dlength = 512; + uint8_t data[512] = {0}; + int res_data = CLIParamHexToBuf(arg_get_str(ctx, 3), data, 512, &dlength); + + int type = arg_get_int(ctx, 4); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); + swap24(aid); + + CLIParserFree(ctx); + + swap24(offset); + + if (type < 0 || type > 1) { + PrintAndLogEx(ERR, "Unknown type (0=Standard/Backup, 1=Record)"); + return PM3_EINVARG; + } + + if (res_data || dlength == 0) { + PrintAndLogEx(ERR, "Data needs some hex bytes to write"); + return PM3_EINVARG; + } + + if (res_offset || (offsetlength != 3 && offsetlength != 0)) { + PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); + return PM3_EINVARG; + } + + if (fno > 0x1F) { + PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); + return PM3_EINVARG; + } + + mfdes_data_t ft; + + memcpy(ft.offset, offset, 3); + htole24(dlength, ft.length); + ft.fileno = fno; + + 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, fno, &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + DropFieldDesfire(); + return PM3_ESOFT; + } + + int res = PM3_ESOFT; + ft.data = data; + res = handler_desfire_writedata(&ft, type, cs); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "Successfully wrote data"); + } else { + PrintAndLogEx(ERR, "Couldn't read data. Error %d", res); + } + DropFieldDesfire(); + return res; +} + static int CmdHF14ADesTest(const char *Cmd) { DesfireTest(true); return PM3_SUCCESS; @@ -6486,7 +6486,7 @@ static command_t CommandTable[] = { {"getfilesettings", CmdHF14ADesGetFileSettings, IfPm3Iso14443a, "[new]Get file settings"}, {"chfilesettings", CmdHF14ADesChFileSettings, IfPm3Iso14443a, "[new]Change file settings"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, - {"read", CmdHF14ADesReadData, IfPm3Iso14443a, "Read data from standard/backup/record file"}, + {"read", CmdHF14ADesReadData, IfPm3Iso14443a, "[new]Read data from standard/backup/record file"}, {"write", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record file"}, {"value", CmdHF14ADesValueOperations, IfPm3Iso14443a, "[new]Operations with value file (get/credit/limited credit/debit/clear)"}, {"clearrecfile", CmdHF14ADesClearRecordFile, IfPm3Iso14443a, "[new]Clear record File"}, From be128741e3bc429d0ba843a43c007b33f8a6de50 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 16:08:20 +0300 Subject: [PATCH 02/37] add cli parser option --- client/src/mifare/desfirecore.c | 9 +++++++++ client/src/mifare/desfirecore.h | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index e21180957..379862226 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -103,6 +103,15 @@ const CLIParserOption DesfireValueFileOperOpts[] = { {0, NULL}, }; +const CLIParserOption DesfireReadFileTypeOpts[] = { + {RFTAuto, "auto"}, + {RFTData, "data"}, + {RFTValue, "value"}, + {RFTRecord, "record"}, + {RFTMAC, "mac"}, + {0, NULL}, +}; + static const char *getstatus(uint16_t *sw) { if (sw == NULL) return "--> sw argument error. This should never happen !"; if (((*sw >> 8) & 0xFF) == 0x91) { diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 14453993b..28dffccc8 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -28,6 +28,14 @@ typedef struct { const bool mayHaveISOfid; } DesfireCreateFileCommandsS; +typedef enum { + RFTAuto, + RFTData, + RFTValue, + RFTRecord, + RFTMAC, +} DesfireReadOpFileType; + extern const CLIParserOption DesfireAlgoOpts[]; extern const CLIParserOption DesfireKDFAlgoOpts[]; extern const CLIParserOption DesfireCommunicationModeOpts[]; @@ -35,6 +43,7 @@ extern const CLIParserOption DesfireCommandSetOpts[]; extern const CLIParserOption DesfireSecureChannelOpts[]; extern const CLIParserOption DesfireFileAccessModeOpts[]; extern const CLIParserOption DesfireValueFileOperOpts[]; +extern const CLIParserOption DesfireReadFileTypeOpts[]; const char *DesfireGetErrorString(int res, uint16_t *sw); uint32_t DesfireAIDByteToUint(uint8_t *data); From 618bdd4bc7d9512a0346e86974a100f6d3b8c178 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 16:54:03 +0300 Subject: [PATCH 03/37] read and write commands --- client/src/mifare/desfirecore.c | 19 +++++++++++++++++++ client/src/mifare/desfirecore.h | 3 +++ include/protocols.h | 2 ++ 3 files changed, 24 insertions(+) diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index 379862226..a506ad460 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -1096,6 +1096,25 @@ int DesfireAbortTransaction(DesfireContext *dctx) { return DesfireCommandNoData(dctx, MFDES_ABORT_TRANSACTION); } +int DesfireReadFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *resp, size_t *resplen) { + uint8_t data[10] = {0}; + data[0] = fnum; + Uint3byteToMemLe(&data[1], offset); + Uint3byteToMemLe(&data[4], len); + + return DesfireCommand(dctx, MFDES_READ_DATA, data, 7, resp, resplen, -1); +} + +int DesfireWriteFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *data) { + uint8_t xdata[1024] = {0}; + xdata[0] = fnum; + Uint3byteToMemLe(&xdata[1], offset); + Uint3byteToMemLe(&xdata[4], len); + memcpy(&xdata[7], data, len); + + return DesfireCommandTxData(dctx, MFDES_WRITE_DATA, xdata, 7 + len); +} + int DesfireValueFileOperations(DesfireContext *dctx, uint8_t fid, uint8_t operation, uint32_t *value) { uint8_t data[250] = {0}; data[0] = fid; diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 28dffccc8..8de744f5b 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -105,4 +105,7 @@ int DesfireAbortTransaction(DesfireContext *dctx); int DesfireValueFileOperations(DesfireContext *dctx, uint8_t fid, uint8_t operation, uint32_t *value); int DesfireClearRecordFile(DesfireContext *dctx, uint8_t fnum); +int DesfireReadFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *resp, size_t *resplen); +int DesfireWriteFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *data); + #endif // __DESFIRECORE_H diff --git a/include/protocols.h b/include/protocols.h index efa3e0a78..57c9dd86f 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -435,7 +435,9 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_GET_FREE_MEMORY 0x6E #define MFDES_GET_DF_NAMES 0x6D #define MFDES_GET_FILE_IDS 0x6F +#define MFDES_WRITE_DATA2 0x8D #define MFDES_ABORT_TRANSACTION 0xA7 +#define MFDES_READ_DATA2 0xAD #define MFDES_ADDITIONAL_FRAME 0xAF #define MFDES_UPDATE_RECORD1 0xBA #define MFDES_READ_RECORDS 0xBB From 8f9e3977d4546a715ec085350d3fc3efbb087c4d Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 16:54:28 +0300 Subject: [PATCH 04/37] read interface. read value works --- client/src/cmdhfmfdes.c | 152 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index f7452beda..1504f890f 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6231,6 +6231,156 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { } static int CmdHF14ADesReadData(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes read", + "Read data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", + "hf mfdes read --aid 123456 --fid 01 -> read file: app=123456, file=01, offset=0, all the data. use default channel settings from `default` command"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("a", "apdu", "show APDU requests and responses"), + arg_lit0("v", "verbose", "show technical data"), + arg_int0("n", "keyno", "", "Key number"), + arg_str0("t", "algo", "", "Crypt algo: DES, 2TDEA, 3TDEA, AES"), + arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("f", "kdf", "", "Key Derivation Function (KDF): None, AN10922, Gallagher"), + arg_str0("i", "kdfi", "", "KDF input (HEX 1-31 bytes)"), + arg_str0("m", "cmode", "", "Communicaton mode: plain/mac/encrypt"), + arg_str0("c", "ccset", "", "Communicaton command set: native/niso/iso"), + arg_str0("s", "schann", "", "Secure channel: d40/ev1/ev2"), + arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), + arg_str0(NULL, "fid", "", "File ID for clearing (1 hex byte)"), + arg_lit0(NULL, "no-auth", "execute without authentication"), + arg_str0("t", "type", "", "File Type auto/data(Standard/Backup)/value/record(linear/cyclic)/mac). Auto - check file settings and then read. Default: auto"), + arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). Default 0"), + arg_str0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data). Default 0."), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + bool APDULogging = arg_get_lit(ctx, 1); + bool verbose = arg_get_lit(ctx, 2); + bool noauth = arg_get_lit(ctx, 13); + + DesfireContext dctx; + int securechann = defaultSecureChannel; + uint32_t appid = 0x000000; + int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid); + if (res) { + CLIParserFree(ctx); + return res; + } + + uint32_t fnum = 1; + res = arg_get_u32_hexstr_def_nlen(ctx, 12, 1, &fnum, 1, true); + if (res == 2) { + PrintAndLogEx(ERR, "File ID must have 1 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + int op = RFTAuto; + if (CLIGetOptionList(arg_get_str(ctx, 14), DesfireReadFileTypeOpts, &op)) { + CLIParserFree(ctx); + return PM3_ESOFT; + } + + uint32_t offset = 0; + res = arg_get_u32_hexstr_def_nlen(ctx, 15, 0, &offset, 3, true); + if (res == 2) { + PrintAndLogEx(ERR, "Offset must have 3 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + uint32_t length = 0; + res = arg_get_u32_hexstr_def_nlen(ctx, 16, 0, &length, 3, true); + if (res == 2) { + PrintAndLogEx(ERR, "Length must have 3 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + SetAPDULogging(APDULogging); + CLIParserFree(ctx); + + if (fnum > 0x1F) { + PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fnum); + return PM3_EINVARG; + } + + if (noauth) { + res = DesfireSelectAIDHex(&dctx, appid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire select " _RED_("error") "."); + DropField(); + return res; + } + } else { + res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose); + if (res != PM3_SUCCESS) { + DropField(); + return res; + } + } + + // get file settings + if (op == RFTAuto) { + + } + + PrintAndLogEx(INFO, "-------------- " _CYAN_("File data") " --------------"); + + uint8_t resp[2048] = {0}; + size_t resplen = 0; + + if (op == RFTData) { + res = DesfireReadFile(&dctx, fnum, offset, length, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadFile command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + if (resplen > 0) { + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x", resplen, fnum); + PrintAndLogEx(INFO, "Offset | Data | Ascii"); + PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); + + for (uint32_t i = 0; i < resplen; i += 16) { + uint32_t l = resplen - i; + PrintAndLogEx(INFO, "%3d/0x%02X | %s| %s", i, i, sprint_hex(&resp[i], l > 16 ? 16 : l), sprint_ascii(&resp[i], l > 16 ? 16 : l)); + } + } else { + PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); + } + } + + if (op == RFTValue) { + uint32_t value = 0; + res = DesfireValueFileOperations(&dctx, fnum, MFDES_GET_VALUE, &value); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire GetValue operation " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + PrintAndLogEx(SUCCESS, "Read file 0x%02x value: %d (0x%08x)", fnum, value, value); + } + + if (op == RFTRecord) { + + } + + if (op == RFTMAC) { + + } + + DropField(); + return PM3_SUCCESS; + + + + /* CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes read", "Read data from File\n" @@ -6342,7 +6492,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { free(data); } DropFieldDesfire(); - return res; + return res; */ } static int CmdHF14ADesWriteData(const char *Cmd) { From 9a822ea0879aa4ddcfe8882802d921bcf0145019 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 17:50:22 +0300 Subject: [PATCH 05/37] add offset print buffer to util --- client/src/util.c | 14 ++++++++++++++ client/src/util.h | 1 + 2 files changed, 15 insertions(+) diff --git a/client/src/util.c b/client/src/util.c index ed6ca6e7c..829af8d7a 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -249,6 +249,20 @@ void print_buffer(const uint8_t *data, const size_t len, int level) { print_buffer_ex(data, len, level, 16); } +void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset) { + PrintAndLogEx(INFO, " Offset | Data | Ascii"); + PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); + + for (uint32_t i = 0; i < len; i += 16) { + uint32_t l = len - i; + PrintAndLogEx(INFO, "%3d/0x%02X | %s" NOLF, offset + i, offset + i, sprint_hex(&data[i], l > 16 ? 16 : l)); + if (l < 16) + PrintAndLogEx(NORMAL, "%*s" NOLF, 3 * (16 - l), " "); + PrintAndLogEx(NORMAL, "| %s", sprint_ascii(&data[i], l > 16 ? 16 : l)); + } +} + + void print_blocks(uint32_t *data, size_t len) { PrintAndLogEx(SUCCESS, "Blk | Data "); PrintAndLogEx(SUCCESS, "----+------------"); diff --git a/client/src/util.h b/client/src/util.h index 9357eb1d0..14795773a 100644 --- a/client/src/util.h +++ b/client/src/util.h @@ -52,6 +52,7 @@ char *sprint_hex_ascii(const uint8_t *data, const size_t len); char *sprint_ascii(const uint8_t *data, const size_t len); char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_str_len); +void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset); void print_buffer(const uint8_t *data, const size_t len, int level); void print_blocks(uint32_t *data, size_t len); From 7d8009a32b488fb73e12de9563fc67e651a883f3 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 17:51:27 +0300 Subject: [PATCH 06/37] move print buffer to util --- client/src/cmdhfmfdes.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 1504f890f..dca5dd81d 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6343,14 +6343,8 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (resplen > 0) { - PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x", resplen, fnum); - PrintAndLogEx(INFO, "Offset | Data | Ascii"); - PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); - - for (uint32_t i = 0; i < resplen; i += 16) { - uint32_t l = resplen - i; - PrintAndLogEx(INFO, "%3d/0x%02X | %s| %s", i, i, sprint_hex(&resp[i], l > 16 ? 16 : l), sprint_ascii(&resp[i], l > 16 ? 16 : l)); - } + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x offset %u", resplen, fnum, offset); + print_buffer_with_offset(resp, resplen, offset); } else { PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); } From 4c743d4772b382e2a2fd701cc1f067d0262d2f6a Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 17:57:39 +0300 Subject: [PATCH 07/37] skip mode warnings for read/write data --- client/src/mifare/desfiresecurechan.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 85df23503..ee5d77153 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -23,7 +23,19 @@ #include "protocols.h" #include "mifare/desfire_crypto.h" -AllowedChannelModesS AllowedChannelModes[] = { +static const AllowedChannelModesS AllowedChannelModes[] = { + // read and write data can go in any mode + {MFDES_READ_DATA, DACd40, DCCNative, DCMPlain}, + {MFDES_READ_DATA, DACd40, DCCNative, DCMMACed}, + {MFDES_READ_DATA, DACd40, DCCNative, DCMEncrypted}, + {MFDES_READ_DATA, DACEV1, DCCNative, DCMMACed}, + {MFDES_READ_DATA, DACEV1, DCCNative, DCMEncrypted}, + {MFDES_WRITE_DATA, DACd40, DCCNative, DCMPlain}, + {MFDES_WRITE_DATA, DACd40, DCCNative, DCMMACed}, + {MFDES_WRITE_DATA, DACd40, DCCNative, DCMEncrypted}, + {MFDES_WRITE_DATA, DACEV1, DCCNative, DCMMACed}, + {MFDES_WRITE_DATA, DACEV1, DCCNative, DCMEncrypted}, + {MFDES_CREATE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_DELETE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_GET_APPLICATION_IDS, DACd40, DCCNative, DCMPlain}, @@ -43,8 +55,6 @@ AllowedChannelModesS AllowedChannelModes[] = { {MFDES_COMMIT_TRANSACTION, DACd40, DCCNative, DCMPlain}, {MFDES_CLEAR_RECORD_FILE, DACd40, DCCNative, DCMPlain}, - {MFDES_READ_DATA, DACd40, DCCNative, DCMMACed}, - {MFDES_WRITE_DATA, DACd40, DCCNative, DCMMACed}, {MFDES_GET_VALUE, DACd40, DCCNative, DCMMACed}, {MFDES_CREDIT, DACd40, DCCNative, DCMMACed}, {MFDES_DEBIT, DACd40, DCCNative, DCMMACed}, @@ -64,8 +74,6 @@ AllowedChannelModesS AllowedChannelModes[] = { {MFDES_GET_UID, DACd40, DCCNative, DCMEncrypted}, {MFDES_CHANGE_KEY_SETTINGS, DACd40, DCCNative, DCMEncrypted}, {MFDES_CHANGE_FILE_SETTINGS, DACd40, DCCNative, DCMEncrypted}, - {MFDES_READ_DATA, DACd40, DCCNative, DCMEncrypted}, - {MFDES_WRITE_DATA, DACd40, DCCNative, DCMEncrypted}, {MFDES_CHANGE_KEY, DACd40, DCCNative, DCMEncryptedPlain}, {MFDES_CHANGE_KEY_EV2, DACd40, DCCNative, DCMEncryptedPlain}, @@ -104,7 +112,7 @@ AllowedChannelModesS AllowedChannelModes[] = { }; #define CMD_HEADER_LEN_ALL 0xffff -CmdHeaderLengthsS CmdHeaderLengths[] = { +static const CmdHeaderLengthsS CmdHeaderLengths[] = { {MFDES_CREATE_APPLICATION, CMD_HEADER_LEN_ALL}, {MFDES_DELETE_APPLICATION, CMD_HEADER_LEN_ALL}, {MFDES_CHANGE_KEY, 1}, From 0b6546012a446abe7d3c5d8c2319097800f8f3af Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 18:28:41 +0300 Subject: [PATCH 08/37] fix crc search with padding --- client/src/mifare/desfirecrypto.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/src/mifare/desfirecrypto.c b/client/src/mifare/desfirecrypto.c index 79604f5eb..e1015c2d8 100644 --- a/client/src/mifare/desfirecrypto.c +++ b/client/src/mifare/desfirecrypto.c @@ -124,7 +124,8 @@ size_t DesfireSearchCRCPos(uint8_t *data, size_t datalen, uint8_t respcode, uint uint8_t crcdata[1024] = {0}; size_t crcposfound = 0; - for (int i = 0; i < crclen + 1; i++) { + // crc may be 00..00 and at the end of file may be padding 0x80. so we search from last zero to crclen + 2 (one for crc=0 and one for padding 0x80) + for (int i = 0; i < crclen + 2; i++) { if (crcpos - i == 0) break; if (crcpos - i + crclen > datalen) From 9bcb30256eb6e7a740a9db6e403d0575032bebcc Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 18:29:34 +0300 Subject: [PATCH 09/37] fix communication modes. header length not counts as data --- client/src/mifare/desfiresecurechan.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index ee5d77153..691a7f964 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -120,6 +120,8 @@ static const CmdHeaderLengthsS CmdHeaderLengths[] = { {MFDES_CHANGE_CONFIGURATION, 1}, {MFDES_CHANGE_FILE_SETTINGS, 1}, {MFDES_CREATE_TRANS_MAC_FILE, 5}, + {MFDES_READ_DATA, 7}, + {MFDES_WRITE_DATA, 7}, }; static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) { @@ -190,7 +192,7 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint // we calc MAC anyway // if encypted channel and no data - we only calc MAC - if (ctx->commMode == DCMPlain || ctx->commMode == DCMMACed || (ctx->commMode == DCMEncrypted && srcdatalen == 0)) { + if (ctx->commMode == DCMPlain || ctx->commMode == DCMMACed || (ctx->commMode == DCMEncrypted && srcdatalen <= hdrlen)) { data[0] = cmd; memcpy(&data[1], srcdata, srcdatalen); uint8_t cmac[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; @@ -198,7 +200,7 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint memcpy(dstdata, srcdata, srcdatalen); *dstdatalen = srcdatalen; - if (srcdatalen != 0 && ctx->commMode == DCMMACed) { + if (srcdatalen > hdrlen && ctx->commMode == DCMMACed) { memcpy(&dstdata[srcdatalen], cmac, DesfireGetMACLength(ctx)); *dstdatalen = srcdatalen + DesfireGetMACLength(ctx); } @@ -227,7 +229,7 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint void DesfireSecureChannelEncode(DesfireContext *ctx, uint8_t cmd, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, size_t *dstdatalen) { ctx->lastCommand = cmd; - ctx->lastRequestZeroLen = (srcdatalen == 0); + ctx->lastRequestZeroLen = (srcdatalen <= DesfireGetCmdHeaderLen(cmd)); switch (ctx->secureChannel) { case DACd40: From dbe85e731fe2b9fcda1c89eee6f452d2afe8f281 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:13:15 +0300 Subject: [PATCH 10/37] add record manipulation commands --- client/src/mifare/desfirecore.c | 31 ++++++++++++++++++++++++++- client/src/mifare/desfirecore.h | 3 +++ client/src/mifare/desfiresecurechan.c | 5 ++++- include/protocols.h | 6 ++++-- 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index a506ad460..a76921a6a 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -1116,7 +1116,7 @@ int DesfireWriteFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32 } int DesfireValueFileOperations(DesfireContext *dctx, uint8_t fid, uint8_t operation, uint32_t *value) { - uint8_t data[250] = {0}; + uint8_t data[10] = {0}; data[0] = fid; size_t datalen = (operation == MFDES_GET_VALUE) ? 1 : 5; if (value) @@ -1132,6 +1132,35 @@ int DesfireValueFileOperations(DesfireContext *dctx, uint8_t fid, uint8_t operat return res; } +int DesfireReadRecords(DesfireContext *dctx, uint8_t fnum, uint32_t recnum, uint32_t reccount, uint8_t *resp, size_t *resplen) { + uint8_t data[10] = {0}; + data[0] = fnum; + Uint3byteToMemLe(&data[1], recnum); + Uint3byteToMemLe(&data[4], reccount); + + return DesfireCommand(dctx, MFDES_READ_RECORDS, data, 7, resp, resplen, -1); +} + +int DesfireWriteRecord(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *data) { + uint8_t xdata[1024] = {0}; + xdata[0] = fnum; + Uint3byteToMemLe(&xdata[1], offset); + Uint3byteToMemLe(&xdata[4], len); + memcpy(&xdata[7], data, len); + + return DesfireCommandTxData(dctx, MFDES_WRITE_RECORD, xdata, 7 + len); +} + +int DesfireUpdateRecord(DesfireContext *dctx, uint8_t fnum, uint32_t recnum, uint32_t offset, uint32_t len, uint8_t *data) { + uint8_t xdata[1024] = {0}; + xdata[0] = fnum; + Uint3byteToMemLe(&xdata[1], recnum); + Uint3byteToMemLe(&xdata[4], offset); + Uint3byteToMemLe(&xdata[7], len); + memcpy(&xdata[10], data, len); + + return DesfireCommandTxData(dctx, MFDES_UPDATE_RECORD, xdata, 10 + len); +} uint8_t DesfireKeyAlgoToType(DesfireCryptoAlgorythm keyType) { switch (keyType) { diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 8de744f5b..55abfe5e8 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -107,5 +107,8 @@ int DesfireClearRecordFile(DesfireContext *dctx, uint8_t fnum); int DesfireReadFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *resp, size_t *resplen); int DesfireWriteFile(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *data); +int DesfireReadRecords(DesfireContext *dctx, uint8_t fnum, uint32_t recnum, uint32_t reccount, uint8_t *resp, size_t *resplen); +int DesfireWriteRecord(DesfireContext *dctx, uint8_t fnum, uint32_t offset, uint32_t len, uint8_t *data); +int DesfireUpdateRecord(DesfireContext *dctx, uint8_t fnum, uint32_t recnum, uint32_t offset, uint32_t len, uint8_t *data); #endif // __DESFIRECORE_H diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 691a7f964..2794e3197 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -61,7 +61,7 @@ static const AllowedChannelModesS AllowedChannelModes[] = { {MFDES_LIMITED_CREDIT, DACd40, DCCNative, DCMMACed}, {MFDES_READ_RECORDS, DACd40, DCCNative, DCMMACed}, {MFDES_WRITE_RECORD, DACd40, DCCNative, DCMMACed}, - {MFDES_UPDATE_RECORD1, DACd40, DCCNative, DCMMACed}, + {MFDES_UPDATE_RECORD, DACd40, DCCNative, DCMMACed}, {MFDES_UPDATE_RECORD2, DACd40, DCCNativeISO, DCMMACed}, {MFDES_INIT_KEY_SETTINGS, DACd40, DCCNative, DCMMACed}, {MFDES_FINALIZE_KEY_SETTINGS, DACd40, DCCNative, DCMMACed}, @@ -122,6 +122,9 @@ static const CmdHeaderLengthsS CmdHeaderLengths[] = { {MFDES_CREATE_TRANS_MAC_FILE, 5}, {MFDES_READ_DATA, 7}, {MFDES_WRITE_DATA, 7}, + {MFDES_READ_RECORDS, 7}, + {MFDES_WRITE_RECORD, 7}, + {MFDES_UPDATE_RECORD, 10}, }; static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) { diff --git a/include/protocols.h b/include/protocols.h index 57c9dd86f..168606498 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -435,11 +435,13 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_GET_FREE_MEMORY 0x6E #define MFDES_GET_DF_NAMES 0x6D #define MFDES_GET_FILE_IDS 0x6F +#define MFDES_WRITE_RECORD2 0x8B #define MFDES_WRITE_DATA2 0x8D #define MFDES_ABORT_TRANSACTION 0xA7 +#define MFDES_READ_RECORDS2 0xAB #define MFDES_READ_DATA2 0xAD #define MFDES_ADDITIONAL_FRAME 0xAF -#define MFDES_UPDATE_RECORD1 0xBA +#define MFDES_UPDATE_RECORD2 0xBA #define MFDES_READ_RECORDS 0xBB #define MFDES_READ_DATA 0xBD #define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 @@ -455,7 +457,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_CREATE_STD_DATA_FILE 0xCD #define MFDES_CREATE_TRANS_MAC_FILE 0xCE #define MFDES_DELETE_APPLICATION 0xDA -#define MFDES_UPDATE_RECORD2 0xDB +#define MFDES_UPDATE_RECORD 0xDB #define MFDES_DEBIT 0xDC #define MFDES_DELETE_FILE 0xDF #define MFDES_CLEAR_RECORD_FILE 0xEB From 2ac2e7dcf9cc39702ce8dafbcf2719a56208484f Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:13:51 +0300 Subject: [PATCH 11/37] add records and mac to command --- client/src/cmdhfmfdes.c | 44 ++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index dca5dd81d..6282f862f 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6073,7 +6073,7 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { } else { res = DesfireCommitTransaction(&dctx, false, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire CommitTrqansaction command " _RED_("error") ". Result: %d", res); + PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); DropField(); return PM3_ESOFT; } @@ -6129,7 +6129,7 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { res = DesfireCommitTransaction(&dctx, false, 0); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire CommitTrqansaction command " _RED_("error") ". Result: %d", res); + PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); DropField(); return PM3_ESOFT; } @@ -6251,9 +6251,9 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), arg_str0(NULL, "fid", "", "File ID for clearing (1 hex byte)"), arg_lit0(NULL, "no-auth", "execute without authentication"), - arg_str0("t", "type", "", "File Type auto/data(Standard/Backup)/value/record(linear/cyclic)/mac). Auto - check file settings and then read. Default: auto"), - arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). Default 0"), - arg_str0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data). Default 0."), + arg_str0(NULL, "type", "", "File Type auto/data(Standard/Backup)/value/record(linear/cyclic)/mac). Auto - check file settings and then read. Default: auto"), + arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). For records - record number (0 - lastest record). Default 0"), + arg_str0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data). For records - records count (0 - all). Default 0."), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -6362,11 +6362,41 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (op == RFTRecord) { - + res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + if (resplen > 0) { + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x offset %u", resplen, fnum, offset); + print_buffer_with_offset(resp, resplen, offset); + } else { + PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); + } } if (op == RFTMAC) { - + res = DesfireReadFile(&dctx, fnum, 0, 0, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadFile command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + if (resplen > 0) { + if (resplen != 12) { + PrintAndLogEx(WARNING, "Read wrong %u bytes from file 0x%02x offset %u", resplen, fnum, offset); + print_buffer_with_offset(resp, resplen, offset); + } else { + uint32_t cnt = MemLeToUint4byte(&resp[0]); + PrintAndLogEx(SUCCESS, "Transaction counter: %d (0x%08x)", cnt, cnt); + PrintAndLogEx(SUCCESS, "Transaction MAC : %s", sprint_hex(&resp[4], 8)); + } + } else { + PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); + } } DropField(); From edb09c4d0164eca414b672c00437cd6ba17e763e Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:17:03 +0300 Subject: [PATCH 12/37] cov 353974 --- client/src/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 6282f862f..9e5abb727 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -5325,7 +5325,7 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) { // print the new file settings if (verbose) - PrintAndLogEx(INFO, "app %06x file %02x settings[%d]: %s", appid, fileid, datalen - 1, sprint_hex(settings, datalen - 1)); + PrintAndLogEx(INFO, "app %06x file %02x settings[%zu]: %s", appid, fileid, datalen - 1, sprint_hex(settings, datalen - 1)); DesfirePrintSetFileSettings(settings, datalen - 1); From 6481142b4112fecee12f399ebf3156ad43969425 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:17:52 +0300 Subject: [PATCH 13/37] cov 353927 --- client/src/cmdhfmfdes.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 9e5abb727..93fa4f98a 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -3931,6 +3931,7 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { CLIGetHexWithReturn(ctx, 16, keydata, &keylen); if (keylen && keylen != desfire_get_key_length(newkeytype)) { PrintAndLogEx(ERR, "%s new key must have %d bytes length instead of %d.", CLIGetOptionListStr(DesfireAlgoOpts, newkeytype), desfire_get_key_length(newkeytype), keylen); + CLIParserFree(ctx); return PM3_EINVARG; } if (keylen) From 882e96a3ce67507b77cdcf437942db698aa0b2d2 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 19:20:30 +0300 Subject: [PATCH 14/37] remove old --- client/src/cmdhfmfdes.c | 116 ---------------------------------------- 1 file changed, 116 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 93fa4f98a..4e72da5b8 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6402,122 +6402,6 @@ static int CmdHF14ADesReadData(const char *Cmd) { DropField(); return PM3_SUCCESS; - - - - /* - CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfdes read", - "Read data from File\n" - "Make sure to select aid or authenticate aid before running this command.", - "hf mfdes read -n 1 -t 0 -o 000000 -l 000000 -a 123456\n" - "hf mfdes read -n 1 -t 0 --> Read all data from standard file, fileno 1" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("n", "fileno", "", "File Number (0 - 31)"), - arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian)"), - arg_strx0("l", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data)"), - arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), - arg_strx0("a", "aid", "", "App ID to select (3 hex bytes, big endian)"), - arg_param_end - }; - - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fno = arg_get_int_def(ctx, 1, 0); - - int offsetlength = 0; - uint8_t offset[3] = {0}; - int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); - - int flength = 0; - uint8_t filesize[3] = {0}; - int res_flen = CLIParamHexToBuf(arg_get_str(ctx, 3), filesize, 3, &flength); - - int type = arg_get_int(ctx, 4); - - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 5, aid, &aidlength); - swap24(aid); - CLIParserFree(ctx); - - if (type > 1) { - PrintAndLogEx(ERR, "Invalid file type (0 = Standard/Backup, 1 = Record)"); - return PM3_EINVARG; - } - - if (res_offset || (offsetlength != 3 && offsetlength != 0)) { - PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); - return PM3_EINVARG; - } - - if (fno > 0x1F) { - PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); - return PM3_EINVARG; - } - - if (res_flen) { - PrintAndLogEx(ERR, "File size input error"); - return PM3_EINVARG; - } - - swap24(filesize); - swap24(offset); - - mfdes_data_t ft; - memcpy(ft.offset, offset, 3); - memcpy(ft.length, filesize, 3); - ft.fileno = fno; - - uint32_t bytestoread = (uint32_t)le24toh(filesize); - bytestoread &= 0xFFFFFF; - - 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, cs); - if (res == PM3_SUCCESS) { - uint32_t len = le24toh(ft.length); - - PrintAndLogEx(SUCCESS, "Read %u bytes from file %d", ft.fileno, len); - PrintAndLogEx(INFO, "Offset | Data | Ascii"); - PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); - - for (uint32_t i = 0; i < len; i += 16) { - uint32_t l = len - i; - PrintAndLogEx(INFO, "%3d/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); - DropFieldDesfire(); - return res; - } - free(data); - } - DropFieldDesfire(); - return res; */ } static int CmdHF14ADesWriteData(const char *Cmd) { From 5a7e507de2c7528a1b1c793a58ddb411ebed965a Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 20:00:18 +0300 Subject: [PATCH 15/37] advanced record reading --- client/src/cmdhfmfdes.c | 26 ++++++++++++++++++++++---- client/src/util.c | 8 +++++--- client/src/util.h | 2 +- 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 4e72da5b8..2dff491ee 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6345,7 +6345,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (resplen > 0) { PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x offset %u", resplen, fnum, offset); - print_buffer_with_offset(resp, resplen, offset); + print_buffer_with_offset(resp, resplen, offset, true); } else { PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); } @@ -6363,6 +6363,17 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (op == RFTRecord) { + res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords (len=1) command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + size_t reclen = resplen; + if (verbose) + PrintAndLogEx(INFO, "Record length %zu", reclen); + res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); @@ -6371,8 +6382,15 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (resplen > 0) { - PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x offset %u", resplen, fnum, offset); - print_buffer_with_offset(resp, resplen, offset); + size_t reccount = resplen / reclen; + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %u record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); + if (reccount > 0) + PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); + for (int i = 0; i < reccount; i++) { + if (i != 0) + PrintAndLogEx(SUCCESS, "Record %d", i + offset); + print_buffer_with_offset(&resp[i * reclen], reclen, offset, (i == 0)); + } } else { PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); } @@ -6389,7 +6407,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (resplen > 0) { if (resplen != 12) { PrintAndLogEx(WARNING, "Read wrong %u bytes from file 0x%02x offset %u", resplen, fnum, offset); - print_buffer_with_offset(resp, resplen, offset); + print_buffer_with_offset(resp, resplen, offset, true); } else { uint32_t cnt = MemLeToUint4byte(&resp[0]); PrintAndLogEx(SUCCESS, "Transaction counter: %d (0x%08x)", cnt, cnt); diff --git a/client/src/util.c b/client/src/util.c index 829af8d7a..7d2772794 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -249,9 +249,11 @@ void print_buffer(const uint8_t *data, const size_t len, int level) { print_buffer_ex(data, len, level, 16); } -void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset) { - PrintAndLogEx(INFO, " Offset | Data | Ascii"); - PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); +void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset, bool print_header) { + if (print_header) { + PrintAndLogEx(INFO, " Offset | Data | Ascii"); + PrintAndLogEx(INFO, "----------------------------------------------------------------------------"); + } for (uint32_t i = 0; i < len; i += 16) { uint32_t l = len - i; diff --git a/client/src/util.h b/client/src/util.h index 14795773a..67ce0faa8 100644 --- a/client/src/util.h +++ b/client/src/util.h @@ -52,7 +52,7 @@ char *sprint_hex_ascii(const uint8_t *data, const size_t len); char *sprint_ascii(const uint8_t *data, const size_t len); char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_str_len); -void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset); +void print_buffer_with_offset(const uint8_t *data, const size_t len, int offset, bool print_header); void print_buffer(const uint8_t *data, const size_t len, int level); void print_blocks(uint32_t *data, size_t len); From 8910fbac6f9278b5858730485367db9772cdc781 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 21:24:51 +0300 Subject: [PATCH 16/37] autodetect file type --- client/src/cmdhfmfdes.c | 51 +++++++++++++++++++---- client/src/mifare/desfirecore.c | 71 ++++++++++++++++++++++++++++++++- client/src/mifare/desfirecore.h | 39 ++++++++++++++++++ 3 files changed, 153 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 2dff491ee..9ceb02310 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6325,9 +6325,44 @@ static int CmdHF14ADesReadData(const char *Cmd) { } } + // length of record for record file + size_t reclen = 0; + // get file settings if (op == RFTAuto) { - + FileSettingsS fsettings; + res = DesfireGetFileSettingsStruct(&dctx, fnum, &fsettings); + if (res == PM3_SUCCESS) { + switch(fsettings.fileType) { + case 0x00: + case 0x01: { + op = RFTData; + break; + } + case 0x02: { + op = RFTValue; + break; + } + case 0x03: + case 0x04: { + op = RFTRecord; + reclen = fsettings.recordSize; + break; + } + case 0x05: { + op = RFTMAC; + break; + } + default: { + break; + } + } + if (verbose) + PrintAndLogEx(INFO, "Got file type: %s. Option: %s", GetDesfireFileType(fsettings.fileType), CLIGetOptionListStr(DesfireReadFileTypeOpts, op)); + + } else { + PrintAndLogEx(WARNING, "GetFileSettings error. Can't get file type."); + } } PrintAndLogEx(INFO, "-------------- " _CYAN_("File data") " --------------"); @@ -6363,14 +6398,16 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (op == RFTRecord) { - res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire ReadRecords (len=1) command " _RED_("error") ". Result: %d", res); - DropField(); - return PM3_ESOFT; + if (reclen == 0) { + res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords (len=1) command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + reclen = resplen; } - size_t reclen = resplen; if (verbose) PrintAndLogEx(INFO, "Record length %zu", reclen); diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index a76921a6a..a0b893e4c 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -1067,6 +1067,16 @@ int DesfireGetFileSettings(DesfireContext *dctx, uint8_t fileid, uint8_t *resp, return DesfireCommand(dctx, MFDES_GET_FILE_SETTINGS, &fileid, 1, resp, resplen, -1); } +int DesfireGetFileSettingsStruct(DesfireContext *dctx, uint8_t fileid, FileSettingsS *fsettings) { + uint8_t resp[250] = {0}; + size_t resplen = 0; + int res = DesfireGetFileSettings(dctx, fileid, resp, &resplen); + if (res == PM3_SUCCESS && resplen > 0 && fsettings != NULL) + DesfireFillFileSettings(resp, resplen, fsettings); + + return res; +} + int DesfireCreateFile(DesfireContext *dctx, uint8_t ftype, uint8_t *fdata, size_t fdatalen, bool checklen) { const DesfireCreateFileCommandsS *rcmd = GetDesfireFileCmdRec(ftype); if (rcmd == NULL) @@ -1355,6 +1365,66 @@ void DesfirePrintAccessRight(uint8_t *data) { PrintAndLogEx(SUCCESS, "change : %s", GetDesfireAccessRightStr(ch)); } +void DesfireFillFileSettings(uint8_t *data, size_t datalen, FileSettingsS *fsettings) { + if (fsettings == NULL) + return; + + memset(fsettings, 0, sizeof(FileSettingsS)); + + if (datalen < 4) + return; + + fsettings->fileType = data[0]; + fsettings->fileOption = data[1]; + fsettings->fileCommMode = data[1] & 0x03; + fsettings->additionalAccessRightsEn = ((data[1] & 0x80) != 0); + fsettings->rawAccessRights = MemLeToUint2byte(&data[2]); + DesfireDecodeFileAcessMode(&data[2], &fsettings->rAccess, &fsettings->wAccess, &fsettings->rwAccess, &fsettings->chAccess); + + int reclen = 0; + switch (fsettings->fileType) { + case 0x00: + case 0x01: { + fsettings->fileSize = MemLeToUint3byte(&data[0]); + reclen = 4 + 3; + break; + } + case 0x02: { + fsettings->lowerLimit = MemLeToUint4byte(&data[0]); + fsettings->upperLimit = MemLeToUint4byte(&data[4]); + fsettings->value = MemLeToUint4byte(&data[8]); + fsettings->limitedCredit = data[12]; + reclen = 4 + 13; + break; + } + case 0x03: + case 0x04: { + fsettings->recordSize = MemLeToUint3byte(&data[0]); + fsettings->maxRecordCount = MemLeToUint3byte(&data[3]); + fsettings->curRecordCount = MemLeToUint3byte(&data[6]); + reclen = 4 + 9; + break; + } + case 0x05: { + fsettings->keyType = data[0]; + fsettings->keyVersion = data[1]; + break; + } + default: { + break; + } + } + + if (fsettings->additionalAccessRightsEn && reclen > 0 && datalen > reclen && datalen == reclen + data[reclen] * 2) { + fsettings->additionalAccessRightsLength = data[reclen]; + + for (int i = 0; i < fsettings->additionalAccessRightsLength; i++) { + fsettings->additionalAccessRights[i] = MemLeToUint2byte(&data[reclen + 1 + i * 2]); + } + } +} + + static void DesfirePrintFileSettDynPart(uint8_t filetype, uint8_t *data, size_t datalen, uint8_t *dynlen, bool create) { switch (filetype) { case 0x00: @@ -1507,7 +1577,6 @@ void DesfirePrintCreateFileSettings(uint8_t filetype, uint8_t *data, size_t len) xlen += reclen; } - int DesfireChangeKey(DesfireContext *dctx, bool change_master_key, uint8_t newkeynum, DesfireCryptoAlgorythm newkeytype, uint32_t newkeyver, uint8_t *newkey, DesfireCryptoAlgorythm oldkeytype, uint8_t *oldkey, bool verbose) { uint8_t okeybuf[DESFIRE_MAX_KEY_SIZE] = {0}; diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 55abfe5e8..8ff954807 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -28,6 +28,43 @@ typedef struct { const bool mayHaveISOfid; } DesfireCreateFileCommandsS; +typedef struct { + // all + uint8_t fileType; + uint8_t fileOption; + uint8_t fileCommMode; + bool additionalAccessRightsEn; + uint16_t rawAccessRights; + uint8_t rAccess; + uint8_t wAccess; + uint8_t rwAccess; + uint8_t chAccess; + + // data + uint32_t fileSize; + + //value + uint32_t lowerLimit; + uint32_t upperLimit; + uint32_t value; + uint8_t limitedCredit; + + // record + uint32_t recordSize; + uint32_t maxRecordCount; + uint32_t curRecordCount; + + //mac + uint8_t keyType; + uint8_t key[16]; + uint8_t keyVersion; + + // additional rights + uint8_t additionalAccessRightsLength; + uint16_t additionalAccessRights[16]; + +} FileSettingsS; + typedef enum { RFTAuto, RFTData, @@ -84,7 +121,9 @@ int DesfireSetConfiguration(DesfireContext *dctx, uint8_t paramid, uint8_t *para int DesfireGetFileIDList(DesfireContext *dctx, uint8_t *resp, size_t *resplen); int DesfireGetFileISOIDList(DesfireContext *dctx, uint8_t *resp, size_t *resplen); +void DesfireFillFileSettings(uint8_t *data, size_t datalen, FileSettingsS *fsettings); int DesfireGetFileSettings(DesfireContext *dctx, uint8_t fileid, uint8_t *resp, size_t *resplen); +int DesfireGetFileSettingsStruct(DesfireContext *dctx, uint8_t fileid, FileSettingsS *fsettings); int DesfireChangeFileSettings(DesfireContext *dctx, uint8_t *data, size_t datalen); const DesfireCreateFileCommandsS *GetDesfireFileCmdRec(uint8_t type); From 1cabef31489935dbf2db1a63121a1c15eae2d13a Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Tue, 27 Jul 2021 21:27:58 +0300 Subject: [PATCH 17/37] settings decode fix --- client/src/mifare/desfirecore.c | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index a0b893e4c..667fa7696 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -1385,29 +1385,29 @@ void DesfireFillFileSettings(uint8_t *data, size_t datalen, FileSettingsS *fsett switch (fsettings->fileType) { case 0x00: case 0x01: { - fsettings->fileSize = MemLeToUint3byte(&data[0]); + fsettings->fileSize = MemLeToUint3byte(&data[4]); reclen = 4 + 3; break; } case 0x02: { - fsettings->lowerLimit = MemLeToUint4byte(&data[0]); - fsettings->upperLimit = MemLeToUint4byte(&data[4]); - fsettings->value = MemLeToUint4byte(&data[8]); - fsettings->limitedCredit = data[12]; + fsettings->lowerLimit = MemLeToUint4byte(&data[4]); + fsettings->upperLimit = MemLeToUint4byte(&data[8]); + fsettings->value = MemLeToUint4byte(&data[12]); + fsettings->limitedCredit = data[16]; reclen = 4 + 13; break; } case 0x03: case 0x04: { - fsettings->recordSize = MemLeToUint3byte(&data[0]); - fsettings->maxRecordCount = MemLeToUint3byte(&data[3]); - fsettings->curRecordCount = MemLeToUint3byte(&data[6]); + fsettings->recordSize = MemLeToUint3byte(&data[4]); + fsettings->maxRecordCount = MemLeToUint3byte(&data[7]); + fsettings->curRecordCount = MemLeToUint3byte(&data[10]); reclen = 4 + 9; break; } case 0x05: { - fsettings->keyType = data[0]; - fsettings->keyVersion = data[1]; + fsettings->keyType = data[4]; + fsettings->keyVersion = data[5]; break; } default: { From 41ed6534a16b3af4b90f8fba848a16d455e10a39 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:05:51 +0300 Subject: [PATCH 18/37] add commands that can use any channel --- client/src/mifare/desfiresecurechan.c | 31 ++++++++++++++++----------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 2794e3197..4a51c6a5c 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -23,19 +23,23 @@ #include "protocols.h" #include "mifare/desfire_crypto.h" +static const uint8_t CommandsCanUseAnyChannel[] = { + MFDES_READ_DATA, + MFDES_WRITE_DATA, + MFDES_GET_VALUE, + MFDES_READ_RECORDS, + MFDES_WRITE_RECORD, + MFDES_UPDATE_RECORD, +}; + +static bool CommandCanUseAnyChannel(uint8_t cmd) { + for (int i = 0; i < ARRAYLEN(CommandsCanUseAnyChannel); i++) + if (CommandsCanUseAnyChannel[i] == cmd) + return true; + return false; +} + static const AllowedChannelModesS AllowedChannelModes[] = { - // read and write data can go in any mode - {MFDES_READ_DATA, DACd40, DCCNative, DCMPlain}, - {MFDES_READ_DATA, DACd40, DCCNative, DCMMACed}, - {MFDES_READ_DATA, DACd40, DCCNative, DCMEncrypted}, - {MFDES_READ_DATA, DACEV1, DCCNative, DCMMACed}, - {MFDES_READ_DATA, DACEV1, DCCNative, DCMEncrypted}, - {MFDES_WRITE_DATA, DACd40, DCCNative, DCMPlain}, - {MFDES_WRITE_DATA, DACd40, DCCNative, DCMMACed}, - {MFDES_WRITE_DATA, DACd40, DCCNative, DCMEncrypted}, - {MFDES_WRITE_DATA, DACEV1, DCCNative, DCMMACed}, - {MFDES_WRITE_DATA, DACEV1, DCCNative, DCMEncrypted}, - {MFDES_CREATE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_DELETE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_GET_APPLICATION_IDS, DACd40, DCCNative, DCMPlain}, @@ -118,6 +122,7 @@ static const CmdHeaderLengthsS CmdHeaderLengths[] = { {MFDES_CHANGE_KEY, 1}, {MFDES_CHANGE_KEY_EV2, 2}, {MFDES_CHANGE_CONFIGURATION, 1}, + {MFDES_GET_FILE_SETTINGS, 1}, {MFDES_CHANGE_FILE_SETTINGS, 1}, {MFDES_CREATE_TRANS_MAC_FILE, 5}, {MFDES_READ_DATA, 7}, @@ -360,6 +365,8 @@ bool PrintChannelModeWarning(uint8_t cmd, DesfireSecureChannel secureChannel, De // no security set if (secureChannel == DACNone) return true; + if (CommandCanUseAnyChannel(cmd)) + return true; bool found = false; for (int i = 0; i < ARRAY_LENGTH(AllowedChannelModes); i++) From 2ed139bfc36ca7e84b7cb963d486d45d80299bbf Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:06:20 +0300 Subject: [PATCH 19/37] communication mode to file mode and vice versa --- client/src/mifare/desfirecrypto.c | 38 +++++++++++++++++++++++++++++++ client/src/mifare/desfirecrypto.h | 3 +++ 2 files changed, 41 insertions(+) diff --git a/client/src/mifare/desfirecrypto.c b/client/src/mifare/desfirecrypto.c index e1015c2d8..b6bb5e961 100644 --- a/client/src/mifare/desfirecrypto.c +++ b/client/src/mifare/desfirecrypto.c @@ -345,6 +345,44 @@ uint8_t DesfireDESKeyGetVersion(uint8_t *key) { return version; } +DesfireCommunicationMode DesfireFileCommModeToCommMode(uint8_t file_comm_mode) { + DesfireCommunicationMode mode = DCMNone; + switch (file_comm_mode & 0x03) { + case 0x00: + case 0x02: + mode = DCMPlain; + break; + case 0x01: + mode = DCMMACed; + break; + case 0x03: + mode = DCMEncrypted; + break; + default: + break; + } + return mode; +} + +uint8_t DesfireCommModeToFileCommMode(DesfireCommunicationMode comm_mode) { + uint8_t fmode = DCMNone; + switch (comm_mode) { + case DCMPlain: + fmode = 0x00; + break; + case DCMMACed: + fmode = 0x01; + break; + case DCMEncrypted: + case DCMEncryptedPlain: + fmode = 0x11; + break; + case DCMNone: + break; + } + return fmode; +} + void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) { crc32_ex(data, len, crc); } diff --git a/client/src/mifare/desfirecrypto.h b/client/src/mifare/desfirecrypto.h index 0ec729a04..a559f11a9 100644 --- a/client/src/mifare/desfirecrypto.h +++ b/client/src/mifare/desfirecrypto.h @@ -105,6 +105,9 @@ void DesfireCryptoCMAC(DesfireContext *ctx, uint8_t *srcdata, size_t srcdatalen, void DesfireDESKeySetVersion(uint8_t *key, DesfireCryptoAlgorythm keytype, uint8_t version); uint8_t DesfireDESKeyGetVersion(uint8_t *key); +DesfireCommunicationMode DesfireFileCommModeToCommMode(uint8_t file_comm_mode); +uint8_t DesfireCommModeToFileCommMode(DesfireCommunicationMode comm_mode); + 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); bool desfire_crc32_check(uint8_t *data, const size_t len, uint8_t *crc); From 5215f4660cc7ce33f10db68ce53355753b3e864c Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:06:46 +0300 Subject: [PATCH 20/37] get comm mode --- client/src/mifare/desfirecore.c | 1 + client/src/mifare/desfirecore.h | 1 + 2 files changed, 2 insertions(+) diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index 667fa7696..befa56c6c 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -1377,6 +1377,7 @@ void DesfireFillFileSettings(uint8_t *data, size_t datalen, FileSettingsS *fsett fsettings->fileType = data[0]; fsettings->fileOption = data[1]; fsettings->fileCommMode = data[1] & 0x03; + fsettings->commMode = DesfireFileCommModeToCommMode(fsettings->fileCommMode); fsettings->additionalAccessRightsEn = ((data[1] & 0x80) != 0); fsettings->rawAccessRights = MemLeToUint2byte(&data[2]); DesfireDecodeFileAcessMode(&data[2], &fsettings->rAccess, &fsettings->wAccess, &fsettings->rwAccess, &fsettings->chAccess); diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 8ff954807..004a452f9 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -33,6 +33,7 @@ typedef struct { uint8_t fileType; uint8_t fileOption; uint8_t fileCommMode; + DesfireCommunicationMode commMode; bool additionalAccessRightsEn; uint16_t rawAccessRights; uint8_t rAccess; From 17944f7d0a05ee6554e308c614f2a442575964d5 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:07:18 +0300 Subject: [PATCH 21/37] auto read file improvement --- client/src/cmdhfmfdes.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 9ceb02310..89591f4c3 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6331,7 +6331,12 @@ static int CmdHF14ADesReadData(const char *Cmd) { // get file settings if (op == RFTAuto) { FileSettingsS fsettings; + + DesfireCommunicationMode commMode = dctx.commMode; + DesfireSetCommMode(&dctx, DCMMACed); res = DesfireGetFileSettingsStruct(&dctx, fnum, &fsettings); + DesfireSetCommMode(&dctx, commMode); + if (res == PM3_SUCCESS) { switch(fsettings.fileType) { case 0x00: @@ -6358,8 +6363,12 @@ static int CmdHF14ADesReadData(const char *Cmd) { } } if (verbose) - PrintAndLogEx(INFO, "Got file type: %s. Option: %s", GetDesfireFileType(fsettings.fileType), CLIGetOptionListStr(DesfireReadFileTypeOpts, op)); + PrintAndLogEx(INFO, "Got file type: %s. Option: %s. comm mode: %s", + GetDesfireFileType(fsettings.fileType), + CLIGetOptionListStr(DesfireReadFileTypeOpts, op), + CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); + DesfireSetCommMode(&dctx, fsettings.commMode); } else { PrintAndLogEx(WARNING, "GetFileSettings error. Can't get file type."); } From 774d60fa83526218060cd1517478adde0b6aada0 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:10:51 +0300 Subject: [PATCH 22/37] fix text --- client/src/cmdhfmfdes.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 89591f4c3..0ce7c3d40 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6609,8 +6609,8 @@ static command_t CommandTable[] = { {"getfilesettings", CmdHF14ADesGetFileSettings, IfPm3Iso14443a, "[new]Get file settings"}, {"chfilesettings", CmdHF14ADesChFileSettings, IfPm3Iso14443a, "[new]Change file settings"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, - {"read", CmdHF14ADesReadData, IfPm3Iso14443a, "[new]Read data from standard/backup/record file"}, - {"write", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record file"}, + {"read", CmdHF14ADesReadData, IfPm3Iso14443a, "[new]Read data from standard/backup/record/value/mac file"}, + {"write", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record/value file"}, {"value", CmdHF14ADesValueOperations, IfPm3Iso14443a, "[new]Operations with value file (get/credit/limited credit/debit/clear)"}, {"clearrecfile", CmdHF14ADesClearRecordFile, IfPm3Iso14443a, "[new]Clear record File"}, {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("System") " -----------------------"}, From 6f2bc725cab57d40168050531df1dc40c62e6b0f Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 00:15:14 +0300 Subject: [PATCH 23/37] fix help --- client/src/cmdhfmfdes.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 0ce7c3d40..d8a0dd543 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6235,7 +6235,8 @@ static int CmdHF14ADesReadData(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes read", "Read data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", - "hf mfdes read --aid 123456 --fid 01 -> read file: app=123456, file=01, offset=0, all the data. use default channel settings from `default` command"); + "hf mfdes read --aid 123456 --fid 01 -> read file: app=123456, file=01, offset=0, all the data. use default channel settings from `default` command\n" + "hf mfdes read --aid 123456 --fid 01 --type record --offset 000000 --length 000001 -> read one last record from record file. use default channel settings from `default` command"); void *argtable[] = { arg_param_begin, @@ -6430,7 +6431,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (resplen > 0) { size_t reccount = resplen / reclen; PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %u record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); - if (reccount > 0) + if (reccount > 1) PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); for (int i = 0; i < reccount; i++) { if (i != 0) From bc5d7084c34cae8fa1d3848b21953b73a76c5ec5 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 28 Jul 2021 09:51:35 +0200 Subject: [PATCH 24/37] change t55xx detect to unset lf config decimation to 1 if its value wasnt 1. Thanks to @mwalker33 --- armsrc/lfsampling.c | 4 +--- client/src/cmdlft55xx.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c index ed65fcb9b..60b25436a 100644 --- a/armsrc/lfsampling.c +++ b/armsrc/lfsampling.c @@ -45,9 +45,7 @@ void printLFConfig(void) { Dbprintf(" [a] averaging........... %s", (config.averaging) ? "yes" : "no"); Dbprintf(" [t] trigger threshold... %d", config.trigger_threshold); Dbprintf(" [s] samples to skip..... %d ", config.samples_to_skip); - - DbpString(_CYAN_("LF Sampling Stack")); - print_stack_usage(); + DbpString(""); } void printSamples(void) { diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 765f966e4..67818c266 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -942,6 +942,27 @@ static int CmdT55xxDetect(const char *Cmd) { // detect called so clear data blocks T55x7_ClearAllBlockData(); + // make sure decimate == 1 + sample_config curr_lf_config; + memset(&curr_lf_config, 0, sizeof(sample_config)); + + res = lf_getconfig(&curr_lf_config); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to get current device LF config"); + return res; + } + int8_t old_decimation = curr_lf_config.decimation; + if (curr_lf_config.decimation != 1) { + curr_lf_config.decimation = 1; + curr_lf_config.verbose = false; + res = lf_config(&curr_lf_config); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to set LF configuration decimation value to 1"); + return res; + } + } + + // sanity check. if (SanityOfflineCheck(use_gb) != PM3_SUCCESS) return PM3_ESOFT; @@ -1016,6 +1037,18 @@ static int CmdT55xxDetect(const char *Cmd) { config.pwd = 0x00; PrintAndLogEx(WARNING, "Could not detect modulation automatically. Try setting it manually with " _YELLOW_("\'lf t55xx config\'")); } + + + if (old_decimation != curr_lf_config.decimation) { + curr_lf_config.decimation = old_decimation; + curr_lf_config.verbose = false; + res = lf_config(&curr_lf_config); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to restore LF configuration"); + return res; + } + } + return PM3_SUCCESS; } From 45ce250810f4ccf5717f9e70fb9aabcbc988bdce Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 28 Jul 2021 09:53:31 +0200 Subject: [PATCH 25/37] text --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9aa805178..d70334344 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] + - Fic `lf t55xx detect` - to unset lf config decimation if value is not one (@iceman1001) - Fix `hf 15 sample` - data collection works again (@iceman1001) - Changed `data plot -h` - removed line (@doegox) - Fix `lf_tharexde` - double define of global variable (@axisray) From b1f819e20805c0dd03996c034fac6500d7e88cc9 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 14:18:53 +0300 Subject: [PATCH 26/37] d40/encoded channel works --- client/src/cmdhfmfdes.c | 19 +++++--- client/src/mifare/desfiresecurechan.c | 68 +++++++++++++-------------- 2 files changed, 44 insertions(+), 43 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index d8a0dd543..77c7ad595 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6363,13 +6363,14 @@ static int CmdHF14ADesReadData(const char *Cmd) { break; } } + + DesfireSetCommMode(&dctx, fsettings.commMode); + if (verbose) PrintAndLogEx(INFO, "Got file type: %s. Option: %s. comm mode: %s", GetDesfireFileType(fsettings.fileType), CLIGetOptionListStr(DesfireReadFileTypeOpts, op), CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); - - DesfireSetCommMode(&dctx, fsettings.commMode); } else { PrintAndLogEx(WARNING, "GetFileSettings error. Can't get file type."); } @@ -6408,6 +6409,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { } if (op == RFTRecord) { + resplen = 0; if (reclen == 0) { res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); if (res != PM3_SUCCESS) { @@ -6421,11 +6423,14 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (verbose) PrintAndLogEx(INFO, "Record length %zu", reclen); - res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); - DropField(); - return PM3_ESOFT; + // if we got one record via the DesfireReadRecords before -- we not need to get it 2nd time + if (length != 1 || resplen == 0) { + res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } } if (resplen > 0) { diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 4a51c6a5c..13a3b907e 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -148,45 +148,38 @@ static void DesfireSecureChannelEncodeD40(DesfireContext *ctx, uint8_t cmd, uint size_t rlen = 0; uint8_t hdrlen = DesfireGetCmdHeaderLen(cmd); - switch (ctx->commMode) { - case DCMPlain: - memcpy(dstdata, srcdata, srcdatalen); - *dstdatalen = srcdatalen; - break; - case DCMMACed: - if (srcdatalen == 0) - break; + if (ctx->commMode == DCMMACed || (ctx->commMode == DCMEncrypted && srcdatalen <= hdrlen)) { + if (srcdatalen == 0) + return; - rlen = srcdatalen + DesfireGetMACLength(ctx); - memcpy(data, srcdata, srcdatalen); - DesfireCryptoEncDec(ctx, true, data, srcdatalen, NULL, true); - memcpy(dstdata, srcdata, srcdatalen); - memcpy(&dstdata[srcdatalen], ctx->IV, 4); - *dstdatalen = rlen; - break; - case DCMEncrypted: - if (srcdatalen == 0 || srcdatalen <= hdrlen) - break; + rlen = srcdatalen + DesfireGetMACLength(ctx); + memcpy(data, srcdata, srcdatalen); + DesfireCryptoEncDec(ctx, true, data, srcdatalen, NULL, true); + memcpy(dstdata, srcdata, srcdatalen); + memcpy(&dstdata[srcdatalen], ctx->IV, 4); + *dstdatalen = rlen; + } else if (ctx->commMode == DCMEncrypted) { + if (srcdatalen == 0 || srcdatalen <= hdrlen) + return; - rlen = padded_data_length(srcdatalen + 2, desfire_get_key_block_length(ctx->keyType)); // 2 - crc16 - memcpy(data, srcdata, srcdatalen); - compute_crc(CRC_14443_A, data, srcdatalen, &data[srcdatalen], &data[srcdatalen + 1]); - DesfireCryptoEncDec(ctx, true, data, rlen, dstdata, true); - *dstdatalen = rlen; - break; - case DCMEncryptedPlain: - if (srcdatalen == 0 || srcdatalen <= hdrlen) - break; + rlen = padded_data_length(srcdatalen + 2, desfire_get_key_block_length(ctx->keyType)); // 2 - crc16 + memcpy(data, srcdata, srcdatalen); + compute_crc(CRC_14443_A, data, srcdatalen, &data[srcdatalen], &data[srcdatalen + 1]); + DesfireCryptoEncDec(ctx, true, data, rlen, dstdata, true); + *dstdatalen = rlen; + } if (ctx->commMode == DCMEncryptedPlain) { + if (srcdatalen == 0 || srcdatalen <= hdrlen) + return; - rlen = padded_data_length(srcdatalen - hdrlen, desfire_get_key_block_length(ctx->keyType)) + hdrlen; - memcpy(data, srcdata, srcdatalen); - memcpy(dstdata, srcdata, hdrlen); - DesfireCryptoEncDec(ctx, true, &data[hdrlen], rlen - hdrlen, &dstdata[hdrlen], true); - *dstdatalen = rlen; - ctx->commMode = DCMEncrypted; - break; - case DCMNone: - ; + rlen = padded_data_length(srcdatalen - hdrlen, desfire_get_key_block_length(ctx->keyType)) + hdrlen; + memcpy(data, srcdata, srcdatalen); + memcpy(dstdata, srcdata, hdrlen); + DesfireCryptoEncDec(ctx, true, &data[hdrlen], rlen - hdrlen, &dstdata[hdrlen], true); + *dstdatalen = rlen; + ctx->commMode = DCMEncrypted; + } else { + memcpy(dstdata, srcdata, srcdatalen); + *dstdatalen = srcdatalen; } } @@ -261,6 +254,9 @@ static void DesfireSecureChannelDecodeD40(DesfireContext *ctx, uint8_t *srcdata, switch (ctx->commMode) { case DCMMACed: + //if (srcdatalen > 4) + // *dstdatalen = srcdatalen - 4; + // TODO check MAC!!! break; case DCMEncrypted: From b508ca3e5d18c3b50c64b77a02f43534816f218c Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 15:27:22 +0300 Subject: [PATCH 27/37] d40/mac mode works in mac and plain modes --- client/src/cmdhfmfdes.c | 5 ++++- client/src/mifare/desfirecrypto.c | 17 ++++++++++------- client/src/mifare/desfirecrypto.h | 2 +- client/src/mifare/desfiresecurechan.c | 26 +++++++++++++++++++++----- 4 files changed, 36 insertions(+), 14 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 77c7ad595..cf15dd0d9 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6334,7 +6334,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { FileSettingsS fsettings; DesfireCommunicationMode commMode = dctx.commMode; - DesfireSetCommMode(&dctx, DCMMACed); + DesfireSetCommMode(&dctx, DCMPlain); res = DesfireGetFileSettingsStruct(&dctx, fnum, &fsettings); DesfireSetCommMode(&dctx, commMode); @@ -6365,6 +6365,9 @@ static int CmdHF14ADesReadData(const char *Cmd) { } DesfireSetCommMode(&dctx, fsettings.commMode); + + if (fsettings.fileCommMode != 0 && noauth) + PrintAndLogEx(WARNING, "File needs communication mode `%s` but there is no authentication", CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); if (verbose) PrintAndLogEx(INFO, "Got file type: %s. Option: %s. comm mode: %s", diff --git a/client/src/mifare/desfirecrypto.c b/client/src/mifare/desfirecrypto.c index b6bb5e961..be98106a7 100644 --- a/client/src/mifare/desfirecrypto.c +++ b/client/src/mifare/desfirecrypto.c @@ -212,14 +212,12 @@ static void DesfireCryptoEncDecSingleBlock(uint8_t *key, DesfireCryptoAlgorythm memcpy(dstdata, edata, block_size); } -void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool encode, uint8_t *iv) { +void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool dir_to_send, bool encode, uint8_t *iv) { uint8_t data[1024] = {0}; uint8_t xiv[DESFIRE_MAX_CRYPTO_BLOCK_SIZE] = {0}; - bool xencode = encode; if (ctx->secureChannel == DACd40) { memset(ctx->IV, 0, DESFIRE_MAX_CRYPTO_BLOCK_SIZE); - xencode = false; } size_t block_size = desfire_get_key_block_length(ctx->keyType); @@ -232,9 +230,9 @@ void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *s size_t offset = 0; while (offset < srcdatalen) { if (use_session_key) - DesfireCryptoEncDecSingleBlock(ctx->sessionKeyMAC, ctx->keyType, srcdata + offset, data + offset, xiv, encode, xencode); + DesfireCryptoEncDecSingleBlock(ctx->sessionKeyMAC, ctx->keyType, srcdata + offset, data + offset, xiv, dir_to_send, encode); else - DesfireCryptoEncDecSingleBlock(ctx->key, ctx->keyType, srcdata + offset, data + offset, xiv, encode, xencode); + DesfireCryptoEncDecSingleBlock(ctx->key, ctx->keyType, srcdata + offset, data + offset, xiv, dir_to_send, encode); offset += block_size; } @@ -248,7 +246,12 @@ void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *s } void DesfireCryptoEncDec(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool encode) { - DesfireCryptoEncDecEx(ctx, use_session_key, srcdata, srcdatalen, dstdata, encode, NULL); + bool dir_to_send = encode; + bool xencode = encode; + if (ctx->secureChannel == DACd40) + xencode = false; + + DesfireCryptoEncDecEx(ctx, use_session_key, srcdata, srcdatalen, dstdata, dir_to_send, xencode, NULL); } static void DesfireCMACGenerateSubkeys(DesfireContext *ctx, uint8_t *sk1, uint8_t *sk2) { @@ -261,7 +264,7 @@ static void DesfireCMACGenerateSubkeys(DesfireContext *ctx, uint8_t *sk1, uint8_ uint8_t ivect[kbs]; memset(ivect, 0, kbs); - DesfireCryptoEncDecEx(ctx, true, l, kbs, l, true, ivect); + DesfireCryptoEncDecEx(ctx, true, l, kbs, l, true, true, ivect); bool txor = false; diff --git a/client/src/mifare/desfirecrypto.h b/client/src/mifare/desfirecrypto.h index a559f11a9..fddef64c9 100644 --- a/client/src/mifare/desfirecrypto.h +++ b/client/src/mifare/desfirecrypto.h @@ -99,7 +99,7 @@ size_t DesfireGetMACLength(DesfireContext *ctx); size_t DesfireSearchCRCPos(uint8_t *data, size_t datalen, uint8_t respcode, uint8_t crclen); void DesfireCryptoEncDec(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool encode); -void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool encode, uint8_t *iv); +void DesfireCryptoEncDecEx(DesfireContext *ctx, bool use_session_key, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, bool dir_to_send, bool encode, uint8_t *iv); void DesfireCryptoCMAC(DesfireContext *ctx, uint8_t *srcdata, size_t srcdatalen, uint8_t *cmac); void DesfireDESKeySetVersion(uint8_t *key, DesfireCryptoAlgorythm keytype, uint8_t version); diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 13a3b907e..fb51f9d92 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -58,6 +58,7 @@ static const AllowedChannelModesS AllowedChannelModes[] = { {MFDES_DEBIT, DACd40, DCCNative, DCMPlain}, {MFDES_COMMIT_TRANSACTION, DACd40, DCCNative, DCMPlain}, {MFDES_CLEAR_RECORD_FILE, DACd40, DCCNative, DCMPlain}, + {MFDES_GET_FILE_SETTINGS, DACd40, DCCNative, DCMPlain}, {MFDES_GET_VALUE, DACd40, DCCNative, DCMMACed}, {MFDES_CREDIT, DACd40, DCCNative, DCMMACed}, @@ -249,16 +250,31 @@ void DesfireSecureChannelEncode(DesfireContext *ctx, uint8_t cmd, uint8_t *srcda } static void DesfireSecureChannelDecodeD40(DesfireContext *ctx, uint8_t *srcdata, size_t srcdatalen, uint8_t respcode, uint8_t *dstdata, size_t *dstdatalen) { + uint8_t data[1024] = {0}; + size_t rlen = 0; + memcpy(dstdata, srcdata, srcdatalen); *dstdatalen = srcdatalen; switch (ctx->commMode) { - case DCMMACed: - //if (srcdatalen > 4) - // *dstdatalen = srcdatalen - 4; - // TODO check MAC!!! - + case DCMMACed: { + size_t maclen = DesfireGetMACLength(ctx); + if (srcdatalen > maclen) { + uint8_t mac[16] = {0}; + rlen = padded_data_length(srcdatalen - maclen, desfire_get_key_block_length(ctx->keyType)); + memcpy(data, srcdata, srcdatalen - maclen); + DesfireCryptoEncDecEx(ctx, true, data, rlen, NULL, true, true, mac); + + if (memcmp(mac, &srcdata[srcdatalen - maclen], maclen) == 0) { + *dstdatalen = srcdatalen - maclen; + } else { + PrintAndLogEx(WARNING, "Received MAC is not match with calculated"); + //PrintAndLogEx(INFO, " received MAC: %s", sprint_hex(&srcdata[srcdatalen - maclen], maclen)); + //PrintAndLogEx(INFO, " calculated MAC: %s", sprint_hex(mac, maclen)); + } + } break; + } case DCMEncrypted: if (srcdatalen < desfire_get_key_block_length(ctx->keyType)) { memcpy(dstdata, srcdata, srcdatalen); From c098c496eb0e521a58aa4a4dcb2b0ed7138f5734 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 16:37:04 +0300 Subject: [PATCH 28/37] coverity 353982 353927 --- client/src/cmdhfmfdes.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index cf15dd0d9..bcfbd3533 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -3912,6 +3912,7 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { CLIGetHexWithReturn(ctx, 13, keydata, &oldkeylen); if (oldkeylen && oldkeylen != desfire_get_key_length(oldkeytype)) { PrintAndLogEx(ERR, "%s old key must have %d bytes length instead of %d.", CLIGetOptionListStr(DesfireAlgoOpts, oldkeytype), desfire_get_key_length(oldkeytype), oldkeylen); + CLIParserFree(ctx); return PM3_EINVARG; } if (oldkeylen) @@ -6438,7 +6439,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { if (resplen > 0) { size_t reccount = resplen / reclen; - PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %u record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %d record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); if (reccount > 1) PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); for (int i = 0; i < reccount; i++) { From f5d5f088b8bb09482eeb607b31b4bfe90b8feb67 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 18:13:07 +0300 Subject: [PATCH 29/37] write file command --- client/src/cmdhfmfdes.c | 270 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 259 insertions(+), 11 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index bcfbd3533..ce5dc21b9 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -1518,7 +1518,7 @@ static int handler_desfire_getkeysettings(uint8_t *key_settings, uint8_t *num_ke return res; } -static int handler_desfire_commit_transaction(void) { +/*static int handler_desfire_commit_transaction(void) { sAPDU apdu = {0x90, MFDES_COMMIT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xC7 uint32_t recv_len = 0; uint16_t sw = 0; @@ -1531,7 +1531,7 @@ static int handler_desfire_commit_transaction(void) { return PM3_ESOFT; return res; -} +}*/ // --- GET APPIDS static int handler_desfire_appids(uint8_t *dest, uint32_t *app_ids_len) { @@ -1747,12 +1747,12 @@ static int handler_desfire_getvalue(mfdes_value_t *value, uint32_t *resplen, uin return res; } -static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint8_t cs) { +//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 */ - +/* if (data->fileno > 0x1F) { return PM3_EINVARG; } @@ -1802,14 +1802,14 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, apdu.Lc = plen - 1; } - /* + * // we dont want to change the value of datasize, so delt with above without change // Doing so can create wrong offsets and endless loop. 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) { @@ -1828,7 +1828,7 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, } } return res; -} +}*/ static int getKeySettings(uint8_t *aid) { if (aid == NULL) return PM3_EINVARG; @@ -2041,7 +2041,7 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { return res; } -static int selectfile(uint8_t *aid, uint8_t fileno, uint8_t *cs) { +/*static int selectfile(uint8_t *aid, uint8_t fileno, uint8_t *cs) { if (handler_desfire_select_application(aid) != PM3_SUCCESS) { PrintAndLogEx(ERR, _RED_(" Couldn't select aid.")); return PM3_ESOFT; @@ -2071,7 +2071,7 @@ static int selectfile(uint8_t *aid, uint8_t fileno, uint8_t *cs) { } *cs = filesettings[1]; return res; -} +}*/ static int CmdHF14ADesInfo(const char *Cmd) { CLIParserContext *ctx; @@ -6252,7 +6252,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_str0("c", "ccset", "", "Communicaton command set: native/niso/iso"), arg_str0("s", "schann", "", "Secure channel: d40/ev1/ev2"), arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), - arg_str0(NULL, "fid", "", "File ID for clearing (1 hex byte)"), + arg_str0(NULL, "fid", "", "File ID (1 hex byte)"), arg_lit0(NULL, "no-auth", "execute without authentication"), arg_str0(NULL, "type", "", "File Type auto/data(Standard/Backup)/value/record(linear/cyclic)/mac). Auto - check file settings and then read. Default: auto"), arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). For records - record number (0 - lastest record). Default 0"), @@ -6479,8 +6479,255 @@ static int CmdHF14ADesReadData(const char *Cmd) { } static int CmdHF14ADesWriteData(const char *Cmd) { - CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes write", + "Write data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", + "hf mfdes write --aid 123456 --fid 01 -d 01020304 -> write file: app=123456, file=01, offset=0, get file type from card. use default channel settings from `default` command\n" + "hf mfdes write --aid 123456 --fid 01 --type record --offset 000000 -d 11223344 -> write record to record file. use default channel settings from `default` command"); + + void *argtable[] = { + arg_param_begin, + arg_lit0("a", "apdu", "show APDU requests and responses"), + arg_lit0("v", "verbose", "show technical data"), + arg_int0("n", "keyno", "", "Key number"), + arg_str0("t", "algo", "", "Crypt algo: DES, 2TDEA, 3TDEA, AES"), + arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("f", "kdf", "", "Key Derivation Function (KDF): None, AN10922, Gallagher"), + arg_str0("i", "kdfi", "", "KDF input (HEX 1-31 bytes)"), + arg_str0("m", "cmode", "", "Communicaton mode: plain/mac/encrypt"), + arg_str0("c", "ccset", "", "Communicaton command set: native/niso/iso"), + arg_str0("s", "schann", "", "Secure channel: d40/ev1/ev2"), + arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), + arg_str0(NULL, "fid", "", "File ID (1 hex byte)"), + arg_lit0(NULL, "no-auth", "execute without authentication"), + arg_str0(NULL, "type", "", "File Type auto/data(Standard/Backup)/value/record(linear/cyclic)/mac). Auto - check file settings and then write. Default: auto"), + arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). For records - record number (0 - lastest record). Default 0"), + arg_str0("d", "data", "", "data for write (data/record file), credit/debit(value file)"), + arg_lit0(NULL, "debit", "use for value file debit operation instead of credit"), + arg_lit0(NULL, "commit", "commit needs for backup, value and record data file. In `auto` type it set automatically."), + arg_int0(NULL, "updaterec", "", "Record number for update record command. Updates record instead of write. Lastest record - 0"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + bool APDULogging = arg_get_lit(ctx, 1); + bool verbose = arg_get_lit(ctx, 2); + bool noauth = arg_get_lit(ctx, 13); + + DesfireContext dctx; + int securechann = defaultSecureChannel; + uint32_t appid = 0x000000; + int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid); + if (res) { + CLIParserFree(ctx); + return res; + } + + uint32_t fnum = 1; + res = arg_get_u32_hexstr_def_nlen(ctx, 12, 1, &fnum, 1, true); + if (res == 2) { + PrintAndLogEx(ERR, "File ID must have 1 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + int op = RFTAuto; + if (CLIGetOptionList(arg_get_str(ctx, 14), DesfireReadFileTypeOpts, &op)) { + CLIParserFree(ctx); + return PM3_ESOFT; + } + + uint32_t offset = 0; + res = arg_get_u32_hexstr_def_nlen(ctx, 15, 0, &offset, 3, true); + if (res == 2) { + PrintAndLogEx(ERR, "Offset must have 3 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + uint8_t data[1024] = {0}; + int datalen = sizeof(data); + CLIGetHexWithReturn(ctx, 16, data, &datalen); + if (datalen == 0) { + PrintAndLogEx(ERR, "Data for write must be present."); + CLIParserFree(ctx); + return PM3_EINVARG; + } + + bool debit = arg_get_lit(ctx, 17); + bool commit = arg_get_lit(ctx, 18); + + SetAPDULogging(APDULogging); + CLIParserFree(ctx); + + if (fnum > 0x1F) { + PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fnum); + return PM3_EINVARG; + } + + if (noauth) { + res = DesfireSelectAIDHex(&dctx, appid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire select " _RED_("error") "."); + DropField(); + return res; + } + } else { + res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose); + if (res != PM3_SUCCESS) { + DropField(); + return res; + } + } + + // get file settings + if (op == RFTAuto) { + FileSettingsS fsettings; + + DesfireCommunicationMode commMode = dctx.commMode; + DesfireSetCommMode(&dctx, DCMPlain); + res = DesfireGetFileSettingsStruct(&dctx, fnum, &fsettings); + DesfireSetCommMode(&dctx, commMode); + + if (res == PM3_SUCCESS) { + switch(fsettings.fileType) { + case 0x00: + case 0x01: { + op = RFTData; + commit = (fsettings.fileType == 0x01); + break; + } + case 0x02: { + op = RFTValue; + commit = true; + break; + } + case 0x03: + case 0x04: { + op = RFTRecord; + commit = true; + if (datalen > fsettings.recordSize) + PrintAndLogEx(WARNING, "Record size (%d) " _RED_("is less") " than data length (%d)", fsettings.recordSize, datalen); + break; + } + case 0x05: { + op = RFTMAC; + commit = false; + break; + } + default: { + break; + } + } + + DesfireSetCommMode(&dctx, fsettings.commMode); + + if (fsettings.fileCommMode != 0 && noauth) + PrintAndLogEx(WARNING, "File needs communication mode `%s` but there is no authentication", CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); + + if (verbose) + PrintAndLogEx(INFO, "Got file type: %s. Option: %s. comm mode: %s", + GetDesfireFileType(fsettings.fileType), + CLIGetOptionListStr(DesfireReadFileTypeOpts, op), + CLIGetOptionListStr(DesfireCommunicationModeOpts, fsettings.commMode)); + } else { + PrintAndLogEx(WARNING, "GetFileSettings error. Can't get file type."); + } + } + + if (op == RFTData) { + res = DesfireWriteFile(&dctx, fnum, offset, datalen, data); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire WriteFile command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + if (commit) { + res = DesfireCommitTransaction(&dctx, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + } + + PrintAndLogEx(SUCCESS, "Write data file %02x " _GREEN_("success"), fnum); + } + + if (op == RFTValue) { + if (datalen != 4) + PrintAndLogEx(WARNING, "Value " _RED_("should be") " 4 byte length instead of %d", datalen); + + uint32_t value = MemBeToUint4byte(data); + uint8_t vop = (debit) ? MFDES_DEBIT : MFDES_CREDIT; + res = DesfireValueFileOperations(&dctx, fnum, vop, &value); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire %s operation " _RED_("error") ". Result: %d", CLIGetOptionListStr(DesfireValueFileOperOpts, vop), res); + DropField(); + return PM3_ESOFT; + } + + if (commit) { + res = DesfireCommitTransaction(&dctx, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + } + + PrintAndLogEx(SUCCESS, "Value file %02x (%s) " _GREEN_("success"), fnum, CLIGetOptionListStr(DesfireValueFileOperOpts, vop)); + } + + if (op == RFTRecord) { +/* resplen = 0; + if (reclen == 0) { + res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords (len=1) command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + reclen = resplen; + } + + if (verbose) + PrintAndLogEx(INFO, "Record length %zu", reclen); + + // if we got one record via the DesfireReadRecords before -- we not need to get it 2nd time + if (length != 1 || resplen == 0) { + res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + } + + if (resplen > 0) { + size_t reccount = resplen / reclen; + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %d record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); + if (reccount > 1) + PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); + for (int i = 0; i < reccount; i++) { + if (i != 0) + PrintAndLogEx(SUCCESS, "Record %d", i + offset); + print_buffer_with_offset(&resp[i * reclen], reclen, offset, (i == 0)); + } + } else { + PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); + }*/ + } + + if (op == RFTMAC) { + PrintAndLogEx(ERR, "Can't " _RED_("write") " to transaction MAC file"); + } + + DropField(); + return PM3_SUCCESS; + +/* CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes write", "Write data to file\n" "Make sure to select aid or authenticate aid before running this command.", @@ -6574,6 +6821,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { } DropFieldDesfire(); return res; + */ } static int CmdHF14ADesTest(const char *Cmd) { From 896aeefd9a6dc0139c0e992ddf3c6b45ebfc0ae7 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 18:24:50 +0300 Subject: [PATCH 30/37] move commit phase outside --- client/src/cmdhfmfdes.c | 48 ++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index ce5dc21b9..4ce2fc679 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6643,21 +6643,16 @@ static int CmdHF14ADesWriteData(const char *Cmd) { return PM3_ESOFT; } - if (commit) { - res = DesfireCommitTransaction(&dctx, false, 0); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); - DropField(); - return PM3_ESOFT; - } - } - - PrintAndLogEx(SUCCESS, "Write data file %02x " _GREEN_("success"), fnum); + if (verbose) + PrintAndLogEx(INFO, "Write data file %02x " _GREEN_("success"), fnum); } if (op == RFTValue) { - if (datalen != 4) - PrintAndLogEx(WARNING, "Value " _RED_("should be") " 4 byte length instead of %d", datalen); + if (datalen != 4) { + PrintAndLogEx(ERR, "Value " _RED_("should be") " 4 byte length instead of %d", datalen); + DropField(); + return PM3_EINVARG; + } uint32_t value = MemBeToUint4byte(data); uint8_t vop = (debit) ? MFDES_DEBIT : MFDES_CREDIT; @@ -6668,16 +6663,8 @@ static int CmdHF14ADesWriteData(const char *Cmd) { return PM3_ESOFT; } - if (commit) { - res = DesfireCommitTransaction(&dctx, false, 0); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); - DropField(); - return PM3_ESOFT; - } - } - - PrintAndLogEx(SUCCESS, "Value file %02x (%s) " _GREEN_("success"), fnum, CLIGetOptionListStr(DesfireValueFileOperOpts, vop)); + if (verbose) + PrintAndLogEx(INFO, "%s value file %02x (%s) " _GREEN_("success"), (debit) ? "Debit" : "Credit", fnum, CLIGetOptionListStr(DesfireValueFileOperOpts, vop)); } if (op == RFTRecord) { @@ -6722,8 +6709,25 @@ static int CmdHF14ADesWriteData(const char *Cmd) { if (op == RFTMAC) { PrintAndLogEx(ERR, "Can't " _RED_("write") " to transaction MAC file"); + DropField(); + return PM3_EINVARG; } + // commit phase + if (commit) { + res = DesfireCommitTransaction(&dctx, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire CommitTransaction command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + + if (verbose) + PrintAndLogEx(INFO, "Commit " _GREEN_("OK")); + } + + PrintAndLogEx(INFO, "Write %s file %02x " _GREEN_("success"), CLIGetOptionListStr(DesfireReadFileTypeOpts, op), fnum); + DropField(); return PM3_SUCCESS; From 3c2542d58b1326b1cb65c9f0a460674fdacef5ad Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 18:37:22 +0300 Subject: [PATCH 31/37] add some help, fix commit logic --- client/src/cmdhfmfdes.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 4ce2fc679..a99cc2304 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6483,6 +6483,10 @@ static int CmdHF14ADesWriteData(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes write", "Write data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", "hf mfdes write --aid 123456 --fid 01 -d 01020304 -> write file: app=123456, file=01, offset=0, get file type from card. use default channel settings from `default` command\n" + "hf mfdes write --aid 123456 --fid 01 --type data -d 01020304 --0ffset 000100 -> write data to std file with offset 0x100\n" + "hf mfdes write --aid 123456 --fid 01 --type data -d 01020304 --commit -> write data to backup file with commit\n" + "hf mfdes write --aid 123456 --fid 01 --type value -d 00000001 -> increment value file\n" + "hf mfdes write --aid 123456 --fid 01 --type value --debit -d 00000001 -> decrement value file\n" "hf mfdes write --aid 123456 --fid 01 --type record --offset 000000 -d 11223344 -> write record to record file. use default channel settings from `default` command"); void *argtable[] = { @@ -6504,7 +6508,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). For records - record number (0 - lastest record). Default 0"), arg_str0("d", "data", "", "data for write (data/record file), credit/debit(value file)"), arg_lit0(NULL, "debit", "use for value file debit operation instead of credit"), - arg_lit0(NULL, "commit", "commit needs for backup, value and record data file. In `auto` type it set automatically."), + arg_lit0(NULL, "commit", "commit needs for backup file only. For the other file types - command set it automatically."), arg_int0(NULL, "updaterec", "", "Record number for update record command. Updates record instead of write. Lastest record - 0"), arg_param_end }; @@ -6665,6 +6669,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { if (verbose) PrintAndLogEx(INFO, "%s value file %02x (%s) " _GREEN_("success"), (debit) ? "Debit" : "Credit", fnum, CLIGetOptionListStr(DesfireValueFileOperOpts, vop)); + commit = true; } if (op == RFTRecord) { @@ -6705,6 +6710,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { } else { PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); }*/ + commit = true; } if (op == RFTMAC) { From 601597362db0384e5820ac30f1cafb4e59e88945 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 18:51:56 +0300 Subject: [PATCH 32/37] write record --- client/src/cmdhfmfdes.c | 56 ++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 32 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index a99cc2304..b4e52561b 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6561,6 +6561,15 @@ static int CmdHF14ADesWriteData(const char *Cmd) { bool debit = arg_get_lit(ctx, 17); bool commit = arg_get_lit(ctx, 18); + uint32_t updaterecno = 0; + res = arg_get_u32_hexstr_def_nlen(ctx, 19, 0, &offset, 3, true); + bool updaterec = (res == 1); + if (res == 2) { + PrintAndLogEx(ERR, "Offset must have 3 byte length"); + CLIParserFree(ctx); + return PM3_EINVARG; + } + SetAPDULogging(APDULogging); CLIParserFree(ctx); @@ -6673,43 +6682,26 @@ static int CmdHF14ADesWriteData(const char *Cmd) { } if (op == RFTRecord) { -/* resplen = 0; - if (reclen == 0) { - res = DesfireReadRecords(&dctx, fnum, offset, 1, resp, &resplen); + if (!updaterec) { + res = DesfireWriteRecord(&dctx, fnum, offset, datalen, data); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire ReadRecords (len=1) command " _RED_("error") ". Result: %d", res); + PrintAndLogEx(ERR, "Desfire WriteRecord command " _RED_("error") ". Result: %d", res); DropField(); return PM3_ESOFT; } - reclen = resplen; - } - - if (verbose) - PrintAndLogEx(INFO, "Record length %zu", reclen); - - // if we got one record via the DesfireReadRecords before -- we not need to get it 2nd time - if (length != 1 || resplen == 0) { - res = DesfireReadRecords(&dctx, fnum, offset, length, resp, &resplen); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Desfire ReadRecords command " _RED_("error") ". Result: %d", res); - DropField(); - return PM3_ESOFT; - } - } - - if (resplen > 0) { - size_t reccount = resplen / reclen; - PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x from record %d record count %zu record length %zu", resplen, fnum, offset, reccount, reclen); - if (reccount > 1) - PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); - for (int i = 0; i < reccount; i++) { - if (i != 0) - PrintAndLogEx(SUCCESS, "Record %d", i + offset); - print_buffer_with_offset(&resp[i * reclen], reclen, offset, (i == 0)); - } + if (verbose) + PrintAndLogEx(INFO, "Write record file %02x " _GREEN_("success"), fnum); } else { - PrintAndLogEx(SUCCESS, "Read operation returned no data from file %d", fnum); - }*/ + res = DesfireUpdateRecord(&dctx, fnum, updaterecno, offset, datalen, data); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire UpdateRecord command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + if (verbose) + PrintAndLogEx(INFO, "Update record %06x in the file %02x " _GREEN_("success"), updaterecno, fnum); + } + commit = true; } From cba4e3f90d0498a85586d436368600b3a4937e72 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 19:18:16 +0300 Subject: [PATCH 33/37] update record works --- client/src/cmdhfmfdes.c | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index b4e52561b..a13cd7520 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6444,7 +6444,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { PrintAndLogEx(SUCCESS, "Lastest record at the bottom."); for (int i = 0; i < reccount; i++) { if (i != 0) - PrintAndLogEx(SUCCESS, "Record %d", i + offset); + PrintAndLogEx(SUCCESS, "Record %d", reccount - (i + offset + 1)); print_buffer_with_offset(&resp[i * reclen], reclen, offset, (i == 0)); } } else { @@ -6561,14 +6561,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { bool debit = arg_get_lit(ctx, 17); bool commit = arg_get_lit(ctx, 18); - uint32_t updaterecno = 0; - res = arg_get_u32_hexstr_def_nlen(ctx, 19, 0, &offset, 3, true); - bool updaterec = (res == 1); - if (res == 2) { - PrintAndLogEx(ERR, "Offset must have 3 byte length"); - CLIParserFree(ctx); - return PM3_EINVARG; - } + int updaterecno = arg_get_int_def(ctx, 19, -1); SetAPDULogging(APDULogging); CLIParserFree(ctx); @@ -6682,7 +6675,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { } if (op == RFTRecord) { - if (!updaterec) { + if (updaterecno < 0) { res = DesfireWriteRecord(&dctx, fnum, offset, datalen, data); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Desfire WriteRecord command " _RED_("error") ". Result: %d", res); From 317526f3fac489a0023947e26a8e5bf78c068711 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 19:24:04 +0300 Subject: [PATCH 34/37] remove old --- client/src/cmdhfmfdes.c | 98 +---------------------------------------- 1 file changed, 1 insertion(+), 97 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index a13cd7520..78c725152 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6721,102 +6721,6 @@ static int CmdHF14ADesWriteData(const char *Cmd) { DropField(); return PM3_SUCCESS; - -/* CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfdes write", - "Write data to file\n" - "Make sure to select aid or authenticate aid before running this command.", - "hf mfdes write -n 01 -t 0 -o 000000 -d 3132333435363738" - ); - - void *argtable[] = { - arg_param_begin, - arg_int0("n", "fileno", "", "File Number (0 - 31)"), - arg_strx0("o", "offset", "", "File Offset (3 hex bytes, big endian), optional"), - arg_strx0("d", "data", "", "Data to write (hex bytes, 256 bytes max)"), - arg_int0("t", "type", "", "File Type (0 = Standard / Backup, 1 = Record)"), - arg_strx0("a", "aid", "", "App ID to select as hex bytes (3 bytes, big endian)"), - arg_param_end - }; - - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fno = arg_get_int_def(ctx, 1, 0); - - int offsetlength = 0; - uint8_t offset[3] = {0}; - int res_offset = CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); - - // iceman: we only have a 1024 byte commandline input array. So this is pointlessly large. - // with 2char hex, 512bytes could be input. - // Instead large binary inputs should be BINARY files and written to card. - int dlength = 512; - uint8_t data[512] = {0}; - int res_data = CLIParamHexToBuf(arg_get_str(ctx, 3), data, 512, &dlength); - - int type = arg_get_int(ctx, 4); - int aidlength = 3; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 5, aid, &aidlength); - swap24(aid); - - CLIParserFree(ctx); - - swap24(offset); - - if (type < 0 || type > 1) { - PrintAndLogEx(ERR, "Unknown type (0=Standard/Backup, 1=Record)"); - return PM3_EINVARG; - } - - if (res_data || dlength == 0) { - PrintAndLogEx(ERR, "Data needs some hex bytes to write"); - return PM3_EINVARG; - } - - if (res_offset || (offsetlength != 3 && offsetlength != 0)) { - PrintAndLogEx(ERR, "Offset needs 3 hex bytes"); - return PM3_EINVARG; - } - - if (fno > 0x1F) { - PrintAndLogEx(ERR, "File number range is invalid (exp 0 - 31), got %d", fno); - return PM3_EINVARG; - } - - mfdes_data_t ft; - - memcpy(ft.offset, offset, 3); - htole24(dlength, ft.length); - ft.fileno = fno; - - 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, fno, &cs) != PM3_SUCCESS) { - PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); - DropFieldDesfire(); - return PM3_ESOFT; - } - - int res = PM3_ESOFT; - ft.data = data; - res = handler_desfire_writedata(&ft, type, cs); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "Successfully wrote data"); - } else { - PrintAndLogEx(ERR, "Couldn't read data. Error %d", res); - } - DropFieldDesfire(); - return res; - */ } static int CmdHF14ADesTest(const char *Cmd) { @@ -6863,7 +6767,7 @@ static command_t CommandTable[] = { {"chfilesettings", CmdHF14ADesChFileSettings, IfPm3Iso14443a, "[new]Change file settings"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, {"read", CmdHF14ADesReadData, IfPm3Iso14443a, "[new]Read data from standard/backup/record/value/mac file"}, - {"write", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record/value file"}, + {"write", CmdHF14ADesWriteData, IfPm3Iso14443a, "[new]Write data to standard/backup/record/value file"}, {"value", CmdHF14ADesValueOperations, IfPm3Iso14443a, "[new]Operations with value file (get/credit/limited credit/debit/clear)"}, {"clearrecfile", CmdHF14ADesClearRecordFile, IfPm3Iso14443a, "[new]Clear record File"}, {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("System") " -----------------------"}, From a0118945427ec26191cd7d4dd5d289df715e326c Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 19:28:55 +0300 Subject: [PATCH 35/37] update help --- client/src/cmdhfmfdes.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 78c725152..e2e0c9746 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -6486,7 +6486,10 @@ static int CmdHF14ADesWriteData(const char *Cmd) { "hf mfdes write --aid 123456 --fid 01 --type data -d 01020304 --0ffset 000100 -> write data to std file with offset 0x100\n" "hf mfdes write --aid 123456 --fid 01 --type data -d 01020304 --commit -> write data to backup file with commit\n" "hf mfdes write --aid 123456 --fid 01 --type value -d 00000001 -> increment value file\n" - "hf mfdes write --aid 123456 --fid 01 --type value --debit -d 00000001 -> decrement value file\n" + "hf mfdes write --aid 123456 --fid 01 --type value -d 00000001 --debit -> decrement value file\n" + "hf mfdes write --aid 123456 --fid 01 -d 01020304 -> write data to record file with `auto` type\n" + "hf mfdes write --aid 123456 --fid 01 --type record -d 01020304 -> write data to record file\n" + "hf mfdes write --aid 123456 --fid 01 --type record -d 01020304 --updaterec 0 -> update record in the record file. record 0 - lastest record.\n" "hf mfdes write --aid 123456 --fid 01 --type record --offset 000000 -d 11223344 -> write record to record file. use default channel settings from `default` command"); void *argtable[] = { @@ -6508,7 +6511,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { arg_str0("o", "offset", "", "File Offset (3 hex bytes, big endian). For records - record number (0 - lastest record). Default 0"), arg_str0("d", "data", "", "data for write (data/record file), credit/debit(value file)"), arg_lit0(NULL, "debit", "use for value file debit operation instead of credit"), - arg_lit0(NULL, "commit", "commit needs for backup file only. For the other file types - command set it automatically."), + arg_lit0(NULL, "commit", "commit needs for backup file only. For the other file types and in the `auto` mode - command set it automatically."), arg_int0(NULL, "updaterec", "", "Record number for update record command. Updates record instead of write. Lastest record - 0"), arg_param_end }; From d9be538fa16e1a1bf7777b5294ba84500df259e8 Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 20:15:44 +0300 Subject: [PATCH 36/37] d40/encode works --- client/src/mifare/desfiresecurechan.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index fb51f9d92..4c0f8f7ec 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -142,9 +142,6 @@ static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) { } static void DesfireSecureChannelEncodeD40(DesfireContext *ctx, uint8_t cmd, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, size_t *dstdatalen) { - memcpy(dstdata, srcdata, srcdatalen); - *dstdatalen = srcdatalen; - uint8_t data[1024] = {0}; size_t rlen = 0; uint8_t hdrlen = DesfireGetCmdHeaderLen(cmd); @@ -152,6 +149,7 @@ static void DesfireSecureChannelEncodeD40(DesfireContext *ctx, uint8_t cmd, uint if (ctx->commMode == DCMMACed || (ctx->commMode == DCMEncrypted && srcdatalen <= hdrlen)) { if (srcdatalen == 0) return; +PrintAndLogEx(INFO, "---MAC"); rlen = srcdatalen + DesfireGetMACLength(ctx); memcpy(data, srcdata, srcdatalen); @@ -163,12 +161,14 @@ static void DesfireSecureChannelEncodeD40(DesfireContext *ctx, uint8_t cmd, uint if (srcdatalen == 0 || srcdatalen <= hdrlen) return; - rlen = padded_data_length(srcdatalen + 2, desfire_get_key_block_length(ctx->keyType)); // 2 - crc16 - memcpy(data, srcdata, srcdatalen); - compute_crc(CRC_14443_A, data, srcdatalen, &data[srcdatalen], &data[srcdatalen + 1]); - DesfireCryptoEncDec(ctx, true, data, rlen, dstdata, true); + rlen = padded_data_length(srcdatalen + 2 - hdrlen, desfire_get_key_block_length(ctx->keyType)) + hdrlen; // 2 - crc16 + memcpy(data, &srcdata[hdrlen], srcdatalen - hdrlen); + iso14443a_crc_append(data, srcdatalen - hdrlen); + memcpy(dstdata, srcdata, hdrlen); + //PrintAndLogEx(INFO, "src[%d]: %s", srcdatalen - hdrlen + 2, sprint_hex(data, srcdatalen - hdrlen + 2)); + DesfireCryptoEncDec(ctx, true, data, rlen - hdrlen, &dstdata[hdrlen], true); *dstdatalen = rlen; - } if (ctx->commMode == DCMEncryptedPlain) { + } else if (ctx->commMode == DCMEncryptedPlain) { if (srcdatalen == 0 || srcdatalen <= hdrlen) return; From 22e8ab89775494c9d0d2b39c9cbc98f0d10368ad Mon Sep 17 00:00:00 2001 From: merlokk <807634+merlokk@users.noreply.github.com> Date: Wed, 28 Jul 2021 20:25:35 +0300 Subject: [PATCH 37/37] d40/mac works --- client/src/mifare/desfiresecurechan.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 4c0f8f7ec..b6ac4a858 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -144,29 +144,39 @@ static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) { static void DesfireSecureChannelEncodeD40(DesfireContext *ctx, uint8_t cmd, uint8_t *srcdata, size_t srcdatalen, uint8_t *dstdata, size_t *dstdatalen) { uint8_t data[1024] = {0}; size_t rlen = 0; + + memcpy(dstdata, srcdata, srcdatalen); + *dstdatalen = srcdatalen; + uint8_t hdrlen = DesfireGetCmdHeaderLen(cmd); if (ctx->commMode == DCMMACed || (ctx->commMode == DCMEncrypted && srcdatalen <= hdrlen)) { if (srcdatalen == 0) return; -PrintAndLogEx(INFO, "---MAC"); rlen = srcdatalen + DesfireGetMACLength(ctx); - memcpy(data, srcdata, srcdatalen); - DesfireCryptoEncDec(ctx, true, data, srcdatalen, NULL, true); + + memcpy(data, &srcdata[hdrlen], srcdatalen - hdrlen); + size_t srcmaclen = padded_data_length(srcdatalen - hdrlen, desfire_get_key_block_length(ctx->keyType)); + + uint8_t mac[32] = {0}; + DesfireCryptoEncDecEx(ctx, true, data, srcmaclen, NULL, true, true, mac); + memcpy(dstdata, srcdata, srcdatalen); - memcpy(&dstdata[srcdatalen], ctx->IV, 4); + memcpy(&dstdata[srcdatalen], mac, DesfireGetMACLength(ctx)); *dstdatalen = rlen; } else if (ctx->commMode == DCMEncrypted) { - if (srcdatalen == 0 || srcdatalen <= hdrlen) + if (srcdatalen <= hdrlen) return; rlen = padded_data_length(srcdatalen + 2 - hdrlen, desfire_get_key_block_length(ctx->keyType)) + hdrlen; // 2 - crc16 memcpy(data, &srcdata[hdrlen], srcdatalen - hdrlen); iso14443a_crc_append(data, srcdatalen - hdrlen); + memcpy(dstdata, srcdata, hdrlen); //PrintAndLogEx(INFO, "src[%d]: %s", srcdatalen - hdrlen + 2, sprint_hex(data, srcdatalen - hdrlen + 2)); DesfireCryptoEncDec(ctx, true, data, rlen - hdrlen, &dstdata[hdrlen], true); + *dstdatalen = rlen; } else if (ctx->commMode == DCMEncryptedPlain) { if (srcdatalen == 0 || srcdatalen <= hdrlen) @@ -178,9 +188,6 @@ PrintAndLogEx(INFO, "---MAC"); DesfireCryptoEncDec(ctx, true, &data[hdrlen], rlen - hdrlen, &dstdata[hdrlen], true); *dstdatalen = rlen; ctx->commMode = DCMEncrypted; - } else { - memcpy(dstdata, srcdata, srcdatalen); - *dstdatalen = srcdatalen; } } @@ -190,6 +197,7 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint memcpy(dstdata, srcdata, srcdatalen); *dstdatalen = srcdatalen; + uint8_t hdrlen = DesfireGetCmdHeaderLen(cmd); // we calc MAC anyway @@ -217,7 +225,7 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint *dstdatalen = hdrlen + rlen; } else if (ctx->commMode == DCMEncryptedPlain) { - if (srcdatalen == 0 || srcdatalen <= hdrlen) + if (srcdatalen <= hdrlen) return; memcpy(dstdata, srcdata, hdrlen);