From a7b127678128346eb119623b2e44a05fa51cbe7c Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 21:13:10 +0200 Subject: [PATCH] phase 1 simulation and desfire fixes... --- armsrc/Makefile | 2 +- armsrc/desfiresim.c | 440 ++++++++++++++++++++++++++++++ armsrc/desfiresim.h | 58 ++++ armsrc/iso14443a.c | 89 +++++- client/src/cmdhf14a.c | 2 +- client/src/cmdhfmfdes.c | 131 ++++++++- client/src/mifare/desfirecore.c | 105 ++++++- client/src/mifare/desfirecore.h | 4 + client/src/mifare/desfirecrypto.h | 4 + client/src/mifare/desfireem.c | 6 + doc/commands.json | 16 +- doc/commands.md | 1 + include/protocols.h | 2 + 13 files changed, 840 insertions(+), 20 deletions(-) create mode 100644 armsrc/desfiresim.c create mode 100644 armsrc/desfiresim.h diff --git a/armsrc/Makefile b/armsrc/Makefile index 689716836..18ed75271 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -72,7 +72,7 @@ endif SRC_LF = lfops.c lfsampling.c pcf7931.c lfdemod.c lfadc.c SRC_HF = hfops.c SRC_ISO15693 = iso15693.c iso15693tools.c -SRC_ISO14443a = iso14443a.c secc.c mifareutil.c mifarecmd.c epa.c mifaresim.c +SRC_ISO14443a = iso14443a.c secc.c mifareutil.c mifarecmd.c epa.c mifaresim.c desfiresim.c ifneq (,$(findstring WITH_SMARTCARD,$(APP_CFLAGS))) SRC_ISO14443a += sam_common.c sam_mfc.c sam_seos.c sam_sc.c diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c new file mode 100644 index 000000000..248d49bea --- /dev/null +++ b/armsrc/desfiresim.c @@ -0,0 +1,440 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MIFARE DESFire tag simulation. +// +// Serves the card image `hf mfdes eload` put in emulator memory. The layout is +// in include/desfire_em.h; nothing here parses json or knows about files on the +// host, it only walks that image. +// +// This file is the DESFire half only. Anticollision, RATS, framing and timing +// are SimulateIso14443aTag()'s job over in iso14443a.c, which activates tag +// type 3 from the identity in the image and hands every ISO 14443-4 I-block to +// desfire_sim_apdu(). Duplicating that loop here got the ATQA wrong and would +// have kept drifting from the one that is exercised by every other tag type. +// +// Two timing regimes, and they want opposite things: +// +// - Before RATS there is no negotiated frame waiting time, and a tag that +// encodes its answer inside the response window is late. ATQA, the UID +// cascades, SAK and ATS are therefore precompiled by SimulateIso14443aInit() +// exactly as every other 14a simulation does. +// +// - After RATS the EV1 ATS asks for FWI 8, which is 77.33 ms, about 3.7 +// million ARM cycles. Everything from SelectApplication onward is computed +// on demand from the image. A software AES block costs a fraction of a +// percent of that, so there is no reason to precompute answers and every +// reason not to: a precomputed card cannot answer a write. +// +// What is implemented so far is the unauthenticated half: a reader can find the +// card, read its version, enumerate applications and files, and read file +// settings. Anything else answers ILLEGAL_COMMAND_CODE, which is what a real +// PICC says to a command it does not have. +//----------------------------------------------------------------------------- + +#include "desfiresim.h" + +#include "string.h" +#include "BigBuf.h" +#include "dbprint.h" +#include "protocols.h" +#include "desfire_em.h" + +typedef struct { + const desfire_em_hdr_t *hdr; + const desfire_em_app_t *apps; + const desfire_em_file_t *files; + const uint8_t *base; + + int selected; // index into apps[], -1 when nothing is selected + uint8_t chain_cmd; // command being continued over 0xAF, 0 when none + uint8_t chain_step; // which frame of it comes next +} desfire_sim_state_t; + +// The simulation runs one card at a time, and the 14a loop calls in here from +// several places, so the state is a file static rather than something the +// caller has to carry around. +static desfire_sim_state_t s_st; +static bool s_ready = false; + +// ---------------------------------------------------------------- image walk + +static bool desfire_sim_load(desfire_sim_state_t *st) { + + const uint8_t *em = BigBuf_get_EM_addr(); + if (em == NULL) { + return false; + } + + const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)em; + + if (hdr->magic != DESFIRE_EM_MAGIC) { + // Not an error: `hf 14a sim -t 3` with nothing loaded is a legitimate + // bare PICC that answers the anticollision and nothing else. The caller + // says so once, rather than this firing on every activation. + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("No DESFire card image in emulator memory, magic is " _YELLOW_("%08x"), hdr->magic); + } + return false; + } + + if (hdr->layout != DESFIRE_EM_LAYOUT_VERSION) { + Dbprintf("Card image layout v%u, this firmware speaks v%u", hdr->layout, DESFIRE_EM_LAYOUT_VERSION); + return false; + } + + if (hdr->size > BigBuf_get_EM_size() || hdr->appcount == 0) { + Dbprintf("Card image does not fit the emulator memory it was loaded into"); + return false; + } + + st->base = em; + st->hdr = hdr; + st->apps = (const desfire_em_app_t *)(em + hdr->app_off); + st->files = (const desfire_em_file_t *)(em + hdr->file_off); + st->selected = 0; // a PICC comes up with AID 000000 selected + st->chain_cmd = 0; + st->chain_step = 0; + return true; +} + +static uint32_t desfire_sim_aid(const desfire_em_app_t *a) { + return a->aid[0] | (a->aid[1] << 8) | (a->aid[2] << 16); +} + +static int desfire_sim_find_app(const desfire_sim_state_t *st, uint32_t aid) { + + for (uint8_t i = 0; i < st->hdr->appcount; i++) { + if ((st->apps[i].flags & DESFIRE_EM_APP_DELETED) == 0 && desfire_sim_aid(&st->apps[i]) == aid) { + return i; + } + } + return -1; +} + +// --------------------------------------------------------------- the answers + +// Build one DESFire answer: a status byte and optional payload. Returns the +// length written to `out`. +static uint16_t desfire_sim_status(uint8_t *out, uint8_t status) { + out[0] = status; + return 1; +} + +static uint16_t desfire_sim_payload(uint8_t *out, uint8_t status, const uint8_t *data, uint16_t len) { + out[0] = status; + if (len) { + memcpy(out + 1, data, len); + } + return len + 1; +} + +// Dispatch one DESFire command. `cmd` is the command byte, `in`/`inlen` the +// parameters after it. Writes the answer to `out` and returns its length. +static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const uint8_t *in, uint16_t inlen, uint8_t *out) { + + const desfire_em_hdr_t *hdr = st->hdr; + + // an additional frame only means anything while a command is being chained + if (cmd == MFDES_ADDITIONAL_FRAME && st->chain_cmd == 0) { + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + if (cmd != MFDES_ADDITIONAL_FRAME) { + st->chain_cmd = 0; + st->chain_step = 0; + } + + switch (cmd) { + + case MFDES_GET_VERSION: { + // three frames: hardware, software, then production. The first two + // are answered with ADDITIONAL_FRAME so the reader asks again. + st->chain_cmd = MFDES_GET_VERSION; + st->chain_step = 1; + return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, hdr->versionhw, hdr->versionhwlen); + } + + case MFDES_ADDITIONAL_FRAME: { + + if (st->chain_cmd == MFDES_GET_VERSION) { + + if (st->chain_step == 1) { + st->chain_step = 2; + return desfire_sim_payload(out, MFDES_ADDITIONAL_FRAME, hdr->versionsw, hdr->versionswlen); + } + + st->chain_cmd = 0; + st->chain_step = 0; + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, hdr->versionprod, hdr->versionprodlen); + } + + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } + + case MFDES_GET_APPLICATION_IDS: { + // PICC level only + if (st->selected != 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = 0; + for (uint8_t i = 1; i < hdr->appcount && (n + 3) <= sizeof(buf); i++) { + if (st->apps[i].flags & DESFIRE_EM_APP_DELETED) { + continue; + } + memcpy(buf + n, st->apps[i].aid, 3); + n += 3; + } + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, buf, n); + } + + case MFDES_SELECT_APPLICATION: { + + if (inlen < 3) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint32_t aid = in[0] | (in[1] << 8) | (in[2] << 16); + int idx = desfire_sim_find_app(st, aid); + if (idx < 0) { + return desfire_sim_status(out, MFDES_E_APPLICATION_NOT_FOUND); + } + + st->selected = idx; + return desfire_sim_status(out, MFDES_S_OPERATION_OK); + } + + case MFDES_GET_FREE_MEMORY: { + // what the card has left, not what emulator memory has left. Three + // bytes, LSB first. + uint32_t freemem = (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0; + uint8_t buf[3] = { freemem & 0xFF, (freemem >> 8) & 0xFF, (freemem >> 16) & 0xFF }; + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, buf, sizeof(buf)); + } + + case MFDES_GET_KEY_SETTINGS: { + const desfire_em_app_t *a = &st->apps[st->selected]; + uint8_t buf[2] = { a->keysettings, a->numkeysraw }; + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, buf, sizeof(buf)); + } + + case MFDES_GET_FILE_IDS: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + uint8_t buf[DESFIRE_SIM_MAX_RESP] = {0}; + uint16_t n = 0; + for (uint16_t i = 0; i < hdr->filecount && n < sizeof(buf); i++) { + if (st->files[i].app != st->selected) { + continue; + } + if (st->files[i].flags & DESFIRE_EM_FILE_DELETED) { + continue; + } + buf[n++] = st->files[i].num; + } + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, buf, n); + } + + case MFDES_GET_FILE_SETTINGS: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + for (uint16_t i = 0; i < hdr->filecount; i++) { + + const desfire_em_file_t *f = &st->files[i]; + if (f->app != st->selected || f->num != in[0]) { + continue; + } + if (f->flags & DESFIRE_EM_FILE_DELETED) { + break; + } + + uint8_t buf[17] = {0}; + uint16_t n = 0; + buf[n++] = f->type; + buf[n++] = f->flags & DESFIRE_EM_FILE_COMM_MASK; + buf[n++] = f->rights & 0xFF; + buf[n++] = (f->rights >> 8) & 0xFF; + + switch (f->type) { + case 0x00: + case 0x01: { + // the size the file was created with, not the rounded + // allocation -- measured, a real card reports 1 for a + // file created with 1 + uint32_t v = f->u.data.size; + buf[n++] = v & 0xFF; + buf[n++] = (v >> 8) & 0xFF; + buf[n++] = (v >> 16) & 0xFF; + break; + } + case 0x02: { + const uint32_t vals[3] = { f->u.value.lower, f->u.value.upper, f->u.value.value }; + for (uint8_t v = 0; v < 3; v++) { + buf[n++] = vals[v] & 0xFF; + buf[n++] = (vals[v] >> 8) & 0xFF; + buf[n++] = (vals[v] >> 16) & 0xFF; + buf[n++] = (vals[v] >> 24) & 0xFF; + } + buf[n++] = (f->flags & DESFIRE_EM_FILE_LIMCREDIT) ? 1 : 0; + break; + } + case 0x03: + case 0x04: { + const uint32_t vals[3] = { f->u.record.recordsize, f->u.record.maxrecords, f->u.record.currecords }; + for (uint8_t v = 0; v < 3; v++) { + buf[n++] = vals[v] & 0xFF; + buf[n++] = (vals[v] >> 8) & 0xFF; + buf[n++] = (vals[v] >> 16) & 0xFF; + } + break; + } + default: + break; + } + + return desfire_sim_payload(out, MFDES_S_OPERATION_OK, buf, n); + } + + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + default: + // Everything not implemented yet lands here, which is also the right + // answer for a command this generation genuinely does not have. + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: unhandled command " _YELLOW_("%02x"), cmd); + } + return desfire_sim_status(out, MFDES_E_ILLEGAL_COMMAND_CODE); + } +} + +//---------------------------------------------------------------- entry points + +bool desfire_sim_init(void) { + + // Always re-parse rather than cache across calls: an eload between two + // simulations replaces the image in place, and a stale parse would serve + // the previous card. It is only pointer setup, so calling it twice during + // activation costs nothing. + s_ready = false; + memset(&s_st, 0, sizeof(s_st)); + + if (desfire_sim_load(&s_st) == false) { + return false; + } + + s_ready = true; + return true; +} + +bool desfire_sim_ready(void) { + return s_ready; +} + +void desfire_sim_identity(uint8_t *uid, uint8_t *uidlen, uint8_t *atqa, uint8_t *sak, uint8_t *ats, uint8_t *atslen) { + + if (s_ready == false) { + return; + } + + const desfire_em_hdr_t *hdr = s_st.hdr; + + if (uid && hdr->uidlen <= sizeof(hdr->uid)) { + memcpy(uid, hdr->uid, hdr->uidlen); + } + + if (uidlen) { + *uidlen = hdr->uidlen; + } + + if (atqa) { + atqa[0] = hdr->atqa[0]; + atqa[1] = hdr->atqa[1]; + } + + if (sak) { + *sak = hdr->sak; + } + + if (ats && atslen) { + + // The image keeps the whole ATS frame the card sent, CRC included, + // because that is what round-trips through the dump file. The 14a layer + // appends its own CRC and checks the length against TL, so hand it the + // ATS proper. + uint8_t n = hdr->atslen; + if (n > 2 && hdr->ats[0] == n - 2) { + n -= 2; + } + + if (n > sizeof(hdr->ats)) { + n = sizeof(hdr->ats); + } + + memcpy(ats, hdr->ats, n); + *atslen = n; + } +} + +void desfire_sim_reset(void) { + + if (s_ready == false) { + return; + } + + s_st.selected = 0; // a PICC comes up with AID 000000 selected + s_st.chain_cmd = 0; + s_st.chain_step = 0; +} + +uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out) { + + if (s_ready == false || inlen < 1) { + return 0; + } + + return desfire_sim_command(&s_st, in[0], in + 1, inlen - 1, out); +} + +void desfire_sim_print_banner(void) { + + if (s_ready == false) { + return; + } + + const desfire_em_hdr_t *hdr = s_st.hdr; + + Dbprintf("Simulating DESFire, %u application(s), " _YELLOW_("%u") " bytes free" + , hdr->appcount - 1 + , (hdr->cardsize > hdr->reserved) ? (hdr->cardsize - hdr->reserved) : 0 + ); + + // The image carries whatever generation the card it came from was, and the + // version bytes we present say so. Only the EV1 command set is implemented, + // so a reader that follows those version bytes into an EV2 or EV3 command + // gets ILLEGAL_COMMAND_CODE. Say so rather than let it look like a bug. + if (hdr->generation != DESFIRE_EM_GEN_EV1 && hdr->generation != DESFIRE_EM_GEN_D40) { + Dbprintf(_YELLOW_("Only the EV1 command set is implemented")); + Dbprintf(_YELLOW_("A reader using a later command will get ILLEGAL_COMMAND_CODE 0x1C")); + } +} diff --git a/armsrc/desfiresim.h b/armsrc/desfiresim.h new file mode 100644 index 000000000..a99c9abc0 --- /dev/null +++ b/armsrc/desfiresim.h @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// MIFARE DESFire tag simulation. +// +// This is the DESFire half only. The 14a layer -- anticollision, RATS, framing, +// timing -- belongs to SimulateIso14443aTag() in iso14443a.c, which calls in +// here for tag type 3. +//----------------------------------------------------------------------------- + +#ifndef __DESFIRESIM_H +#define __DESFIRESIM_H + +#include "common.h" + +// Largest answer built before the 14443-4 prologue and CRC are added. +// GetApplicationIDs on a full PICC is 28 * 3 bytes plus a status byte. +#define DESFIRE_SIM_MAX_RESP 128 + +// Pick up the card image `hf mfdes eload` put in emulator memory. False when +// there is none, or it is not a layout this firmware speaks -- the caller then +// simulates a bare DESFire shell that only answers the anticollision. +// Idempotent: call it as often as convenient, it parses once. +bool desfire_sim_init(void); + +// Whether desfire_sim_init() found an image. Cheap, safe before init. +bool desfire_sim_ready(void); + +// Card identity out of the image, for the precompiled 14a answers. Every +// pointer is optional; `ats` wants room for 20 bytes and comes back without its +// CRC, which is what SimulateIso14443aInit() expects. +void desfire_sim_identity(uint8_t *uid, uint8_t *uidlen, uint8_t *atqa, uint8_t *sak, uint8_t *ats, uint8_t *atslen); + +// A fresh activation or a HALT puts the PICC back at AID 000000 and drops any +// command that was being chained. +void desfire_sim_reset(void); + +// Answer one DESFire command. `in`/`inlen` is the ISO 14443-4 I-block payload +// with the prologue and CRC already stripped; `out` receives the status byte +// and its payload, at most DESFIRE_SIM_MAX_RESP bytes. Returns that length. +uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out); + +// One line about what is loaded, for the simulation banner. +void desfire_sim_print_banner(void); + +#endif // __DESFIRESIM_H diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 071b5b9fe..dda812388 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -18,6 +18,7 @@ // Routines to support ISO 14443 type A. //----------------------------------------------------------------------------- #include "iso14443a.h" +#include "desfiresim.h" #include "pm3_cmd.h" #include "string.h" @@ -1393,6 +1394,40 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, sak = 0x20; memcpy(rATS, "\x06\x75\x77\x81\x02\x80\x00\x00", 8); rATS_len = 8; // including CRC + + // A DESFire card image in emulator memory answers for itself: ATQA, + // SAK and ATS come from the card it was dumped from, and the loop + // below hands ISO 14443-4 I-blocks to it. Without an image this + // stays the generic shell that only answers the anticollision. + if (desfire_sim_init()) { + + uint8_t im_atqa[2] = {0}; + uint8_t im_sak = 0; + uint8_t im_ats[20] = {0}; + uint8_t im_atslen = 0; + desfire_sim_identity(NULL, NULL, im_atqa, &im_sak, im_ats, &im_atslen); + + if (im_atqa[0] || im_atqa[1]) { + // the UID size bits of byte 0 are set further down, from the + // cascade level the image's UID actually needs + rATQA[0] = im_atqa[0]; + rATQA[1] = im_atqa[1]; + } + + if (im_sak) { + sak = im_sak; + } + + if (im_atslen > 0 && (size_t)im_atslen + 2 <= sizeof(rATS)) { + memset(rATS, 0, sizeof(rATS)); + memcpy(rATS, im_ats, im_atslen); + rATS_len = im_atslen + 2; // including CRC + } + + } else { + DbpString("No DESFire card image loaded, simulating a bare PICC"); + DbpString("Load one with " _YELLOW_("`hf mfdes eload -f `")); + } break; } case 4: { // ISO/IEC 14443-4 - javacard (JCOP) @@ -1570,6 +1605,16 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, memcpy(data, emdata, 3); // uid bytes 0-2 memcpy(data + 3, emdata + 4, 4); // uid bytes 3-7 FLAG_SET_UID_IN_DATA(flags, 7); + } else if (tagType == 3 && desfire_sim_ready()) { + // a DESFire image does not start with the UID, it starts with a + // header that has the UID and its length in it + uint8_t im_uidlen = 0; + desfire_sim_identity(data, &im_uidlen, NULL, NULL, NULL, NULL); + FLAG_SET_UID_IN_DATA(flags, im_uidlen); + if (IS_FLAG_UID_IN_EMUL(flags)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("[-] ERROR: card image has a %u byte UID", im_uidlen); + return false; + } } else { emlGet(data, 0, 4); FLAG_SET_UID_IN_DATA(flags, 4); @@ -1802,6 +1847,10 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u uint16_t dynamic_response_buffer_size = DYNAMIC_RESPONSE_BUFFER_SIZE; if (tagType == 10) { dynamic_response_buffer_size = ST25TA_EML_NDEF_MAX + 4; + } else if (tagType == 3) { + // GetApplicationIDs on a full PICC is 28 * 3 bytes, over the 64 the + // other tag types get. Room for the 14443-4 prologue and CRC on top. + dynamic_response_buffer_size = DESFIRE_SIM_MAX_RESP + 8; } // prepare_tag_modulation() memcpy's the encoded answer out of the ToSend @@ -1870,6 +1919,10 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u } } + if (tagType == 3) { + desfire_sim_print_banner(); + } + // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); @@ -2018,8 +2071,11 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u if (odd_reply) { p_response = &responses[RESP_INDEX_ATQA]; } + // a fresh activation puts a DESFire back at AID 000000 + desfire_sim_reset(); } else if (receivedCmd[0] == ISO14443A_CMD_WUPA && len == 1) { // Received a WAKEUP p_response = &responses[RESP_INDEX_ATQA]; + desfire_sim_reset(); } else if (receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && len == 2) { // Received request for UID (cascade 1) p_response = &responses[RESP_INDEX_UIDC1]; } else if (receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && len == 2) { // Received request for UID (cascade 2) @@ -2500,8 +2556,39 @@ void SimulateIso14443aTagEx(uint8_t tagType, uint16_t flags, uint8_t *useruid, u dynamic_response_info.response_n = 0; dynamic_response_info.modulation_n = 0; + // DESFire, from the card image in emulator memory. Only I-blocks + // come here; S(DESELECT), R-blocks and the rest keep the generic + // 14443-4 handling below. + if (tagType == 3 && desfire_sim_ready() && (receivedCmd[0] & 0xC0) == 0x00) { + + // prologue is PCB, then CID and NAD when the PCB says so + uint8_t prologue = 1; + if (receivedCmd[0] & 0x08) { + prologue++; + } + if (receivedCmd[0] & 0x04) { + prologue++; + } + + // prologue + at least a command byte + CRC + if (len >= prologue + 1 + 2) { + + // echo the prologue back untouched. The low bit of the PCB + // is the block number, and a reader that gets the wrong one + // reads the answer as a retransmission and stalls. + memcpy(dynamic_response_info.response, receivedCmd, prologue); + dynamic_response_info.response[0] &= ~0x10; // we never chain + + uint16_t n = desfire_sim_apdu(receivedCmd + prologue, + len - prologue - 2, + dynamic_response_info.response + prologue); + if (n > 0) { + dynamic_response_info.response_n = prologue + n; + } + } + // ST25TA512B IKEA Rothult - if (tagType == 10) { + } else if (tagType == 10) { // we replay 90 00 for all commands but the read bin and we deny the verify cmd. static const uint8_t default_st25ta_ndef[] = { diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index 453d17560..a021d0b80 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -1071,7 +1071,7 @@ int CmdHF14ASim(const char *Cmd) { "Use type 7 for Mifare Ultralight EV1, Amiibo (NTAG215 pack 0x8080)", "hf 14a sim -t 1 --uid 11223344 -> MIFARE Classic 1k\n" "hf 14a sim -t 2 -> MIFARE Ultralight\n" - "hf 14a sim -t 3 -> MIFARE Desfire\n" + "hf 14a sim -t 3 -> MIFARE DESFire (card image from `hf mfdes eload`)\n" "hf 14a sim -t 4 -> ISO/IEC 14443-4\n" "hf 14a sim -t 5 -> MIFARE Tnp3xxx\n" "hf 14a sim -t 6 -> MIFARE Mini\n" diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 230f797d9..27d7280f0 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -661,7 +661,14 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE size_t prepare_resp_len = 0; uint8_t respcode = 0xFF; res = DesfireExchangeEx(activate_field, dctx, MFDES_PREPARE_PC, NULL, 0, &respcode, prepare_resp, &prepare_resp_len, true, 0); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + // DesfireExchangeEx reports the transport result; the card's own status + // comes back in respcode and an error there still reads as success. It + // also ends the authentication, so drop our side of the session. + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Prepare proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw)); goto out; @@ -715,7 +722,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE respcode = 0xFF; res = DesfireExchange(dctx, MFDES_PROXIMITY_CHECK, round_payload, challenge_part_len + 1, &respcode, round_resp, &round_resp_len); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Proximity check round %u command failed. Result: %d %s", (unsigned int)round + 1, res, DesfireGetErrorString(res, &sw)); goto out; @@ -767,7 +778,11 @@ static int DesfirePCRun(DesfireContext_t *dctx, const uint8_t proximity_key[MFDE size_t verify_resp_len = 0; respcode = 0xFF; res = DesfireExchange(dctx, MFDES_VERIFY_PC, verify_cmd_mac, sizeof(verify_cmd_mac), &respcode, verify_resp, &verify_resp_len); - if (res != PM3_SUCCESS) { + if (res != PM3_SUCCESS || respcode != MFDES_S_OPERATION_OK) { + if (res == PM3_SUCCESS) { + res = PM3_EAPDU_FAIL; + } + DesfireClearSession(dctx); uint16_t sw = status(respcode); PrintAndLogEx(ERR, "Verify proximity check command failed. Result: %d %s", res, DesfireGetErrorString(res, &sw)); goto out; @@ -1468,6 +1483,13 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, if (res == PM3_SUCCESS) { if (filescount > 0) { for (int i = 0; i < filescount; i++) { + if (fileList[i].fileSettingsRead == false) { + // settings we could not read tell us nothing about which + // keys the file uses, so keep every key in the search + for (int k = 0; k < DESFIRE_MAX_KEY_COUNT; k++) + usedkeys[k] = 1; + break; + } if (fileList[i].fileSettings.rAccess < 0x0e) usedkeys[fileList[i].fileSettings.rAccess] = 1; if (fileList[i].fileSettings.wAccess < 0x0e) @@ -3128,6 +3150,7 @@ static int DesfireGetDelegatedInfoNoFieldOn(DesfireContext_t *dctx, uint16_t dam } if (respcode != MFDES_S_OPERATION_OK) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -8156,8 +8179,13 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { } PrintAndLogEx(INFO, "------------------------------------------ " _CYAN_("File list") " -----------------------------------------------------"); - for (int i = 0; i < filescount; i++) + for (int i = 0; i < filescount; i++) { + if (FileList[i].fileSettingsRead == false) { + PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read", FileList[i].fileNum); + continue; + } DesfirePrintFileSettingsTable((i == 0), FileList[i].fileNum, isopresent, FileList[i].fileISONum, &FileList[i].fileSettings); + } DropField(); return PM3_SUCCESS; @@ -8343,7 +8371,15 @@ static int DesfireDumpFindApp(const AppListS appList, size_t appcount, const Des return -1; } -static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f) { +static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f, bool settings_ok) { + + // Settings we never read are not a 0 byte standard data file. Leave the + // whole record at its defaults and say so, the same way read_ok does for + // contents -- a simulator built from this image must not invent a file. + if (settings_ok == false) { + f->settings_ok = false; + return; + } f->type = fs->fileType; f->commmode = fs->fileCommMode; @@ -8583,9 +8619,16 @@ static int DesfireDumpCollectApp(DesfireContext_t *dctx, desfire_dump_app_t *app desfire_dump_file_t *f = &app->files[app->filecount]; f->num = FileList[i].fileNum; f->isofid = FileList[i].fileISONum; - DesfireDumpFillFileSettings(&FileList[i].fileSettings, f); + DesfireDumpFillFileSettings(&FileList[i].fileSettings, f, FileList[i].fileSettingsRead); app->filecount++; + if (FileList[i].fileSettingsRead == false) { + // without the settings we do not know the file's type, so there is + // no sensible read command to send + PrintAndLogEx(WARNING, "File " _YELLOW_("0x%02x") " settings could not be read, contents skipped", f->num); + continue; + } + session_lost = (DesfireDumpReadFile(dctx, &FileList[i].fileSettings, f, maxlength, verbose) == PM3_ESOFT); DesfireDumpPrintFile(f, isopresent); @@ -9043,6 +9086,81 @@ static void DesfireViewPrintApp(const desfire_dump_app_t *app) { } } +static int CmdHF14ADesSim(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes sim", + "Simulate the DESFire card image currently in emulator memory.\n" + "Load one first with `hf mfdes eload`, and read back what a reader\n" + "changed with `hf mfdes esave`.\n" + "\n" + "This is `hf 14a sim -t 3` with the DESFire command set behind it:\n" + "UID, ATQA, SAK and ATS all come out of the loaded image", + "hf mfdes sim\n" + "hf mfdes sim -n 1 -> stop after the first reader session\n"); + + void *argtable[] = { + arg_param_begin, + arg_int0("n", "num", "", "Exit after commands have been answered. 0 = infinite"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + uint8_t exit_after = arg_get_int_def(ctx, 1, 0); + CLIParserFree(ctx); + + // Same payload the 14a simulation takes -- there is one 14443a tag loop on + // the device and this is it. Tag type 3 is MIFARE DESFire; the UID is left + // for the device to lift out of the card image header, which is why no UID + // is supplied here. + struct { + uint8_t tagtype; + uint16_t flags; + uint8_t uid[10]; + uint8_t exitAfter; + uint8_t rats[20]; + uint8_t ulauth_1a1_len; + uint8_t ulauth_1a2_len; + uint8_t ulauth_1a1[16]; + uint8_t ulauth_1a2[16]; + bool ulauth_1a2_mirror; + } PACKED payload; + + memset(&payload, 0x00, sizeof(payload)); + payload.tagtype = 3; + payload.exitAfter = exit_after; + FLAG_SET_UID_IN_EMUL(payload.flags); + + clearCommandBuffer(); + SendCommandNG(CMD_HF_ISO14443A_SIMULATE, (uint8_t *)&payload, sizeof(payload)); + + 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_MIFARE_SIMULATE, &resp, 1500) == false) { + continue; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Simulation stopped"); + PrintAndLogEx(HINT, "Hint: load a card image with " _YELLOW_("`hf mfdes eload -f `")); + return resp.status; + } + 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"); + return PM3_SUCCESS; +} + static int CmdHF14ADesELoad(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes eload", @@ -11018,6 +11136,7 @@ static command_t CommandTable[] = { {"eload", CmdHF14ADesELoad, IfPm3Iso14443a, "Upload file into emulator memory"}, {"esave", CmdHF14ADesESave, IfPm3Iso14443a, "Save emulator memory to file"}, {"eview", CmdHF14ADesEView, IfPm3Iso14443a, "View emulator memory"}, + {"sim", CmdHF14ADesSim, IfPm3Iso14443a, "Simulate DESFire card from emulator memory"}, {"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"}, {"createvaluefile", CmdHF14ADesCreateValueFile, IfPm3Iso14443a, "Create Value File"}, {"createrecordfile", CmdHF14ADesCreateRecordFile, IfPm3Iso14443a, "Create Linear/Cyclic Record File"}, diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index 23921a9af..fb80e66f9 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -437,6 +437,27 @@ void DesfirePrintContext(DesfireContext_t *ctx) { } } +// Table 11 of M075031 footnotes five status codes as "not expected to appear +// during normal operation": the card saying it has damaged or disabled itself. +// Those are never noise, so they are reported whether or not APDU logging is on. +// Everything else is an ordinary refusal, and the caller decides what to say. +static void DesfireReportUnrecoverable(uint8_t cmd, uint8_t respcode) { + + if (respcode != MFDES_E_PICC_INTEGRITY && + respcode != MFDES_E_PICC_DISABLED && + respcode != MFDES_E_APPL_INTEGRITY && + respcode != MFDES_E_FILE_INTEGRITY && + respcode != MFDES_E_EEPROM) { + return; + } + + uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode); + PrintAndLogEx(WARNING, "Desfire command " _YELLOW_("0x%02X") " -> " _RED_("0x%02X") " %s" + , cmd + , respcode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &sw)); +} + static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) { if (result_len) *result_len = 0; if (sw) *sw = 0; @@ -483,6 +504,11 @@ static int DESFIRESendApduEx(bool activate_field, sAPDU_t apdu, uint16_t le, uin isw != DESFIRE_GET_ISO_STATUS(MFDES_S_SIGNATURE) && isw != DESFIRE_GET_ISO_STATUS(MFDES_S_ADDITIONAL_FRAME) && isw != DESFIRE_GET_ISO_STATUS(MFDES_S_NO_CHANGES)) { + + if ((isw >> 8) == 0x91) { + DesfireReportUnrecoverable(apdu.INS, isw & 0xFF); + } + if (GetAPDULogging()) { if (isw >> 8 == 0x61) { PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); @@ -567,6 +593,8 @@ static int DESFIRESendRaw(bool activate_field, uint8_t *data, size_t datalen, ui if (!rcode_ok) { + DesfireReportUnrecoverable(data[0], rcode); + if (GetAPDULogging()) { PrintAndLogEx(ERR, "Command (%02x) ERROR: 0x%02x", data[0], rcode); } @@ -2002,7 +2030,18 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap // result bytes: 3, 2, 1-16. total record size = 24 res = DesfireGetDFList(dctx, buf, &buflen); if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Desfire GetDFList command " _RED_("error") ". Result: %d", res); + // Same hazard as GetFileISOIDList below: the PICC ends the authentication + // on a command error, so drop our side of the session too. Left alone, + // every following command is still framed as MACed against a session the + // card has already thrown away, and the card sees a run of frames whose + // integrity it cannot verify. Callers that keep using the card + // re-authenticate. + dctx->secureChannel = DACNone; + uint16_t dfsw = DESFIRE_GET_ISO_STATUS(dctx->lastRespCode); + PrintAndLogEx(WARNING, "Desfire GetDFList command " _RED_("error") ". Result: %d, card said " _RED_("0x%02X") " %s. Session dropped by the PICC" + , res + , dctx->lastRespCode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &dfsw)); } else if (buflen > 0) { for (int i = 0; i < buflen; i++) { int indx = AppListSearchAID(DesfireAIDByteToUint(&buf[i * 24 + 1]), appList, PICCInfo->appCount); @@ -2030,7 +2069,7 @@ int DesfireFillAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS ap if (res != PM3_SUCCESS) continue; - DesfireGetKeySettings(dctx, buf, &buflen); + res = DesfireGetKeySettings(dctx, buf, &buflen); if (res == PM3_SUCCESS && buflen >= 2) { appList[i].keySettings = buf[0]; appList[i].numKeysRaw = buf[1]; @@ -2126,7 +2165,11 @@ void DesfirePrintAppList(DesfireContext_t *dctx, PICCInfo_t *PICCInfo, AppListS PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); } } - DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings); + if (appList[i].fileList[fnum].fileSettingsRead) { + DesfirePrintFileSettingsExtended(&appList[i].fileList[fnum].fileSettings); + } else { + PrintAndLogEx(WARNING, "File settings : " _YELLOW_("could not be read")); + } } } PrintAndLogEx(NORMAL, ""); @@ -2156,6 +2199,24 @@ static int DesfireCommandEx(DesfireContext_t *dctx, uint8_t cmd, uint8_t *data, } if (respcode != MFDES_S_OPERATION_OK) { + // Keep and print which status the card returned. Every card error + // collapses to PM3_EAPDU_FAIL on the way out, so without this the + // difference between 0x1C ILLEGAL_COMMAND_CODE, 0xCA COMMAND_ABORTED and + // 0xC1 PICC_INTEGRITY_ERROR -- the card saying it has just disabled + // itself -- never reaches the caller or the log. + dctx->lastRespCode = respcode; + uint16_t sw = DESFIRE_GET_ISO_STATUS(respcode); + PrintAndLogEx(DEBUG, "Desfire command " _YELLOW_("0x%02X") " returned " _RED_("0x%02X") " %s" + , cmd + , respcode + , DesfireGetErrorString(PM3_EAPDU_FAIL, &sw)); + + // The PICC ends the authentication on a command error, so drop our side + // of the session too. Left set, every following command is still framed + // as MACed against a session the card has thrown away: the plain answer + // gets parsed as a CMAC, and the card sees a run of frames whose + // integrity it cannot verify. Callers that keep going re-authenticate. + DesfireClearSession(dctx); free(xresp); return PM3_EAPDU_FAIL; } @@ -2230,6 +2291,7 @@ int DesfireReadSignature(DesfireContext_t *dctx, uint8_t sid, uint8_t *resp, siz } if (respcode != 0x90) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -2283,6 +2345,7 @@ int DesfireCreateDelegatedApplication(DesfireContext_t *dctx, uint8_t *appdata, return res; } if (respcode != MFDES_S_OPERATION_OK) { + DesfireClearSession(dctx); return PM3_EAPDU_FAIL; } @@ -2360,7 +2423,8 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil for (int i = 0; i < buflen; i++) { FileList[i].fileNum = buf[i]; - DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings); + FileList[i].fileSettingsRead = + (DesfireFileSettingsStruct(dctx, FileList[i].fileNum, &FileList[i].fileSettings) == PM3_SUCCESS); } *filescount = buflen; @@ -2378,6 +2442,13 @@ int DesfireFillFileList(DesfireContext_t *dctx, FileList_t FileList, size_t *fil size_t isoindx = 0; if (buflen > 0) { for (int i = 0; i < *filescount; i++) { + if (FileList[i].fileSettingsRead == false) { + // we do not know this file's type, so we cannot tell whether it + // takes an entry. Stop rather than hand out ISO ids that belong + // to other files. + PrintAndLogEx(DEBUG, "File 0x%02x settings unknown, ISO ID mapping stops here", FileList[i].fileNum); + break; + } if (FileList[i].fileSettings.fileType != 0x02 && FileList[i].fileSettings.fileType != 0x05) { FileList[i].fileISONum = MemLeToUint2byte(&buf[isoindx * 2]); isoindx++; @@ -3190,8 +3261,12 @@ int DesfireISOSelectEx(DesfireContext_t *dctx, bool fieldon, DesfireISOSelectCon if (res == PM3_EAPDU_FAIL && sw == 0 && xresplen == 0) { return PM3_ECARDEXCHANGE; } - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // the success path below clears the session because a select ends the + // authentication; a refused select ends it just the same + DesfireClearSession(dctx); return PM3_ESOFT; + } if (resp != NULL && resplen != NULL) { *resplen = xresplen; @@ -3260,8 +3335,11 @@ int DesfireISOReadBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t filei uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_BINARY, p1, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3279,8 +3357,11 @@ int DesfireISOUpdateBinary(DesfireContext_t *dctx, bool use_file_id, uint8_t fil uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_UPDATE_BINARY, p1, p2, datalen, data}, 0, resp, &resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3290,8 +3371,11 @@ int DesfireISOReadRecords(DesfireContext_t *dctx, uint8_t recordnum, bool read_a uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_READ_RECORDS, recordnum, p2, 0, NULL}, (length == 0) ? APDU_INCLUDE_LE_00 : length, resp, resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } @@ -3304,8 +3388,11 @@ int DesfireISOAppendRecord(DesfireContext_t *dctx, uint8_t fileid, uint8_t *data uint16_t sw = 0; int res = DesfireExchangeISO(false, dctx, (sAPDU_t) {0x00, ISO7816_APPEND_RECORD, 0x00, p2, datalen, data}, 0, resp, &resplen, &sw); - if (res == PM3_SUCCESS && sw != ISO7816_OK) + if (res == PM3_SUCCESS && sw != ISO7816_OK) { + // an error ends the authentication on the card, so drop our side too + DesfireClearSession(dctx); return PM3_ESOFT; + } return res; } diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index ab18f5d20..194d18207 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -95,6 +95,10 @@ typedef struct { typedef struct { uint8_t fileNum; uint16_t fileISONum; + // false means GetFileSettings failed for this file, so fileSettings is + // zeros and not a 0 byte standard data file. Callers must not read + // fileSettings without checking this first + bool fileSettingsRead; FileSettings_t fileSettings; } FileListElm_t; diff --git a/client/src/mifare/desfirecrypto.h b/client/src/mifare/desfirecrypto.h index 8327e9be3..dd82abca2 100644 --- a/client/src/mifare/desfirecrypto.h +++ b/client/src/mifare/desfirecrypto.h @@ -86,6 +86,10 @@ typedef struct { uint8_t sessionKeyEnc[DESFIRE_MAX_KEY_SIZE]; // look at mifare4.h - mf4Session_t uint8_t lastIV[DESFIRE_MAX_KEY_SIZE]; uint8_t lastCommand; + // status byte of the last answer the card gave. Every card error collapses + // to PM3_EAPDU_FAIL on the way out, so this is the only place the caller can + // find out which one it was + uint8_t lastRespCode; bool lastRequestZeroLen; uint16_t cmdCntr; // for AES uint8_t TI[4]; // for AES diff --git a/client/src/mifare/desfireem.c b/client/src/mifare/desfireem.c index 7a71a4b4b..3ee1af73d 100644 --- a/client/src/mifare/desfireem.c +++ b/client/src/mifare/desfireem.c @@ -601,6 +601,12 @@ void desfire_em_print(const uint8_t *img, size_t imglen) { const desfire_em_hdr_t *hdr = (const desfire_em_hdr_t *)img; + if (hdr->magic != DESFIRE_EM_MAGIC) { + PrintAndLogEx(WARNING, "No DESFire card image here, magic is " _YELLOW_("%08X"), hdr->magic); + PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); + return; + } + PrintAndLogEx(INFO, "--- " _CYAN_("DESFire card image") " -----------------------"); PrintAndLogEx(SUCCESS, "Generation....... %s", desfire_em_gen_str(hdr->generation)); PrintAndLogEx(SUCCESS, "UID.............. %s", sprint_hex_inrow(hdr->uid, hdr->uidlen)); diff --git a/doc/commands.json b/doc/commands.json index 0481f9161..605cbc9af 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -8566,6 +8566,18 @@ ], "usage": "hf mfdes setconfig [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [-p ] [-d ]" }, + "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`", + "notes": [ + "hf mfdes sim" + ], + "offline": false, + "options": [ + "-h, --help This help" + ], + "usage": "hf mfdes sim [-h]" + }, "hf mfdes test": { "command": "hf mfdes test", "description": "Regression crypto tests", @@ -16602,8 +16614,8 @@ } }, "metadata": { - "commands_extracted": 924, + "commands_extracted": 925, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-14T17:45:11+00:00" + "extracted_on": "2026-09-14T17:55:25+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index d92ad86aa..1004517ba 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -821,6 +821,7 @@ Check column "offline" for their availability. |`hf mfdes eload `|N |`Upload file into emulator memory` |`hf mfdes esave `|N |`Save emulator memory to file` |`hf mfdes eview `|N |`View emulator memory` +|`hf mfdes sim `|N |`Simulate DESFire card from emulator memory` |`hf mfdes createfile `|N |`Create Standard/Backup File` |`hf mfdes createvaluefile`|N |`Create Value File` |`hf mfdes createrecordfile`|N |`Create Linear/Cyclic Record File` diff --git a/include/protocols.h b/include/protocols.h index c9f40e843..fda9b4dd2 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -726,6 +726,8 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_S_SIGNATURE 0x90 #define MFDES_S_ADDITIONAL_FRAME 0xAF +#define MFDES_S_OPERATION_OK 0x00 +#define MFDES_S_NO_CHANGES 0x0C #define MFDES_E_OUT_OF_EEPROM 0x0E #define MFDES_E_ILLEGAL_COMMAND_CODE 0x1C #define MFDES_E_INTEGRITY_ERROR 0x1E