diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c5fe2360..ecc4c5173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Add `--wiegand/--fc/--cn` to `hf iclass encode` (@bettse) + - 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) 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/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 2689ea665..e2e0c9746 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,220 +2071,7 @@ static int selectfile(uint8_t *aid, uint8_t fileno, uint8_t *cs) { } *cs = filesettings[1]; 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; @@ -4125,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) @@ -4144,6 +3932,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) @@ -5538,7 +5327,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); @@ -6286,7 +6075,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; } @@ -6342,7 +6131,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; } @@ -6443,6 +6232,500 @@ 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. 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\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, + 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 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); + + 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; + } + } + + // length of record for record file + size_t reclen = 0; + + // 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; + break; + } + case 0x02: { + op = RFTValue; + break; + } + case 0x03: + case 0x04: { + op = RFTRecord; + reclen = fsettings.recordSize; + break; + } + case 0x05: { + op = RFTMAC; + 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."); + } + } + + 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 offset %u", resplen, fnum, offset); + print_buffer_with_offset(resp, resplen, offset, true); + } 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) { + 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", reccount - (i + offset + 1)); + 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) { + 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, true); + } 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(); + return PM3_SUCCESS; +} + +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 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 -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[] = { + 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 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 + }; + 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); + + int updaterecno = arg_get_int_def(ctx, 19, -1); + + 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 (verbose) + PrintAndLogEx(INFO, "Write data file %02x " _GREEN_("success"), fnum); + } + + if (op == RFTValue) { + 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; + 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 (verbose) + PrintAndLogEx(INFO, "%s value file %02x (%s) " _GREEN_("success"), (debit) ? "Debit" : "Credit", fnum, CLIGetOptionListStr(DesfireValueFileOperOpts, vop)); + commit = true; + } + + if (op == RFTRecord) { + if (updaterecno < 0) { + res = DesfireWriteRecord(&dctx, fnum, offset, datalen, data); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Desfire WriteRecord command " _RED_("error") ". Result: %d", res); + DropField(); + return PM3_ESOFT; + } + if (verbose) + PrintAndLogEx(INFO, "Write record file %02x " _GREEN_("success"), fnum); + } else { + 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; + } + + 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; +} + static int CmdHF14ADesTest(const char *Cmd) { DesfireTest(true); return PM3_SUCCESS; @@ -6486,8 +6769,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, "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, "[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") " -----------------------"}, 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; } diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index e21180957..befa56c6c 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) { @@ -1058,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) @@ -1087,8 +1106,27 @@ 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}; + uint8_t data[10] = {0}; data[0] = fid; size_t datalen = (operation == MFDES_GET_VALUE) ? 1 : 5; if (value) @@ -1104,6 +1142,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) { @@ -1298,6 +1365,67 @@ 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->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); + + int reclen = 0; + switch (fsettings->fileType) { + case 0x00: + case 0x01: { + fsettings->fileSize = MemLeToUint3byte(&data[4]); + reclen = 4 + 3; + break; + } + case 0x02: { + 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[4]); + fsettings->maxRecordCount = MemLeToUint3byte(&data[7]); + fsettings->curRecordCount = MemLeToUint3byte(&data[10]); + reclen = 4 + 9; + break; + } + case 0x05: { + fsettings->keyType = data[4]; + fsettings->keyVersion = data[5]; + 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: @@ -1450,7 +1578,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 14453993b..004a452f9 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -28,6 +28,52 @@ typedef struct { const bool mayHaveISOfid; } DesfireCreateFileCommandsS; +typedef struct { + // all + uint8_t fileType; + uint8_t fileOption; + uint8_t fileCommMode; + DesfireCommunicationMode commMode; + 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, + RFTValue, + RFTRecord, + RFTMAC, +} DesfireReadOpFileType; + extern const CLIParserOption DesfireAlgoOpts[]; extern const CLIParserOption DesfireKDFAlgoOpts[]; extern const CLIParserOption DesfireCommunicationModeOpts[]; @@ -35,6 +81,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); @@ -75,7 +122,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); @@ -96,4 +145,10 @@ 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); +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/desfirecrypto.c b/client/src/mifare/desfirecrypto.c index 79604f5eb..be98106a7 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) @@ -211,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); @@ -231,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; } @@ -247,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) { @@ -260,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; @@ -344,6 +348,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..fddef64c9 100644 --- a/client/src/mifare/desfirecrypto.h +++ b/client/src/mifare/desfirecrypto.h @@ -99,12 +99,15 @@ 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); 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); diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 85df23503..b6ac4a858 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -23,7 +23,23 @@ #include "protocols.h" #include "mifare/desfire_crypto.h" -AllowedChannelModesS AllowedChannelModes[] = { +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[] = { {MFDES_CREATE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_DELETE_APPLICATION, DACd40, DCCNative, DCMPlain}, {MFDES_GET_APPLICATION_IDS, DACd40, DCCNative, DCMPlain}, @@ -42,16 +58,15 @@ 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_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}, {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}, @@ -64,8 +79,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,14 +117,20 @@ 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}, {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}, + {MFDES_WRITE_DATA, 7}, + {MFDES_READ_RECORDS, 7}, + {MFDES_WRITE_RECORD, 7}, + {MFDES_UPDATE_RECORD, 10}, }; static uint8_t DesfireGetCmdHeaderLen(uint8_t cmd) { @@ -123,52 +142,52 @@ 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 data[1024] = {0}; - 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[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); - 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; + memcpy(dstdata, srcdata, srcdatalen); + memcpy(&dstdata[srcdatalen], mac, DesfireGetMACLength(ctx)); + *dstdatalen = rlen; + } else if (ctx->commMode == DCMEncrypted) { + if (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 + 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) + 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; } } @@ -178,11 +197,12 @@ static void DesfireSecureChannelEncodeEV1(DesfireContext *ctx, uint8_t cmd, uint memcpy(dstdata, srcdata, srcdatalen); *dstdatalen = srcdatalen; + uint8_t hdrlen = DesfireGetCmdHeaderLen(cmd); // 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}; @@ -190,7 +210,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); } @@ -205,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); @@ -219,7 +239,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: @@ -238,13 +258,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: - + 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); @@ -347,6 +385,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++) diff --git a/client/src/util.c b/client/src/util.c index ed6ca6e7c..7d2772794 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -249,6 +249,22 @@ 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, 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; + 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..67ce0faa8 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, 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); diff --git a/include/protocols.h b/include/protocols.h index efa3e0a78..168606498 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -435,9 +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 @@ -453,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