From 2d70fcb4ff12e24ed959d013aea1bce51aba1401 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 15 Sep 2026 14:43:52 +0200 Subject: [PATCH] hf mfdes sim: self contained DESFire simulation, and stop bitstream downloads eating emulator memory The DESFire simulation gets its own ISO 14443-A loop in armsrc/desfiresim.c rather than hooking into SimulateIso14443aTag(). That function is complicated enough without a DESFire state machine threaded through it, and the hook had already got the ATQA wrong once. It still borrows the library helpers from iso14443a.c -- the precompiled activation answers, the receive call, the send calls -- so there is no duplicated state machine, and iso14443a.c goes back to knowing nothing about DESFire. desfiresim.h exports one symbol. Three fixes were needed to make it actually answer a reader. 1. ISO 7816 wrapping. A reader sends `02 90 60 00 00 00`, not `02 60`. The simulation read in[0] as the DESFire command and so saw 0x90, the class byte, answering ILLEGAL_COMMAND_CODE to everything -- and in native form (status || data) when the reader wanted the wrapped form (data || 91 SW). Both framings are handled now, including the Lc/Le distinction: five bytes means no data and in[4] is Le, longer means in[4] is Lc with data following. 2. A bitstream download frees and clears BigBuf to get scratch space for the decompressor. SimulateIso14443aTagEx() and Mifare1ksim() both guard against this by calling FpgaDownloadAndGo_keep_EM() before they allocate anything; the new loop did not, so iso14443a_setup() wiped the emulator memory holding the card image and the precompiled answers after they had been filled. The pointers survive, the bytes do not, and the tag then clocks out zeros. 3. iso14443a_setup() itself used the plain FpgaDownloadAndGo(), which does BigBuf_free() and BigBuf_Clear_ext() -- taking the emulator memory with it. Every 14a command comes through there, so a card image that `eload` had just put in place was destroyed by the next `hf 14a` command whenever the HF bitstream was not already resident. Demonstrated before and after: `eload` then `hf 14a reader` then `eview` used to report "No DESFire card image in emulator memory" and now returns the image intact. This affected every emulator memory user, not only DESFire. Verified against a second Proxmark3 acting as reader, simulating a real DESFire EV1 8K dump: activation (UID 04268512A25680, ATQA 03 44, SAK 20, ATS 06 75 77 81 02 80), the three frame GetVersion chain over 0xAF, GetFreeMem, GetApplicationIDs, SelectApplication, GetKeySettings and GetFileSettings. `hf mfdes info`, `getaids`, `freemem`, `lsapp` and `lsfiles` all read correctly, including per application key types (AES, 2TDEA, 3TDEA) and all five EV1 file types with their real settings -- a value file holding 1000 with limits [0..10000], a linear record 2/8 of 16 bytes, a cyclic record 1/4 of 24 bytes, standard files of 256 and 64 bytes, and a backup file of 128 bytes in MAC mode with keyed rights 1200. Not implemented yet: GetDFNames (0x6D) and GetISOFileIDs (0x61), so a reader sees empty ISO IDs and DF names. Everything else answers ILLEGAL_COMMAND_CODE, which is what a PICC says to a command it does not have. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 + armsrc/appmain.c | 5 + armsrc/desfiresim.c | 256 ++++++++++++++++++++++++++++++++++++++-- armsrc/desfiresim.h | 48 ++------ armsrc/iso14443a.c | 106 ++--------------- client/src/cmdhf14a.c | 2 +- client/src/cmdhfmfdes.c | 36 +----- include/pm3_cmd.h | 1 + 8 files changed, 282 insertions(+), 174 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a79f8cb19..40af7e997 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf 14a` - an FPGA bitstream download no longer destroys the emulator memory that `eload` just filled (@iceman1001) +- Changed `hf mfdes sim` - now a self contained DESFire simulation, answering both native and ISO 7816 wrapped commands (@iceman1001) - Fixed `hf mfdes` - GetDFNames is no longer sent inside an authenticated session, which permanently disabled DESFire EV1 cards (@iceman1001) - Added `hf mfdes` - the five DESFire status codes that mean the card damaged or disabled itself are now named instead of reported as `-20` (@iceman1001) - Fixed `hf mfdes` - a command error now drops the client's secure channel, since the PICC has already ended the authentication (@iceman1001) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index a813bde6c..0e885c9c6 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -68,6 +68,7 @@ #include "mifarecmd.h" #include "mifaredesfire.h" #include "mifaresim.h" +#include "desfiresim.h" #include "emvsim.h" #include "pcf7931.h" #include "Standalone/standalone.h" @@ -2548,6 +2549,10 @@ static void PacketReceived(PacketCommandNG *packet) { Mifare1ksim(payload->flags, payload->exitAfter, payload->uid, payload->atqa, payload->sak); break; } + case CMD_HF_DESFIRE_SIMULATE: { + SimulateDesfireTag(); + break; + } case CMD_HF_MIFARE_EML_MEMCLR: { //----------------------------------------------------------------------------- diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c index 48b545e37..d385fe3ac 100644 --- a/armsrc/desfiresim.c +++ b/armsrc/desfiresim.c @@ -47,11 +47,28 @@ #include "desfiresim.h" #include "string.h" +#include "proxmark3_arm.h" +#include "cmd.h" +#include "appmain.h" #include "BigBuf.h" #include "dbprint.h" +#include "util.h" +#include "iso14443a.h" +#include "crc16.h" +#include "fpga_apis.h" +#include "fpga_loader.h" #include "protocols.h" #include "desfire_em.h" +// ISO 7816 wrapping of the DESFire command set: class byte on the way in, +// first status byte on the way back. +#define DESFIRE_SIM_ISO7816_CLA 0x90 +#define DESFIRE_SIM_ISO7816_SW1 0x91 + +// 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 + typedef struct { const desfire_em_hdr_t *hdr; const desfire_em_app_t *apps; @@ -330,7 +347,7 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const //---------------------------------------------------------------- entry points -bool desfire_sim_init(void) { +static 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 @@ -347,11 +364,7 @@ bool desfire_sim_init(void) { 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) { +static 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; @@ -396,7 +409,7 @@ void desfire_sim_identity(uint8_t *uid, uint8_t *uidlen, uint8_t *atqa, uint8_t } } -void desfire_sim_reset(void) { +static void desfire_sim_reset(void) { if (s_ready == false) { return; @@ -407,7 +420,7 @@ void desfire_sim_reset(void) { s_st.chain_step = 0; } -uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out) { +static uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out) { if (s_ready == false || inlen < 1) { return 0; @@ -455,7 +468,7 @@ uint16_t desfire_sim_apdu(const uint8_t *in, uint16_t inlen, uint8_t *out) { return desfire_sim_command(&s_st, in[0], in + 1, inlen - 1, out); } -void desfire_sim_print_banner(void) { +static void desfire_sim_print_banner(void) { if (s_ready == false) { return; @@ -477,3 +490,228 @@ void desfire_sim_print_banner(void) { Dbprintf(_YELLOW_("A reader using a later command will get ILLEGAL_COMMAND_CODE 0x1C")); } } + +//-------------------------------------------------------- the simulation loop + +// ISO/IEC 14443-4 block prologue. The low bit of an I-block PCB is the block +// number and has to be echoed back, or the reader reads our answer as a +// retransmission and stalls. +#define PCB_TYPE_MASK 0xC0 +#define PCB_TYPE_I 0x00 +#define PCB_TYPE_R 0x80 +#define PCB_TYPE_S 0xC0 +#define PCB_I_CHAINING 0x10 +#define PCB_BLOCKNUM 0x01 +#define PCB_CID_FOLLOWS 0x08 +#define PCB_NAD_FOLLOWS 0x04 +#define PCB_S_DESELECT 0xC2 + +// enough for a 2 byte ATQA: 9 bytes of modulation per byte, plus framing +#define ATQA_MODULATION_BUFFER_SIZE 32 + +void SimulateDesfireTag(void) { + + //------------------------------------------------------------------------- + // Get the bitstream in place before anything is allocated. iso14443a_setup() + // below would otherwise do it, and a bitstream download frees and clears + // BigBuf to get scratch space for the decompressor -- taking the emulator + // memory holding our card image and the precompiled anticollision answers + // with it. The pointers survive, the bytes behind them do not, and the tag + // then clocks out zeros. + //------------------------------------------------------------------------- + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); + + // keep emulator memory, that is where eload put the card image + BigBuf_free_keep_EM(); + + if (desfire_sim_init() == false) { + Dbprintf("No DESFire card image in emulator memory"); + Dbprintf("Load one with " _YELLOW_("`hf mfdes eload -f `")); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + + uint8_t uid[10] = {0}; + uint8_t uidlen = 0; + uint8_t atqa[2] = {0}; + uint8_t sak = 0; + uint8_t ats[20] = {0}; + uint8_t atslen = 0; + desfire_sim_identity(uid, &uidlen, atqa, &sak, ats, &atslen); + + uint16_t flags = FLAG_ATS_IN_DATA; + switch (uidlen) { + case 7: + flags |= FLAG_7B_UID_IN_DATA; + break; + case 10: + flags |= FLAG_10B_UID_IN_DATA; + break; + default: + Dbprintf("Card image has a %u byte UID, cannot simulate that", uidlen); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINVARG, NULL, 0); + return; + } + + tag_response_info_t *responses = NULL; + uint32_t cuid = 0; + uint8_t pages = 0; + + // tag type 3 gives the DESFire SAK and a DESFire shaped ATS; the ATS from + // the image replaces it because FLAG_ATS_IN_DATA is set + if (SimulateIso14443aInit(3, flags, uid, ats, atslen, &responses, &cuid, &pages, NULL) == false) { + BigBuf_free_keep_EM(); + reply_ng(CMD_HF_DESFIRE_SIMULATE, PM3_EINIT, NULL, 0); + return; + } + + // SimulateIso14443aInit() derives the ATQA from the tag type, so a 7 byte + // UID comes out 44 03 -- which is right for DESFire, but the image may say + // otherwise. Rebuild that one precompiled answer when it differs. + if ((atqa[0] || atqa[1]) && + (responses[RESP_INDEX_ATQA].response[0] != atqa[0] || + responses[RESP_INDEX_ATQA].response[1] != atqa[1])) { + + uint8_t *atqa_buf = BigBuf_calloc(ATQA_MODULATION_BUFFER_SIZE); + if (atqa_buf != NULL) { + + uint8_t *p = atqa_buf; + size_t avail = ATQA_MODULATION_BUFFER_SIZE; + + tag_response_info_t atqa_resp = { + .response = atqa, + .response_n = sizeof(atqa) + }; + + if (prepare_allocated_tag_modulation(&atqa_resp, &p, &avail)) { + responses[RESP_INDEX_ATQA] = atqa_resp; + } else { + Dbprintf(_RED_("Could not build the ATQA answer, using the default")); + } + } + } + + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + + uint8_t receivedCmd[MAX_FRAME_SIZE] = {0}; + uint8_t receivedCmdPar[MAX_PARITY_SIZE] = {0}; + uint8_t answer[DESFIRE_SIM_MAX_RESP + 8] = {0}; + + clear_trace(); + set_tracing(true); + LED_A_ON(); + + desfire_sim_print_banner(); + + int retval = PM3_SUCCESS; + uint32_t cmdcount = 0; + + for (;;) { + + WDT_HIT(); + + int len = 0; + if (GetIso14443aCommandFromReader(receivedCmd, sizeof(receivedCmd), receivedCmdPar, &len) == false) { + Dbprintf("Emulator stopped. Trace length: %d", BigBuf_get_traceLen()); + retval = PM3_EOPABORTED; + break; + } + + if (len <= 0) { + continue; + } + + cmdcount++; + + tag_response_info_t *p_response = NULL; + + // ---- activation, all precompiled ---- + if (receivedCmd[0] == ISO14443A_CMD_WUPA || receivedCmd[0] == ISO14443A_CMD_REQA) { + desfire_sim_reset(); // a fresh activation reselects the PICC + p_response = &responses[RESP_INDEX_ATQA]; + + } else if (len == 2 && receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { + p_response = &responses[RESP_INDEX_UIDC1]; + } else if (len == 2 && receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { + p_response = &responses[RESP_INDEX_UIDC2]; + } else if (len == 9 && receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { + p_response = &responses[RESP_INDEX_SAKC1]; + } else if (len == 9 && receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { + p_response = &responses[RESP_INDEX_SAKC2]; + } else if (receivedCmd[0] == ISO14443A_CMD_RATS && len == 4) { + p_response = &responses[RESP_INDEX_ATS]; + } else if (receivedCmd[0] == ISO14443A_CMD_PPS) { + p_response = &responses[RESP_INDEX_PPS]; + } else if (receivedCmd[0] == ISO14443A_CMD_HALT && len == 4) { + desfire_sim_reset(); + continue; // a halted tag says nothing + + // ---- ISO/IEC 14443-4 ---- + } else if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_S) { + + if (receivedCmd[0] == PCB_S_DESELECT) { + uint8_t r[3] = { PCB_S_DESELECT, 0, 0 }; + AddCrc14A(r, 1); + EmSendCmd(r, sizeof(r)); + desfire_sim_reset(); + } + continue; + + } else if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_R) { + + // R(ACK) is a retransmission request. We do not keep the previous + // answer, so acknowledge and move on. + uint8_t r[3] = { (uint8_t)(0xA2 | (receivedCmd[0] & PCB_BLOCKNUM)), 0, 0 }; + AddCrc14A(r, 1); + EmSendCmd(r, sizeof(r)); + continue; + + } else if ((receivedCmd[0] & PCB_TYPE_MASK) == PCB_TYPE_I) { + + uint8_t prologue = 1; + if (receivedCmd[0] & PCB_CID_FOLLOWS) { + prologue++; + } + if (receivedCmd[0] & PCB_NAD_FOLLOWS) { + prologue++; + } + + // prologue + at least a command byte + CRC + if (len < prologue + 1 + 2) { + continue; + } + + uint16_t n = desfire_sim_apdu(receivedCmd + prologue, len - prologue - 2, answer + prologue); + if (n == 0) { + continue; + } + + // echo the prologue back, block number included + memcpy(answer, receivedCmd, prologue); + answer[0] &= ~PCB_I_CHAINING; + + AddCrc14A(answer, prologue + n); + EmSendCmd(answer, prologue + n + 2); + continue; + + } else { + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("DESFire sim: unknown frame, %d bytes", len); + Dbhexdump(len, receivedCmd, false); + } + continue; + } + + EmSendPrecompiledCmd(p_response); + } + + switch_off(); + set_tracing(false); + BigBuf_free_keep_EM(); + + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("-[ commands received %u ]-", cmdcount); + } + + reply_ng(CMD_HF_DESFIRE_SIMULATE, retval, NULL, 0); +} diff --git a/armsrc/desfiresim.h b/armsrc/desfiresim.h index b3e88a8d1..ea06fb7a8 100644 --- a/armsrc/desfiresim.h +++ b/armsrc/desfiresim.h @@ -15,9 +15,11 @@ //----------------------------------------------------------------------------- // 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. +// Self contained: everything DESFire lives in desfiresim.c, including its own +// ISO 14443-A loop. It borrows the library helpers from iso14443a.c -- the +// precompiled activation answers, the receive call, the send calls -- but not +// SimulateIso14443aTag() itself, which is complicated enough without a DESFire +// state machine threaded through it. //----------------------------------------------------------------------------- #ifndef __DESFIRESIM_H @@ -25,39 +27,11 @@ #include "common.h" -// ISO 7816 wrapping of the DESFire command set: class byte on the way in, -// first status byte on the way back. -#define DESFIRE_SIM_ISO7816_CLA 0x90 -#define DESFIRE_SIM_ISO7816_SW1 0x91 - -// 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); +// Simulate the DESFire card image sitting in emulator memory, as put there by +// `hf mfdes eload`. Self contained: this owns its own ISO 14443-A loop rather +// 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); #endif // __DESFIRESIM_H diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 99d1d4763..9dff52cc4 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -18,7 +18,6 @@ // Routines to support ISO 14443 type A. //----------------------------------------------------------------------------- #include "iso14443a.h" -#include "desfiresim.h" #include "pm3_cmd.h" #include "string.h" @@ -1394,40 +1393,6 @@ 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) @@ -1605,16 +1570,6 @@ 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); @@ -1847,10 +1802,6 @@ 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 @@ -1919,10 +1870,6 @@ 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); @@ -2071,11 +2018,8 @@ 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) @@ -2556,46 +2500,8 @@ 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; - - // count answered DESFire commands, so `-n` can bound a - // simulation the way it does for the other tag types - numReads++; - if (exitAfterNReads > 0 && numReads >= exitAfterNReads) { - finished = true; - } - } - } - // ST25TA512B IKEA Rothult - } else if (tagType == 10) { + 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[] = { @@ -3082,6 +2988,7 @@ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { } } LastTimeProxToAirStart = ThisTransferTime + (correction_needed ? 8 : 0); + return PM3_SUCCESS; } @@ -4221,7 +4128,14 @@ int iso14443a_fast_select_card(const uint8_t *uid_ptr, uint8_t num_cascades) { void iso14443a_setup(uint8_t fpga_minor_mode) { set_session_channel(false); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + + // keep_EM: a bitstream download frees and clears BigBuf to get scratch space + // for the decompressor, and the plain FpgaDownloadAndGo() takes the emulator + // memory with it. Every 14a command comes through here, so a card image that + // `eload` had just put in place was destroyed by the next `hf 14a` command + // whenever the HF bitstream was not already resident. The decompressor still + // has BigBuf below the emulator memory to work in. + FpgaDownloadAndGo_keep_EM(FPGA_BITSTREAM_HF); // Set up the synchronous serial port FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A); // connect Demodulated Signal to ADC: diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index a021d0b80..453d17560 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 (card image from `hf mfdes eload`)\n" + "hf 14a sim -t 3 -> MIFARE Desfire\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 19a843192..bb7ba778e 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -9092,44 +9092,18 @@ 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" - "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"); + "hf mfdes sim"); 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)); + SendCommandNG(CMD_HF_DESFIRE_SIMULATE, NULL, 0); PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort simulation"); @@ -9139,13 +9113,13 @@ static int CmdHF14ADesSim(const char *Cmd) { keypress = kbd_enter_pressed(); - if (WaitForResponseTimeout(CMD_HF_MIFARE_SIMULATE, &resp, 1500) == false) { + if (WaitForResponseTimeout(CMD_HF_DESFIRE_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 `")); + PrintAndLogEx(WARNING, "Simulation stopped, no card image in emulator memory?"); + PrintAndLogEx(HINT, "Hint: load one with " _YELLOW_("`hf mfdes eload -f `")); return resp.status; } break; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index ece62e3a1..e0ea7587d 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -1187,6 +1187,7 @@ typedef struct { #define CMD_HF_DESFIRE_READER 0x072c #define CMD_HF_DESFIRE_INFO 0x072d #define CMD_HF_DESFIRE_COMMAND 0x072e +#define CMD_HF_DESFIRE_SIMULATE 0x072f #define CMD_HF_MIFARE_NACK_DETECT 0x0730 #define CMD_HF_MIFARE_STATIC_NONCE 0x0731