From 90525502f1ace61217104c9fc1dcbaca6fd9390d Mon Sep 17 00:00:00 2001 From: Daniel Underhay <27876907+dunderhay@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:01:32 +1000 Subject: [PATCH] Add DESFire reader candidate-key probe Add an opt-in simulator probe that checks a reader's AES authentication continuation against a supplied candidate and stops before the final card response. Expose the result through the firmware protocol and etest bench command, and document the evidence and handshake scope. Co-Authored-By: OpenAI Codex --- armsrc/appmain.c | 2 +- armsrc/desfiresim.c | 253 ++++++++++++++++++++++++++++++++++++++-- armsrc/desfiresim.h | 2 +- armsrc/iso14443a.c | 13 ++- armsrc/iso14443a.h | 1 + client/src/cmdhfmfdes.c | 148 +++++++++++++++++++---- doc/commands.json | 16 ++- doc/desfire.md | 18 +++ include/desfire.h | 49 ++++++++ 9 files changed, 460 insertions(+), 42 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 1678a10cb..9064831d1 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -2746,7 +2746,7 @@ static void PacketReceived(PacketCommandNG *packet) { } #ifdef WITH_DESFIRE_SIM case CMD_HF_DESFIRE_SIMULATE: { - SimulateDesfireTag(); + SimulateDesfireTag(packet); break; } #ifdef ENABLE_HFMFDESETEST diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c index bbe3304aa..6979451c4 100644 --- a/armsrc/desfiresim.c +++ b/armsrc/desfiresim.c @@ -144,6 +144,29 @@ typedef struct { static desfire_sim_state_t s_st; static bool s_ready = false; +typedef struct { + bool enabled; + bool done; + desfire_sim_probe_cmd_t config; + desfire_sim_probe_result_t result; +} desfire_sim_probe_state_t; + +static desfire_sim_probe_state_t g_desfire_probe; + +static void desfire_sim_probe_configure(const desfire_sim_probe_cmd_t *config) { + memset(&g_desfire_probe, 0, sizeof(g_desfire_probe)); + if (config == NULL) { + return; + } + g_desfire_probe.enabled = true; + g_desfire_probe.config = *config; + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_DISCOVERY_FAILED; + memcpy(g_desfire_probe.result.aid, config->aid, sizeof(config->aid)); + g_desfire_probe.result.keyno = config->keyno; + g_desfire_probe.result.algorithm = config->algorithm; + g_desfire_probe.result.candidate_id = config->candidate_id; +} + // ---------------------------------------------------------------- image walk static bool desfire_sim_load(desfire_sim_state_t *st) { @@ -201,6 +224,30 @@ static int desfire_sim_find_app(const desfire_sim_state_t *st, uint32_t aid) { return -1; } +static bool desfire_sim_probe_target_selected(const desfire_sim_state_t *st) { + return g_desfire_probe.enabled + && st->selected >= 0 + && memcmp(st->apps[st->selected].aid, g_desfire_probe.config.aid, 3) == 0; +} + +static bool desfire_sim_probe_discovery_selected(const desfire_sim_state_t *st) { + static const uint8_t empty_aid[3] = {0}; + return g_desfire_probe.enabled + && st->selected >= 0 + && memcmp(g_desfire_probe.config.discovery_aid, empty_aid, 3) != 0 + && memcmp(st->apps[st->selected].aid, g_desfire_probe.config.discovery_aid, 3) == 0; +} + +static void desfire_sim_probe_mark_selected(const desfire_sim_state_t *st) { + if (desfire_sim_probe_discovery_selected(st)) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_DISCOVERY_SELECTED; + } + if (desfire_sim_probe_target_selected(st)) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_SELECTED; + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_NO_RESPONSE; + } +} + // --------------------------------------------------------------- the answers // Build one DESFire answer: a status byte and optional payload. Returns the @@ -453,6 +500,27 @@ static void desfire_sim_auth_clear(desfire_sim_state_t *st) { static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, const uint8_t *in, uint16_t inlen, uint8_t *out) { + bool probe_target = desfire_sim_probe_target_selected(st); + if (probe_target) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_AUTH_REQUEST; + g_desfire_probe.result.last_command = cmd; + g_desfire_probe.result.keyno = inlen ? (in[0] & 0x0F) : DESFIRE_SIM_PROBE_KEY_ANY; + if (g_desfire_probe.result.flags & DESFIRE_SIM_PROBE_CHALLENGE) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_NO_RESPONSE; + g_desfire_probe.done = true; // never reuse the host nonce for a second target challenge + return 0; + } + if (inlen < 1 + || (g_desfire_probe.config.keyno != DESFIRE_SIM_PROBE_KEY_ANY + && g_desfire_probe.result.keyno != g_desfire_probe.config.keyno) + || cmd != MFDES_AUTHENTICATE_AES + || g_desfire_probe.config.algorithm != T_AES) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.done = true; + return 0; + } + } + if (inlen < 1) { return desfire_sim_status(out, MFDES_E_LENGTH); } @@ -461,17 +529,33 @@ static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, const desfire_em_app_t *app = &st->apps[st->selected]; if (keyno >= (app->numkeysraw & 0x0F) && keyno != 0) { + if (probe_target) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.done = true; + return 0; + } return desfire_sim_status(out, MFDES_E_NO_SUCH_KEY); } const desfire_em_key_t *k = desfire_sim_find_key(st, st->selected, keyno); if (k == NULL) { + if (probe_target) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.done = true; + return 0; + } // we do not hold this key, so we cannot play the other half if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("DESFire sim: no key %u for app index %d in the image", keyno, st->selected); } return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); } + if (g_desfire_probe.enabled && probe_target == false) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.result.last_command = cmd; + g_desfire_probe.done = true; // no preliminary application may complete authentication + return 0; + } // the command has to match the application's key algorithm uint8_t algo = app->keytype; @@ -479,6 +563,11 @@ static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, (cmd == MFDES_AUTHENTICATE_ISO && (algo == T_DES || algo == T_3DES || algo == T_3K3DES)) || (cmd == MFDES_AUTHENTICATE_AES && algo == T_AES)); if (ok == false) { + if (probe_target) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.done = true; + return 0; + } return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); } @@ -486,7 +575,9 @@ static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, desfire_sim_make_key(&st->authkey, algo, k->key); st->rndlen = desfire_sim_rndlen(algo); - if (desfire_sim_random(st->rndb, st->rndlen) == false) { + if (probe_target) { + memcpy(st->rndb, g_desfire_probe.config.rndb, st->rndlen); + } else if (desfire_sim_random(st->rndb, st->rndlen) == false) { memcpy(st->rndb, s_sim_rndb, st->rndlen); } @@ -502,6 +593,12 @@ static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, st->auth_cmd = cmd; st->auth_keynum = keyno; + if (probe_target) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_CHALLENGE; + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_NO_RESPONSE; + g_desfire_probe.result.challenge_ms = GetTickCount(); + memcpy(g_desfire_probe.result.rndb, st->rndb, st->rndlen); + } return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, encrndb, st->rndlen); } @@ -510,8 +607,21 @@ static uint16_t desfire_sim_auth_start(desfire_sim_state_t *st, uint8_t cmd, static uint16_t desfire_sim_auth_finish(desfire_sim_state_t *st, const uint8_t *in, uint16_t inlen, uint8_t *out) { uint16_t want = st->rndlen * 2; + bool probe_target = desfire_sim_probe_target_selected(st); + if (probe_target) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_CONTINUATION; + g_desfire_probe.result.continuation_ms = GetTickCount(); + g_desfire_probe.result.continuation_len = MIN(inlen, sizeof(g_desfire_probe.result.continuation)); + memcpy(g_desfire_probe.result.continuation, in, g_desfire_probe.result.continuation_len); + g_desfire_probe.result.last_command = MFDES_ADDITIONAL_FRAME; + } if (inlen < want) { desfire_sim_auth_clear(st); + if (probe_target) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_NO_MATCH; + g_desfire_probe.done = true; + return 0; + } return desfire_sim_status(out, MFDES_E_LENGTH); } @@ -521,6 +631,9 @@ static uint16_t desfire_sim_auth_finish(desfire_sim_state_t *st, const uint8_t * } else { desfire_sim_crypt(&st->authkey, in, both, want, st->iv, false); } + if (probe_target) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_DECRYPTED; + } const uint8_t *rnda = both; const uint8_t *rndbprime = both + st->rndlen; @@ -532,9 +645,22 @@ static uint16_t desfire_sim_auth_finish(desfire_sim_state_t *st, const uint8_t * if (memcmp(expect, rndbprime, st->rndlen) != 0) { // the reader does not hold the key desfire_sim_auth_clear(st); + if (probe_target) { + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_NO_MATCH; + g_desfire_probe.done = true; + return 0; + } return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); } + if (probe_target) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_RNDB_MATCH; + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_MATCH; + g_desfire_probe.done = true; + desfire_sim_auth_clear(st); + return 0; // no final E(RndA') goes over the air + } + uint8_t rndaprime[16] = {0}; memcpy(rndaprime, rnda, st->rndlen); desfire_sim_rol(rndaprime, st->rndlen); @@ -2137,6 +2263,17 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const const desfire_em_hdr_t *hdr = st->hdr; + if (g_desfire_probe.enabled + && desfire_sim_probe_target_selected(st) + && (cmd == MFDES_AUTHENTICATE_EV2F || cmd == MFDES_AUTHENTICATE_EV2NF)) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_AUTH_REQUEST; + g_desfire_probe.result.last_command = cmd; + g_desfire_probe.result.keyno = inlen ? (in[0] & 0x0F) : DESFIRE_SIM_PROBE_KEY_ANY; + g_desfire_probe.result.outcome = DESFIRE_SIM_PROBE_UNSUPPORTED; + g_desfire_probe.done = true; + return 0; + } + // an additional frame only means anything while a command is being chained, // a write is being gathered, or an authentication is half done if (cmd == MFDES_ADDITIONAL_FRAME && st->chain_cmd == 0 && st->auth_cmd == 0 && st->wcmd == 0) { @@ -2326,6 +2463,7 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const } st->selected = idx; + desfire_sim_probe_mark_selected(st); // "each SelectApplication command invalidates the current // authentication status" -- M134034 9.4.5 @@ -2601,7 +2739,14 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const uint32_t off = in[1] | (in[2] << 8) | (in[3] << 16); uint32_t len = in[4] | (in[5] << 8) | (in[6] << 16); - return desfire_sim_read_start(st, f, off, len, 1, f->u.data.size, comm, out); + uint16_t response_len = desfire_sim_read_start(st, f, off, len, 1, f->u.data.size, comm, out); + if (desfire_sim_probe_discovery_selected(st) + && in[0] == g_desfire_probe.config.discovery_file + && response_len > 1 + && (out[0] == MFDES_S_OPERATION_OK || out[0] == MFDES_ADDITIONAL_FRAME)) { + g_desfire_probe.result.flags |= DESFIRE_SIM_PROBE_DISCOVERY_READ; + } + return response_len; } case MFDES_READ_RECORDS: @@ -3543,6 +3688,7 @@ static uint16_t desfire_sim_iso7816(desfire_sim_state_t *st, const uint8_t *in, // selecting an application this way ends the session like SelectApplication does st->selected = idx; + desfire_sim_probe_mark_selected(st); desfire_sim_auth_clear(st); return desfire_sim_sw(out, ISO7816_SW_OK); } @@ -3655,7 +3801,25 @@ typedef enum { // enough for a 2 byte ATQA: 9 bytes of modulation per byte, plus framing #define ATQA_MODULATION_BUFFER_SIZE 32 -void SimulateDesfireTag(void) { +void SimulateDesfireTag(PacketCommandNG *packet) { + + const desfire_sim_probe_cmd_t *probe = NULL; + if (packet->length != 0) { + if (packet->ng == false || packet->length != sizeof(desfire_sim_probe_cmd_t)) { + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + probe = (const desfire_sim_probe_cmd_t *)packet->data.asBytes; + if (probe->algorithm != T_AES + || probe->overall_timeout_ms < 1000 || probe->overall_timeout_ms > 60000 + || probe->continuation_timeout_ms < 100 + || probe->continuation_timeout_ms > probe->overall_timeout_ms + || (probe->keyno >= DESFIRE_MAX_KEY_COUNT && probe->keyno != DESFIRE_SIM_PROBE_KEY_ANY)) { + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + } + desfire_sim_probe_configure(probe); //------------------------------------------------------------------------- // Get the bitstream in place before anything is allocated. iso14443a_setup() @@ -3777,6 +3941,7 @@ void SimulateDesfireTag(void) { int retval = PM3_SUCCESS; uint32_t cmdcount = 0; + uint32_t probe_started = GetTickCount(); // Field state. A DESFire is passively powered, so when the field goes away // it loses the selected application, the authentication and anything a @@ -3795,13 +3960,25 @@ void SimulateDesfireTag(void) { WDT_HIT(); - // Watch for the client asking us to stop, in this loop rather than - // relying on the one inside EmGetCmd(). With no field EmGetCmd() - // returns "field off" after 4 ms, which is long before its own check - // fires at 3 * 4000 iterations -- so a simulation sitting in front of - // no reader would never see CMD_BREAK_LOOP, and the device would stay - // in this loop after the client had gone. Same shape as Mifare1ksim. - if (idle_counter >= 1000) { + uint32_t wait_ms = 0; + if (g_desfire_probe.enabled) { + uint32_t elapsed = GetTickCountDelta(probe_started); + if (elapsed >= g_desfire_probe.config.overall_timeout_ms) { + break; + } + wait_ms = g_desfire_probe.config.overall_timeout_ms - elapsed; + if (g_desfire_probe.result.flags & DESFIRE_SIM_PROBE_CHALLENGE) { + elapsed = GetTickCountDelta(g_desfire_probe.result.challenge_ms); + if (elapsed >= g_desfire_probe.config.continuation_timeout_ms) { + break; + } + wait_ms = MIN(wait_ms, g_desfire_probe.config.continuation_timeout_ms - elapsed); + } + } + + // With no field EmGetCmd() returns before its host-stop check. + // Probe cancellation must be checked on every field-off pass. + if ((g_desfire_probe.enabled && !field_on) || idle_counter >= 1000) { idle_counter = 0; if (data_available()) { retval = PM3_EOPABORTED; @@ -3817,10 +3994,17 @@ void SimulateDesfireTag(void) { } uint16_t len = 0; - int res = EmGetCmd(receivedCmd, sizeof(receivedCmd), &len, receivedCmdPar); + int res = EmGetCmdTimeout(receivedCmd, sizeof(receivedCmd), &len, receivedCmdPar, wait_ms); + + if (res == 3) { + break; + } if (res == 2) { // the reader took its field away, so the PICC lost power + if (g_desfire_probe.enabled && (g_desfire_probe.result.flags & DESFIRE_SIM_PROBE_CHALLENGE)) { + break; + } if (field_on) { field_on = false; pstate = DESF_NOFIELD; @@ -4020,6 +4204,14 @@ void SimulateDesfireTag(void) { picc_block ^= 1; uint16_t n = desfire_sim_apdu(receivedCmd + prologue, len - prologue - 2, answer + prologue); + if (g_desfire_probe.done) { + const tUart14a *uart = GetUart14a(); + LogTrace(receivedCmd, len, + uart->startTime * 16 - DELAY_AIR2ARM_AS_TAG, + uart->endTime * 16 - DELAY_AIR2ARM_AS_TAG, + receivedCmdPar, true); + break; // the final card authentication response is never transmitted + } if (n == 0) { continue; } @@ -4056,7 +4248,12 @@ void SimulateDesfireTag(void) { set_tracing(false); BigBuf_free_keep_EM(); - reply_ng(CMD_HF_DESFIRE_SIMULATE, retval, NULL, 0); + if (g_desfire_probe.enabled && retval == PM3_SUCCESS) { + reply_ng(CMD_HF_DESFIRE_SIMULATE, retval, + (uint8_t *)&g_desfire_probe.result, sizeof(g_desfire_probe.result)); + } else { + reply_ng(CMD_HF_DESFIRE_SIMULATE, retval, NULL, 0); + } } //------------------------------------------------------- host driven simulation @@ -4091,12 +4288,14 @@ void DesfireSimTest(PacketCommandNG *packet) { // check the image is there, then wait for SCAN like a card waits for a field case DESFIRE_SIM_TEST_BEGIN: desfire_sim_random_clear(); + desfire_sim_probe_configure(NULL); status = desfire_sim_init() ? PM3_SUCCESS : PM3_ENODATA; s_ready = false; break; case DESFIRE_SIM_TEST_END: desfire_sim_random_clear(); + desfire_sim_probe_configure(NULL); memset(&s_st, 0, sizeof(s_st)); s_ready = false; status = PM3_SUCCESS; @@ -4128,6 +4327,10 @@ void DesfireSimTest(PacketCommandNG *packet) { if (s_ready == false || p->len == 0) { break; } + if (g_desfire_probe.done) { + status = PM3_SUCCESS; + break; // RF probe has exited; no later APDU can receive a card answer + } n = desfire_sim_apdu(p->data, p->len, out); data = out; status = PM3_SUCCESS; @@ -4153,6 +4356,32 @@ void DesfireSimTest(PacketCommandNG *packet) { status = PM3_SUCCESS; break; + case DESFIRE_SIM_TEST_PROBE_CONFIG: { + if (p->len != sizeof(desfire_sim_probe_cmd_t)) { + break; + } + const desfire_sim_probe_cmd_t *config = (const desfire_sim_probe_cmd_t *)p->data; + if (config->algorithm != T_AES + || config->overall_timeout_ms < 1000 || config->overall_timeout_ms > 60000 + || config->continuation_timeout_ms < 100 + || config->continuation_timeout_ms > config->overall_timeout_ms + || (config->keyno >= DESFIRE_MAX_KEY_COUNT && config->keyno != DESFIRE_SIM_PROBE_KEY_ANY)) { + break; + } + desfire_sim_probe_configure(config); + status = PM3_SUCCESS; + break; + } + + case DESFIRE_SIM_TEST_PROBE_RESULT: + if (g_desfire_probe.enabled == false) { + break; + } + data = (uint8_t *)&g_desfire_probe.result; + n = sizeof(g_desfire_probe.result); + status = PM3_SUCCESS; + break; + default: break; } diff --git a/armsrc/desfiresim.h b/armsrc/desfiresim.h index 704f719e4..de63b5e9d 100644 --- a/armsrc/desfiresim.h +++ b/armsrc/desfiresim.h @@ -33,7 +33,7 @@ // than hooking into SimulateIso14443aTag(), which is busy enough already. // Runs until the button is pressed or the client breaks the loop, and answers // on CMD_HF_DESFIRE_SIMULATE. -void SimulateDesfireTag(void); +void SimulateDesfireTag(PacketCommandNG *packet); // Drive the same simulation from the host, one operation per packet and no // RF: the command bytes arrive over USB and the answer goes back the same way. diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index c89130d95..661a1d9fe 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2840,12 +2840,14 @@ static void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uin */ //----------------------------------------------------------------------------- // Wait for commands from reader -// Stop when button is pressed (return 1) or field was gone (return 2) +// Stop when button is pressed (return 1), field was gone (return 2), +// or an optional timeout expires (return 3) // Or return 0 when command is captured //----------------------------------------------------------------------------- -int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_t *par) { +int EmGetCmdTimeout(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_t *par, uint32_t timeout_ms) { *len = 0; + uint32_t started = timeout_ms ? GetTickCount() : 0; uint32_t timer = 0; int analogCnt = 0; int analogAVG = 0; @@ -2891,6 +2893,9 @@ int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_ if (Uart.state == STATE_14A_UNSYNCD) { usb_check(); } + if (timeout_ms && GetTickCountDelta(started) >= timeout_ms) { + return 3; + } flip++; checker = 4000; @@ -2937,6 +2942,10 @@ int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_ } } +int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_t *par) { + return EmGetCmdTimeout(received, received_max_len, len, par, 0); +} + int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { volatile uint8_t b; uint16_t i = 0; diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index faa467b11..135c4836b 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -193,6 +193,7 @@ int EmSend4bit(uint8_t resp); int EmSendCmd(uint8_t *resp, uint16_t respLen); int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool collision); int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_t *par); +int EmGetCmdTimeout(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_t *par, uint32_t timeout_ms); int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par); int EmSendCmdParEx(uint8_t *resp, uint16_t respLen, uint8_t *par, bool collision); int EmSendPrecompiledCmd(tag_response_info_t *p_response); diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 0bfb76fb9..d291b7ee0 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -9216,6 +9216,9 @@ static void DesfireViewPrintApp(const desfire_dump_app_t *app) { } } +static int desfire_etest_probe_result(const PacketResponseNG *resp, bool json, + char *fields, size_t fields_len); + static int CmdHF14ADesSim(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes sim", @@ -9223,45 +9226,73 @@ static int CmdHF14ADesSim(const char *Cmd) { "Load one first with `hf mfdes eload`, and read back what a reader\n" "changed with `hf mfdes esave`.\n" "\n" - "UID, ATQA, SAK and ATS all come out of the loaded image", - "hf mfdes sim"); + "UID, ATQA, SAK and ATS all come out of the loaded image.\n" + "--probe tests a reader with a candidate AES key in the loaded image;\n" + "supply a fresh nonce for each live run.", + "hf mfdes sim\n" + "hf mfdes sim --probe <33-byte-payload>"); void *argtable[] = { arg_param_begin, + arg_str0(NULL, "probe", "", "Candidate-key probe payload (33 bytes)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIExecWithReturn(ctx, Cmd, argtable, false); + bool has_probe = arg_get_str(ctx, 1)->count > 0; + uint8_t probe[sizeof(desfire_sim_probe_cmd_t)] = {0}; + int probe_len = 0; + if (CLIParamHexToBuf(arg_get_str(ctx, 1), probe, sizeof(probe), &probe_len)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } CLIParserFree(ctx); + if (has_probe && probe_len != sizeof(probe)) { + PrintAndLogEx(WARNING, "Probe payload must be %zu bytes", sizeof(probe)); + return PM3_EINVARG; + } + clearCommandBuffer(); - SendCommandNG(CMD_HF_DESFIRE_SIMULATE, NULL, 0); + SendCommandNG(CMD_HF_DESFIRE_SIMULATE, has_probe ? probe : NULL, has_probe ? probe_len : 0); PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort simulation"); PacketResponseNG resp; - bool keypress = kbd_enter_pressed(); - while (keypress == false) { - - keypress = kbd_enter_pressed(); - - if (WaitForResponseTimeout(CMD_HF_DESFIRE_SIMULATE, &resp, 1500) == false) { + bool stop_requested = false; + for (;;) { + if (stop_requested == false && kbd_enter_pressed()) { + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + stop_requested = true; + } + if (WaitForResponseTimeout(CMD_HF_DESFIRE_SIMULATE, &resp, stop_requested ? 3000 : 1500) == false) { + if (stop_requested) { + PrintAndLogEx(WARNING, "No simulation stop response"); + return PM3_ETIMEOUT; + } continue; } if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Simulation stopped, no card image in emulator memory?"); - PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); + PrintAndLogEx(WARNING, "Simulation stopped (status %d)", resp.status); + if (resp.status == PM3_EINVARG) { + PrintAndLogEx(HINT, "Hint: check the card image and probe payload"); + } return resp.status; } + if (has_probe) { + int res = desfire_etest_probe_result(&resp, false, NULL, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Probe result missing or invalid"); + return res; + } + } break; } - if (keypress) { - SendCommandNG(CMD_BREAK_LOOP, NULL, 0); - } - PrintAndLogEx(INFO, "Done!"); - PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes esave`") " to see what a reader changed"); + if (has_probe == false) { + PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`hf mfdes esave`") " to see what a reader changed"); + } return PM3_SUCCESS; } @@ -9300,6 +9331,50 @@ static void desfire_etest_hex(char *dst, size_t dstlen, const uint8_t *src, size dst[2 * i] = 0; } +static int desfire_etest_probe_result(const PacketResponseNG *resp, bool json, + char *fields, size_t fields_len) { + if (resp->length != sizeof(desfire_sim_probe_result_t)) { + return PM3_EFAILED; + } + + desfire_sim_probe_result_t result; + memcpy(&result, resp->data.asBytes, sizeof(result)); + if (result.outcome > DESFIRE_SIM_PROBE_UNSUPPORTED + || result.continuation_len > sizeof(result.continuation)) { + return PM3_EFAILED; + } + static const char *outcome_names[] = { + "discovery failed", "no response", "no match", "match", "unsupported authentication" + }; + char rndb[33] = {0}; + char continuation[65] = {0}; + desfire_etest_hex(rndb, sizeof(rndb), result.rndb, sizeof(result.rndb)); + desfire_etest_hex(continuation, sizeof(continuation), result.continuation, + MIN(result.continuation_len, sizeof(result.continuation))); + if (json) { + snprintf(fields, fields_len, + ",\"outcome\":%u,\"flags\":%u,\"aid\":\"%02X%02X%02X\",\"keyno\":%u," + "\"candidate_id\":%" PRIu32 ",\"rndb\":\"%s\",\"continuation\":\"%s\"", + result.outcome, result.flags, result.aid[2], result.aid[1], result.aid[0], + result.keyno, result.candidate_id, rndb, continuation); + } else { + PrintAndLogEx(SUCCESS, "Probe outcome..... %s (%u)", outcome_names[result.outcome], result.outcome); + PrintAndLogEx(SUCCESS, "Evidence flags..... 0x%02X", result.flags); + PrintAndLogEx(SUCCESS, "AID/key............ %02X%02X%02X / %u", + result.aid[2], result.aid[1], result.aid[0], result.keyno); + PrintAndLogEx(SUCCESS, "Candidate ID....... %" PRIu32, result.candidate_id); + PrintAndLogEx(SUCCESS, "CAD selected/read.. %s / %s", + result.flags & DESFIRE_SIM_PROBE_DISCOVERY_SELECTED ? "yes" : "no", + result.flags & DESFIRE_SIM_PROBE_DISCOVERY_READ ? "yes" : "no"); + PrintAndLogEx(SUCCESS, "RndB............... %s", rndb); + PrintAndLogEx(SUCCESS, "Reader continuation %s", continuation); + PrintAndLogEx(SUCCESS, "Challenge/reader ms %" PRIu32 " / %" PRIu32, + result.challenge_ms, result.continuation_ms); + PrintAndLogEx(SUCCESS, "Last command....... 0x%02X", result.last_command); + } + return PM3_SUCCESS; +} + static int CmdHF14ADesETest(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes etest", @@ -9314,6 +9389,8 @@ static int CmdHF14ADesETest(const char *Cmd) { "hf mfdes etest --scan\n" "hf mfdes etest --random 0102030405060708\n" "hf mfdes etest --apdu 900A0000010000 -j\n" + "hf mfdes etest --probe F48120FF03010000000102030405060708090A0B0C0D0E0F10F4812F0030758813\n" + "hf mfdes etest --probe-result -j\n" "hf mfdes etest --state -j\n" "hf mfdes etest --end"); @@ -9326,6 +9403,8 @@ static int CmdHF14ADesETest(const char *Cmd) { arg_str0(NULL, "random", "", "Queue bytes for the next RndB / random UID draws"), arg_lit0(NULL, "fieldoff", "RF reset, session dropped"), arg_lit0(NULL, "state", "Show session and random queue state"), + arg_str0(NULL, "probe", "", "Configure a 33-byte candidate-key probe payload"), + arg_lit0(NULL, "probe-result", "Read probe evidence and outcome"), arg_lit0("j", "json", "One line of JSON instead of text"), arg_param_end }; @@ -9338,7 +9417,9 @@ static int CmdHF14ADesETest(const char *Cmd) { bool has_random = (arg_get_str(ctx, 5)->count > 0); bool fieldoff = arg_get_lit(ctx, 6); bool state = arg_get_lit(ctx, 7); - bool json = arg_get_lit(ctx, 8); + bool has_probe = (arg_get_str(ctx, 8)->count > 0); + bool probe_result = arg_get_lit(ctx, 9); + bool json = arg_get_lit(ctx, 10); int apdulen = 0; uint8_t apdu[PM3_CMD_DATA_SIZE - sizeof(desfire_sim_test_cmd_t)] = {0}; @@ -9353,9 +9434,15 @@ static int CmdHF14ADesETest(const char *Cmd) { CLIParserFree(ctx); return PM3_EINVARG; } + int probe_len = 0; + uint8_t probe[sizeof(desfire_sim_probe_cmd_t)] = {0}; + if (CLIParamHexToBuf(arg_get_str(ctx, 8), probe, sizeof(probe), &probe_len)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } CLIParserFree(ctx); - if (begin + end + scan + has_apdu + has_random + fieldoff + state != 1) { + if (begin + end + scan + has_apdu + has_random + fieldoff + state + has_probe + probe_result != 1) { PrintAndLogEx(WARNING, "Give exactly one action"); return PM3_EINVARG; } @@ -9364,6 +9451,10 @@ static int CmdHF14ADesETest(const char *Cmd) { PrintAndLogEx(WARNING, "Need at least one byte"); return PM3_EINVARG; } + if (has_probe && probe_len != sizeof(desfire_sim_probe_cmd_t)) { + PrintAndLogEx(WARNING, "Probe configuration must be %zu bytes", sizeof(desfire_sim_probe_cmd_t)); + return PM3_EINVARG; + } uint8_t op; const char *name; @@ -9392,6 +9483,14 @@ static int CmdHF14ADesETest(const char *Cmd) { } else if (fieldoff) { op = DESFIRE_SIM_TEST_FIELDOFF; name = "fieldoff"; + } else if (has_probe) { + op = DESFIRE_SIM_TEST_PROBE_CONFIG; + name = "probe"; + data = probe; + len = probe_len; + } else if (probe_result) { + op = DESFIRE_SIM_TEST_PROBE_RESULT; + name = "probe-result"; } else { op = DESFIRE_SIM_TEST_STATE; name = "state"; @@ -9466,6 +9565,10 @@ static int CmdHF14ADesETest(const char *Cmd) { } } + if (res == PM3_SUCCESS && op == DESFIRE_SIM_TEST_PROBE_RESULT) { + res = desfire_etest_probe_result(&resp, json, fields, sizeof(fields)); + } + if (res != PM3_SUCCESS) { const char *why; switch (res) { @@ -9497,8 +9600,11 @@ static int CmdHF14ADesETest(const char *Cmd) { return res; } - bool plain_ack = (op == DESFIRE_SIM_TEST_BEGIN || op == DESFIRE_SIM_TEST_END || - op == DESFIRE_SIM_TEST_RANDOM || op == DESFIRE_SIM_TEST_FIELDOFF); + bool plain_ack = (op == DESFIRE_SIM_TEST_BEGIN + || op == DESFIRE_SIM_TEST_END + || op == DESFIRE_SIM_TEST_RANDOM + || op == DESFIRE_SIM_TEST_FIELDOFF + || op == DESFIRE_SIM_TEST_PROBE_CONFIG); if (json) { PrintAndLogEx(NORMAL, "{\"command\":\"%s\",\"ok\":true%s}", name, fields); } else if (plain_ack) { diff --git a/doc/commands.json b/doc/commands.json index 7aadd9acc..5c19243a3 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -7921,6 +7921,8 @@ "hf mfdes etest --scan", "hf mfdes etest --random 0102030405060708", "hf mfdes etest --apdu 900A0000010000 -j", + "hf mfdes etest --probe F48120FF03010000000102030405060708090A0B0C0D0E0F10F4812F0030758813", + "hf mfdes etest --probe-result -j", "hf mfdes etest --state -j", "hf mfdes etest --end" ], @@ -7934,9 +7936,11 @@ "--random Queue bytes for the next RndB / random UID draws", "--fieldoff RF reset, session dropped", "--state Show session and random queue state", + "--probe Configure a 33-byte candidate-key probe payload", + "--probe-result Read probe evidence and outcome", "-j, --json One line of JSON instead of text" ], - "usage": "hf mfdes etest [-hj] [--begin] [--end] [--scan] [--apdu ] [--random ] [--fieldoff] [--state]" + "usage": "hf mfdes etest [-hj] [--begin] [--end] [--scan] [--apdu ] [--random ] [--fieldoff] [--state] [--probe ] [--probe-result]" }, "hf mfdes eview": { "command": "hf mfdes eview", @@ -8591,15 +8595,17 @@ }, "hf mfdes sim": { "command": "hf mfdes sim", - "description": "Simulate the DESFire card image currently in emulator memory. Load one first with `hf mfdes eload`, and read back what a reader changed with `hf mfdes esave`. UID, ATQA, SAK and ATS all come out of the loaded image", + "description": "Simulate the DESFire card image currently in emulator memory. Load one first with `hf mfdes eload`, and read back what a reader changed with `hf mfdes esave`. UID, ATQA, SAK and ATS all come out of the loaded image. --probe tests a reader with a candidate AES key in the loaded image; supply a fresh nonce for each live run.", "notes": [ - "hf mfdes sim" + "hf mfdes sim", + "hf mfdes sim --probe <33-byte-payload>" ], "offline": false, "options": [ - "-h, --help This help" + "-h, --help This help", + "--probe Candidate-key probe payload (33 bytes)" ], - "usage": "hf mfdes sim [-h]" + "usage": "hf mfdes sim [-h] [--probe ]" }, "hf mfdes test": { "command": "hf mfdes test", diff --git a/doc/desfire.md b/doc/desfire.md index 9aadaf70b..4d8b1b3cf 100644 --- a/doc/desfire.md +++ b/doc/desfire.md @@ -27,6 +27,7 @@ - [How to work with transaction mac](#how-to-work-with-transaction-mac) - [How to switch DESFire Light to LRP mode](#how-to-switch-desfire-light-to-lrp-mode) - [How to drive the simulation from the host](#how-to-drive-the-simulation-from-the-host) + - [How to test a reader with a candidate AES key](#how-to-test-a-reader-with-a-candidate-aes-key) ## Documentation @@ -609,3 +610,20 @@ The simulation normally uses a fixed RndB and a tick-derived random UID. Queued ``` {"command":"apdu","ok":true,"data":"DF6AB29AAE46BA2791AF"} ``` + +### How to test a reader with a candidate AES key +^[Top](#top) + +The optional DESFire simulator probe tests whether a **reader** can continue an AES authentication using a candidate key already loaded in a synthetic card image. It does not derive a key, extract one from the reader, or test a physical access card. The caller supplies the image, target AID, key choice, candidate identifier, and a fresh 16-byte RndB. Key preparation, any discovery data, and interpretation of the observation belong to the calling workflow. + +An empty `CMD_HF_DESFIRE_SIMULATE` payload retains normal simulation. A probe payload enables the bounded probe; its packed request and result layouts, flags, and numeric outcomes are defined in `include/desfire.h`. Key number `FF` accepts the number requested by the reader, provided that key exists in the image. The optional discovery AID and file number record whether the reader selected and read a routing file before selecting the target application. The payload also sets an overall timeout (1–60 seconds) and a post-challenge timeout (100 ms up to the overall timeout). Both limits apply while the reader field stays on but sends no frames. With no reader field, a host stop request is checked on each field-off pass rather than waiting for the overall timeout. + +When the reader sends `AuthenticateAES`, the simulator encrypts the supplied RndB with the image key and transmits that challenge. It then records and decrypts the reader's 32-byte continuation and checks the returned one-byte rotation of RndB. `MATCH=3` means that continuation matched for this AID, key number, candidate image, and exchange. Results also distinguish discovery failure (`0`), no response (`1`), no match (`2`), and unsupported authentication (`4`). The probe ends after one target challenge or a timeout, so a host nonce is not reused for another target attempt. + +The probe does not complete authentication outside the target application. If a reader starts authentication with a key present in the image at PICC level or in another application, the result is `UNSUPPORTED=4`; this does not establish whether the reader would later use the target key. A request for an unavailable key may instead receive a key error and leave the probe running (the synthetic fixture's CAD key-2 request returns `40`). A reader that never reaches the target application before the overall timeout produces `DISCOVERY_FAILED=0`. + +The probe stops after the reader's response in the three-way AES authentication handshake: the simulator sends its challenge and checks the reader's continuation, then withholds the final card response. That is enough to test whether the reader used the candidate key, without completing mutual authentication or testing an access decision. It is not a speed optimization or a firmware key-search loop. The structured result stores RndB and the raw reader continuation, but not the encrypted challenge. The challenge can be checked in the RF trace or reconstructed from the image key and RndB. The terminal reader frame is logged explicitly because no final card answer triggers the simulator's usual request-and-answer trace logging. + +For a live reader check, load a synthetic image with `hf mfdes eload`, then run `hf mfdes sim --probe <33-byte-hex>`. This command prints the structured outcome and evidence when the probe ends. The 33 bytes are target AID in wire order (3), key number (1), AES algorithm (1), candidate ID in little-endian order (4), fresh RndB (16), optional discovery AID in wire order (3), discovery file (1), overall timeout in milliseconds in little-endian order (2), and post-challenge timeout in milliseconds in little-endian order (2). For example, `30758813` at the end sets 30 seconds overall and 5 seconds after the challenge. Preserve the RF trace separately and verify that it contains the challenge and reader continuation, with no final card response. + +For an offline USB bench test, use `hf mfdes etest --begin`, `--probe <33-byte-hex>`, `--scan`, the desired `--apdu` sequence, `--probe-result -j`, and `--end`. The offline request uses the same packed layout. A fixed nonce is suitable only for a deterministic bench replay; generate a fresh nonce for every live reader run. The result includes the observed key number, flags, RndB, and raw reader continuation. The offline test checks the simulator path, not a physical reader. diff --git a/include/desfire.h b/include/desfire.h index 33cc9d1c1..e71fe3f7a 100644 --- a/include/desfire.h +++ b/include/desfire.h @@ -35,6 +35,53 @@ typedef enum { #define DESFIRE_MAX_APP_COUNT 64 // applications we keep track of per PICC #define DESFIRE_MAX_FILE_COUNT 32 // file numbers 0x00 ... 0x1F +// Optional CMD_HF_DESFIRE_SIMULATE payload. An empty payload keeps normal +// simulation unchanged. A probe stops before the final authentication answer. +#define DESFIRE_SIM_PROBE_KEY_ANY 0xFF +typedef enum { + DESFIRE_SIM_PROBE_DISCOVERY_FAILED = 0, + DESFIRE_SIM_PROBE_NO_RESPONSE = 1, + DESFIRE_SIM_PROBE_NO_MATCH = 2, + DESFIRE_SIM_PROBE_MATCH = 3, + DESFIRE_SIM_PROBE_UNSUPPORTED = 4, +} desfire_sim_probe_outcome_t; + +typedef struct { + uint8_t aid[3]; // target AID in wire order + uint8_t keyno; // 0xFF: use the reader-requested key in the image + uint8_t algorithm; // DesfireCryptoAlgorithm + uint32_t candidate_id; // opaque host identifier, never key material + uint8_t rndb[16]; // fresh host nonce; deterministic only in tests + uint8_t discovery_aid[3]; // optional pre-auth application, zero disables + uint8_t discovery_file; // file number to observe on that application + uint16_t overall_timeout_ms; // 1000..60000 + uint16_t continuation_timeout_ms; // 100..overall_timeout_ms +} PACKED desfire_sim_probe_cmd_t; + +#define DESFIRE_SIM_PROBE_SELECTED (1 << 0) +#define DESFIRE_SIM_PROBE_AUTH_REQUEST (1 << 1) +#define DESFIRE_SIM_PROBE_CHALLENGE (1 << 2) +#define DESFIRE_SIM_PROBE_CONTINUATION (1 << 3) +#define DESFIRE_SIM_PROBE_DECRYPTED (1 << 4) +#define DESFIRE_SIM_PROBE_RNDB_MATCH (1 << 5) +#define DESFIRE_SIM_PROBE_DISCOVERY_SELECTED (1 << 6) +#define DESFIRE_SIM_PROBE_DISCOVERY_READ (1 << 7) + +typedef struct { + uint8_t outcome; // desfire_sim_probe_outcome_t + uint8_t flags; + uint8_t aid[3]; + uint8_t keyno; + uint8_t algorithm; + uint32_t candidate_id; + uint32_t challenge_ms; // GetTickCount at challenge + uint32_t continuation_ms; // GetTickCount at continuation + uint8_t rndb[16]; + uint8_t continuation[32]; + uint8_t continuation_len; + uint8_t last_command; +} PACKED desfire_sim_probe_result_t; + // Keys recovered for one application. // keys[algo][keyno][0] is the found flag, keys[algo][keyno][1..] the key itself. // `algo` is a DesfireCryptoAlgorithm, `keyno` the DESFire key number. @@ -52,6 +99,8 @@ typedef enum { DESFIRE_SIM_TEST_RANDOM, // data: bytes the next RndB / random id draws use DESFIRE_SIM_TEST_FIELDOFF, // RF reset: session dropped, image re-read -> no data DESFIRE_SIM_TEST_STATE, // -> desfire_sim_test_state_t + DESFIRE_SIM_TEST_PROBE_CONFIG, // data: desfire_sim_probe_cmd_t -> no data + DESFIRE_SIM_TEST_PROBE_RESULT, // -> desfire_sim_probe_result_t } desfire_sim_test_op_t; // bytes the random queue holds, RANDOM answers PM3_EOVFLOW past this