From f3e169652a9e352b6c8c590c5d4658c7135d5783 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 15 Sep 2026 23:48:42 +0200 Subject: [PATCH] hf mfdes sim: chain an enciphered read instead of refusing it An enciphered read longer than one frame was answered with 91 7E, because the CRC32 covers the whole read and the code could only build that in one piece. It is one CBC run over the file data, a CRC32 behind it and zero padding, split across frames with the init vector carried from one to the next -- "if the commands are queued due to a very long data stream, the init vector for the decipherment is always updated" (M134034 7.3.7). So each frame only has to carry whole blocks, which the 96 byte chunk and the padded total both are, and the reader joins the ciphertext and deciphers the lot in one go. The read now walks a stream rather than a file extent: bytes come from the file while they last, then the CRC32, then padding. The CRC is taken up front, over the data and the status byte the last frame will carry, so it has to be built a piece at a time -- the status byte is not in the card image and the data can be a whole file, which rules out crc32_ex() and its single buffer. common/crc.h already has an incremental CRC, the one legicrf.c uses, so that is what this uses: crc_update() shifts LSB first, so the polynomial goes in already reflected with neither reflect flag set. Those parameters were checked against crc32_ex() over every length from 0 to 200 before being used. Tested against the simulation with a 128 byte file created through the reader in Full communication mode with all rights on key 0, so the file's mode actually applies rather than being forced plain by a free access right. Reads of 64, 96, 112 and 128 bytes all verify, the last three over two frames, and the content comes back as written. A wrong init vector or a wrong CRC would have failed the client's CRC32 check rather than passed quietly. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 3 ++ armsrc/desfiresim.c | 90 ++++++++++++++++++++++++++++++++--------- client/src/cmdhfmfdes.c | 67 ++++++++++++++++++++++++++++-- 3 files changed, 136 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e7fc23674..0971b5438 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ 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 mfdes detect` - the same cipher is no longer sent to the card twice, cutting a PICC level scan with the bundled dictionary from 99 authentications to 63 (@iceman1001) +- Changed `hf mfdes detect` - a single key number is printed as one value instead of a range of one, so a PICC level scan reads `key num 0x00` (@iceman1001) +- Fixed `hf mfdes sim` - an enciphered read longer than one frame is chained instead of refused, the init vector carrying from frame to frame (@iceman1001) - Fixed `lf read` - a realtime read no longer ends early when the host falls behind, and the device no longer goes silent until it is replugged (@iceman1001) - Fixed `lf read` - a realtime read ending on a full USB packet now delivers its last 64 bytes, an odd packet count was silently one packet short (@iceman1001) - Fixed `lf read` - a transfer that stops short says so, instead of being presented as a complete read (@iceman1001) diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c index 026d80fc8..392f86925 100644 --- a/armsrc/desfiresim.c +++ b/armsrc/desfiresim.c @@ -56,6 +56,7 @@ #include "iso14443a.h" #include "crc16.h" #include "crc32.h" +#include "crc.h" #include "commonutil.h" #include "fpga_apis.h" #include "fpga_loader.h" @@ -65,6 +66,8 @@ #include "desfire_em.h" #include "desfire_crypto.h" +#define DESFIRE_CRC32_POLY 0xEDB88320 + // 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 @@ -100,9 +103,12 @@ typedef struct { // file, and the mode the first frame settled on -- the access rights are // evaluated once, when the command arrives, not again per frame. int16_t chain_file; // index into files[], -1 when none - uint32_t chain_off; // next byte or record to send - uint32_t chain_end; // one past the last + uint32_t chain_base; // where the read starts inside the file + uint32_t chain_datalen; // how many bytes of it the reader asked for + uint32_t chain_off; // position in the stream being handed out + uint32_t chain_end; // its total length uint8_t chain_comm; // effective comm mode for the whole transfer + uint8_t chain_crc[4]; // CRC32 of an enciphered read, computed up front // ---- authentication // auth_cmd is the handshake in flight, 0 when none. The second frame @@ -920,6 +926,7 @@ static bool desfire_sim_unwrap(desfire_sim_state_t *st, uint8_t cmd, uint8_t com // ------------------------------------------------------------------- files + // Find a live file by its file number within the selected application. static const desfire_em_file_t *desfire_sim_find_file(const desfire_sim_state_t *st, uint8_t fileno) { @@ -948,21 +955,12 @@ static int16_t desfire_sim_file_index(const desfire_sim_state_t *st, const desfi static uint16_t desfire_sim_read_chunk(desfire_sim_state_t *st, uint8_t *out) { const desfire_em_file_t *f = &st->files[st->chain_file]; + const uint8_t *data = st->base + f->dataoff + st->chain_base; uint32_t left = st->chain_end - st->chain_off; uint32_t n = (left > DESFIRE_SIM_READ_CHUNK) ? DESFIRE_SIM_READ_CHUNK : left; - // An enciphered transfer is one CRC over the whole read, so it cannot be - // split across frames the way a plain one can. Everything this simulation - // serves fits a frame, so a read that does not is refused rather than - // answered wrongly. - if (st->chain_comm == DESFIRE_SIM_COMM_FULL && left > DESFIRE_SIM_READ_CHUNK) { - st->chain_cmd = 0; - st->chain_file = -1; - return desfire_sim_status(out, MFDES_E_LENGTH); - } - - const uint8_t *src = st->base + f->dataoff + st->chain_off; + uint32_t at = st->chain_off; st->chain_off += n; bool more = (st->chain_off < st->chain_end); @@ -972,11 +970,32 @@ static uint16_t desfire_sim_read_chunk(desfire_sim_state_t *st, uint8_t *out) { st->chain_file = -1; } - if (st->chain_comm == DESFIRE_SIM_COMM_FULL) { - return desfire_sim_enciphered(st, out, MFDES_S_OPERATION_OK, src, n); + if (st->chain_comm != DESFIRE_SIM_COMM_FULL) { + return desfire_sim_chained(st, out, more, data + at, n); } - return desfire_sim_chained(st, out, more, src, n); + // An enciphered read is one CBC run over the file data, a CRC32 behind it + // and zero padding, split across frames with the init vector carried from + // one to the next -- "if the commands are queued due to a very long data + // stream, the init vector for the decipherment is always updated" (M134034 7.3.7). + uint8_t plain[DESFIRE_SIM_READ_CHUNK] = {0}; + + for (uint32_t i = 0; i < n; i++) { + + uint32_t p = at + i; + + if (p < st->chain_datalen) { + plain[i] = data[p]; + } else if (p < st->chain_datalen + 4) { + plain[i] = st->chain_crc[p - st->chain_datalen]; + } else { + plain[i] = 0x00; + } + } + + out[0] = more ? MFDES_ADDITIONAL_FRAME : MFDES_S_OPERATION_OK; + desfire_sim_crypt(&st->sesskey, plain, out + 1, n, st->iv, true); + return n + 1; } // Set up a data or record read and answer its first frame. `unit` is 1 for a @@ -1008,16 +1027,47 @@ static uint16_t desfire_sim_read_start(desfire_sim_state_t *st, const desfire_em st->chain_cmd = MFDES_READ_DATA; st->chain_file = desfire_sim_file_index(st, f); - st->chain_off = off * unit; - st->chain_end = (off + len) * unit; + st->chain_base = off * unit; + st->chain_datalen = len * unit; + st->chain_off = 0; st->chain_comm = comm; // the command CMAC has already been taken and its result discarded, so the // running state starts empty for the response half desfire_sim_cmac_reset(st); - if (st->chain_end > f->datalen) { - st->chain_end = f->datalen; + if (st->chain_base + st->chain_datalen > f->datalen) { + st->chain_datalen = (f->datalen > st->chain_base) ? (f->datalen - st->chain_base) : 0; + } + + st->chain_end = st->chain_datalen; + + if (comm == DESFIRE_SIM_COMM_FULL) { + + size_t kbs = key_block_size(&st->sesskey); + if (kbs == 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + + // The CRC32 covers the data and the status byte the last frame will + // carry, so it is taken now and fed out with the rest of the stream. + const uint8_t *data = st->base + f->dataoff + st->chain_base; + + crc_t crc; + crc_init_ref(&crc, 32, DESFIRE_CRC32_POLY, 0xFFFFFFFF, 0, false, false); + + for (uint32_t i = 0; i < st->chain_datalen; i++) { + crc_update(&crc, data[i], 8); + } + crc_update(&crc, MFDES_S_OPERATION_OK, 8); + + uint32_t v = crc_finish(&crc); + st->chain_crc[0] = v & 0xFF; + st->chain_crc[1] = (v >> 8) & 0xFF; + st->chain_crc[2] = (v >> 16) & 0xFF; + st->chain_crc[3] = (v >> 24) & 0xFF; + + st->chain_end = padded_data_length(st->chain_datalen + 4, kbs); } return desfire_sim_read_chunk(st, out); diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 9bbfe6d15..2417483b2 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -56,6 +56,10 @@ #include "util.h" #include "crypto/originality.h" +// How many distinct candidates `hf mfdes detect` remembers per key number so it +// does not send the same cipher to the card twice. +#define MFDES_DETECT_TRIED_MAX 256 + #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 // how many errors in a row from the card before we give up on a key number @@ -2195,10 +2199,16 @@ static int CmdHF14aDesDetect(const char *Cmd) { snprintf(algostr, sizeof(algostr), "unknown"); } - PrintAndLogEx(INFO, "%s... key num " _YELLOW_("0x%02x") ".." _YELLOW_("0x%02x") ", algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), + char keynostr[32] = {0}; + if (keynofirst == keynolast) { + snprintf(keynostr, sizeof(keynostr), _YELLOW_("0x%02x"), keynofirst); + } else { + snprintf(keynostr, sizeof(keynostr), _YELLOW_("0x%02x") ".." _YELLOW_("0x%02x"), keynofirst, keynolast); + } + + PrintAndLogEx(INFO, "%s... key num %s, algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), (DesfireMFSelected(selectway, id)) ? "PICC level" : DesfireWayIDStr(selectway, id), - keynofirst, - keynolast, + keynostr, algostr, CLIGetOptionListStr(DesfireSecureChannelOpts, securechann) ); @@ -2225,6 +2235,9 @@ static int CmdHF14aDesDetect(const char *Cmd) { dctx.keyNum = keyno; bool found = false; + uint8_t tried[MFDES_DETECT_TRIED_MAX][1 + DESFIRE_MAX_KEY_SIZE] = {0}; + uint16_t triedcount = 0; + uint32_t skipped = 0; // for key types for (uint8_t ktype = T_DES; ktype <= T_AES && found == false; ktype++) { @@ -2258,7 +2271,48 @@ static int CmdHF14aDesDetect(const char *Cmd) { for (uint32_t i = 0; i < keyListLen; i++) { - res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); + uint8_t *candidate = &keyList[i * keylen]; + + // fingerprint: the cipher this key really drives + uint8_t fp[1 + DESFIRE_MAX_KEY_SIZE] = {0}; + uint8_t fplen; + + if (dctx.keyType == T_DES || + ( + (dctx.keyType == T_3DES) && + (keylen == 16) && + (memcmp(candidate, candidate + 8, 8) == 0) + )) { + + fp[0] = T_DES; // single DES, however it was written + memcpy(fp + 1, candidate, 8); + fplen = 1 + 8; + + } else { + fp[0] = dctx.keyType; + memcpy(fp + 1, candidate, keylen); + fplen = 1 + keylen; + } + + bool already = false; + for (uint16_t d = 0; d < triedcount; d++) { + if (memcmp(tried[d], fp, fplen) == 0) { + already = true; + break; + } + } + + if (already) { + skipped++; + continue; + } + + if (triedcount < MFDES_DETECT_TRIED_MAX) { + memcpy(tried[triedcount], fp, sizeof(fp)); + triedcount++; + } + + res = DesfireAuthCheck(&dctx, selectway, id, securechann, candidate); if (res == PM3_SUCCESS) { found = true; break; // all the params already in the dctx @@ -2298,6 +2352,11 @@ static int CmdHF14aDesDetect(const char *Cmd) { } } + if (verbose && skipped) { + PrintAndLogEx(INFO, "Skipped %u authentication%s the card had already been sent", + skipped, (skipped == 1) ? "" : "s"); + } + if (found) { foundcount++;