From 31d05aef5384d45db65b6443d027cb4f538b373a Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 15 Sep 2026 21:15:41 +0200 Subject: [PATCH] hf mfdes: ChangeFileSettings, and an esave option to keep what was deleted ChangeFileSettings is answered by the simulation now. Which form it takes is decided by the file's own "change access rights" right, not by the reader: never refuses the command outright, free means the settings arrive as plain text with no security mechanism at all, and anything else names the key that has to be authenticated and the settings arrive enciphered under it (M134034 9.5.4). That enciphered form is the first command whose parameters the reader secured rather than the card, so it shares the unwrapping the writes use: the file number stays in the clear, the rest is one CBC run under the session key, and the CRC32 behind the plaintext is checked before anything is changed. A command that unwraps its own parameters also has to be kept away from the blanket command CMAC, or the IV moves twice. Tested against the simulation: a file whose change right is free goes from rights eeee to 1234 with no session at all, a file whose change right is key 0 goes from 1200 to 3210 authenticated and enciphered, and a file whose change right has been set to F refuses every later change and keeps its settings, which is the point of that value. Separately, `hf mfdes esave` grew a `--keep` flag. A deleted application or file stays in the card image as a tombstone, because the memory it held stays spent until a FormatPICC, and esave was writing those out as though they still existed. They are now left out by default, so a dump is the card as a reader sees it, and `--keep` puts them back for when what a reader did is the interesting part rather than the result it left. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 3 + armsrc/desfiresim.c | 357 +++++++++++++++++++++++++++++++++- client/src/cmdhfmfdes.c | 13 +- client/src/mifare/desfireem.c | 54 ++++- client/src/mifare/desfireem.h | 5 + 5 files changed, 424 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb807509c..341e6e1b3 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] +- Added `hf mfdes sim` - ChangeFileSettings is answered, plain when the change access right is free and enciphered under the key it names otherwise (@iceman1001) +- Added `hf mfdes esave` - `--keep` saves applications and files a reader deleted, which are otherwise left out so the dump is the card as a reader sees it (@iceman1001) +- Added `hf mfdes sim` - CreateFile in all five EV1 flavours and DeleteFile are answered, so a reader can lay out an application's file system on the simulated card (@iceman1001) - Added `hf mfdes sim` - CreateApplication and DeleteApplication are answered, so a reader can add and remove applications on the simulated card (@iceman1001) - Added `hf mfdes sim` - FormatPICC is answered, releasing every application and file and handing the memory back, with the PICC master key and its settings kept (@iceman1001) - Fixed `hf mfdes esave` - the ATS was saved as zeros, a `sizeof()` of the 256 byte destination cast to uint8_t wrapped to 0 and the copy was skipped while its length was still reported (@iceman1001) diff --git a/armsrc/desfiresim.c b/armsrc/desfiresim.c index 65d6cc7e1..e9974b5b4 100644 --- a/armsrc/desfiresim.c +++ b/armsrc/desfiresim.c @@ -785,6 +785,7 @@ static uint8_t desfire_sim_hdrlen(uint8_t cmd) { case MFDES_DEBIT: case MFDES_LIMITED_CREDIT: case MFDES_GET_VALUE: + case MFDES_CHANGE_FILE_SETTINGS: return 1; // file number only default: return 0; @@ -817,6 +818,13 @@ static bool desfire_sim_cmd_is_write(uint8_t cmd) { return (desfire_sim_cmd_macs_request(cmd)); } +// The writes gather across frames; ChangeFileSettings arrives whole but is +// enciphered, and either way the command's own handler does the unwrapping and +// moves the IV along, so the blanket CMAC has to keep its hands off. +static bool desfire_sim_cmd_unwraps_own(uint8_t cmd) { + return (desfire_sim_cmd_is_write(cmd) || cmd == MFDES_CHANGE_FILE_SETTINGS); +} + // Take the reader's secure messaging off a gathered command. // // `buf`/`len` is the command's parameters as they arrived, header included and @@ -1135,6 +1143,151 @@ static uint16_t desfire_sim_dfname_record(const desfire_sim_state_t *st, uint8_t return 0; } +// ------------------------------------------------------------ file creation + +// Bytes the committed region of a file occupies, before any shadow. The same +// accounting eload uses, so an image a reader has added files to still agrees +// with itself. +static uint32_t desfire_sim_file_extent(uint8_t type, uint32_t size, + uint32_t recsize, uint32_t maxrec) { + + switch (type) { + case 0x00: + case 0x01: + return size; + case 0x02: + // the payload is a 4 byte value, but it is allocated and shadowed + // like anything else, so it gets a whole granule + return DESFIRE_EM_GRANULE; + case 0x03: + case 0x04: + // the declared extent, not the records that happen to exist, so + // WriteRecord never has to grow anything + return recsize * maxrec; + default: + return 0; + } +} + +// CommitTransaction covers everything but a standard data file, and what it +// covers needs a shadow region to write into -- EV1 9.6.10. +static bool desfire_sim_type_has_shadow(uint8_t type) { + return (type == 0x01 || type == 0x02 || type == 0x03 || type == 0x04); +} + +// Add a file to the selected application. +// +// The file table sits between the application table and the key table, so a new +// entry goes in where the key table starts and the keys move up by one entry. +// The file's data is taken off the other end, from the region growing down. +// +// Returns a DESFire status byte. +static uint8_t desfire_sim_file_create(desfire_sim_state_t *st, uint8_t fileno, uint8_t type, + uint8_t comm, uint16_t rights, uint16_t isofid, + uint32_t size, uint32_t recsize, uint32_t maxrec, + uint32_t lower, uint32_t upper, uint32_t value, + uint8_t options) { + + uint8_t *base = desfire_sim_wbase(); + desfire_em_hdr_t *hdr = (desfire_em_hdr_t *)base; + + if (st->selected == 0) { + return MFDES_E_PERMISSION_DENIED; + } + + if (fileno > 0x1F) { + return MFDES_E_PARAMETER_ERROR; + } + + if (hdr->filecount >= DESFIRE_EM_MAX_FILES) { + return MFDES_E_OUT_OF_EEPROM; + } + + if (desfire_sim_find_file(st, fileno) != NULL) { + return MFDES_E_DUPLICATE; + } + + uint32_t extent = DESFIRE_EM_ROUNDUP(desfire_sim_file_extent(type, size, recsize, maxrec)); + if (extent == 0) { + return MFDES_E_PARAMETER_ERROR; + } + + uint32_t reserve = desfire_sim_type_has_shadow(type) ? (extent * 2) : extent; + + if ((uint32_t)hdr->reserved + reserve > hdr->cardsize) { + return MFDES_E_OUT_OF_EEPROM; + } + + // the tables grow up and the file data grows down, and an allocation only + // has to leave the two apart -- here both move at once + uint32_t grow = sizeof(desfire_em_file_t); + if ((uint32_t)hdr->tables_end + grow + reserve > hdr->data_start) { + return MFDES_E_OUT_OF_EEPROM; + } + + // open a gap where the key table starts + uint16_t at = hdr->key_off; + memmove(base + at + grow, base + at, hdr->tables_end - at); + + desfire_em_file_t *f = (desfire_em_file_t *)(base + at); + memset(f, 0, sizeof(*f)); + f->app = st->selected; + f->num = fileno; + f->type = type; + f->flags = comm & DESFIRE_EM_FILE_COMM_MASK; + f->rights = rights; + f->isofid = isofid; + + hdr->key_off += grow; + hdr->tables_end += grow; + + // and take the data off the far end + hdr->data_start -= reserve; + hdr->reserved += reserve; + + f->dataoff = hdr->data_start; + f->datalen = extent; + f->shadow_off = desfire_sim_type_has_shadow(type) ? (hdr->data_start + extent) : 0; + + // a new file reads back as zeros, which is a fact about it rather than a + // gap in the dump, so it is not marked unknown + memset(base + hdr->data_start, 0, reserve); + + switch (type) { + case 0x00: + case 0x01: + f->u.data.size = size; + break; + case 0x02: + f->u.value.lower = lower; + f->u.value.upper = upper; + f->u.value.value = value; + if (options & 0x01) { + f->flags |= DESFIRE_EM_FILE_LIMCREDIT; + } + if (options & 0x02) { + f->flags |= DESFIRE_EM_FILE_FREEGETVAL; + } + break; + case 0x03: + case 0x04: + f->u.record.recordsize = recsize; + f->u.record.maxrecords = maxrec; + f->u.record.currecords = 0; + break; + default: + break; + } + + hdr->filecount++; + + // the key table moved, so the parsed view has to be taken again + int selected = st->selected; + desfire_sim_load(st); + st->selected = selected; + return MFDES_S_OPERATION_OK; +} + // ------------------------------------------------------- applications // Room the card charges for an application: the application itself plus its @@ -1543,7 +1696,7 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const // so it is left to the auth, read and write paths that own the chain. if (cmd != MFDES_AUTHENTICATE && cmd != MFDES_AUTHENTICATE_ISO && cmd != MFDES_AUTHENTICATE_AES && cmd != MFDES_ADDITIONAL_FRAME && - st->auth_cmd == 0 && desfire_sim_cmd_is_write(cmd) == false && st->wcmd == 0) { + st->auth_cmd == 0 && desfire_sim_cmd_unwraps_own(cmd) == false && st->wcmd == 0) { desfire_sim_cmac_command(st, cmd, in, inlen); } @@ -1905,6 +2058,208 @@ static uint16_t desfire_sim_command(desfire_sim_state_t *st, uint8_t cmd, const case MFDES_LIMITED_CREDIT: return desfire_sim_write_gather(st, cmd, in, inlen, out); + case MFDES_CREATE_STD_DATA_FILE: + case MFDES_CREATE_BACKUP_DATA_FILE: + case MFDES_CREATE_VALUE_FILE: + case MFDES_CREATE_LINEAR_RECORD_FILE: + case MFDES_CREATE_CYCLIC_RECORD_FILE: { + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_app_t *app = &st->apps[st->selected]; + + // application key settings bit 2 clear means create and delete need + // the application master key (M134034 9.3.4) + if ((app->keysettings & 0x04) == 0) { + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + } + + // the ISO file id is only on the wire when the application was + // created with ISO file ids enabled + bool isofids = (app->flags & DESFIRE_EM_APP_ISOFIDS) != 0; + uint8_t type; + uint8_t need; + + switch (cmd) { + case MFDES_CREATE_STD_DATA_FILE: + type = 0x00; + need = isofids ? 9 : 7; + break; + case MFDES_CREATE_BACKUP_DATA_FILE: + type = 0x01; + need = isofids ? 9 : 7; + break; + case MFDES_CREATE_VALUE_FILE: + type = 0x02; + need = 17; // never carries an ISO file id + break; + case MFDES_CREATE_LINEAR_RECORD_FILE: + type = 0x03; + need = isofids ? 12 : 10; + break; + default: + type = 0x04; + need = isofids ? 12 : 10; + break; + } + + // every one of these is fixed length, so a frame that is not + // exactly the expected size is rejected rather than parsed from the + // wrong offset -- a reader that sends an ISO file id to an + // application that does not use them lands here + if (inlen != need) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + uint8_t fileno = in[0]; + uint16_t isofid = 0; + const uint8_t *p = in + 1; + + if (isofids && type != 0x02) { + isofid = p[0] | (p[1] << 8); + p += 2; + } + + uint8_t comm = p[0]; + uint16_t rights = p[1] | (p[2] << 8); + p += 3; + + uint32_t size = 0, recsize = 0, maxrec = 0; + uint32_t lower = 0, upper = 0, value = 0; + uint8_t options = 0; + + if (type == 0x00 || type == 0x01) { + + size = p[0] | (p[1] << 8) | (p[2] << 16); + + } else if (type == 0x02) { + + lower = p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24); + upper = p[4] | (p[5] << 8) | (p[6] << 16) | ((uint32_t)p[7] << 24); + value = p[8] | (p[9] << 8) | (p[10] << 16) | ((uint32_t)p[11] << 24); + options = p[12]; + + // "The upper limit has to be higher than the lower limit, + // otherwise an error message would be sent by the PICC and thus + // the file would not be created" -- M134034 9.5.7, and the + // initial value has to sit between the two + if ((int32_t)upper <= (int32_t)lower || + (int32_t)value < (int32_t)lower || (int32_t)value > (int32_t)upper) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + + } else { + + recsize = p[0] | (p[1] << 8) | (p[2] << 16); + maxrec = p[3] | (p[4] << 8) | (p[5] << 16); + + if (recsize == 0 || maxrec == 0) { + return desfire_sim_status(out, MFDES_E_PARAMETER_ERROR); + } + } + + uint8_t res = desfire_sim_file_create(st, fileno, type, comm, rights, isofid, + size, recsize, maxrec, lower, upper, value, options); + if (res != MFDES_S_OPERATION_OK) { + return desfire_sim_status(out, res); + } + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_CHANGE_FILE_SETTINGS: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + uint8_t change = DESFIRE_SIM_AR_CHANGE(f->rights); + + // "This change only succeeds if the current Access Rights for + // Change Access Rights is different from never" -- M134034 9.5.4 + if (change == DESFIRE_SIM_AR_DENY) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + // "However, if the ChangeAccessRights Access Rights is set with the + // value free, no security mechanism is necessary and therefore the + // data is sent as plain text (5 byte overall length)." Otherwise it + // is enciphered under the key that right names. + uint8_t comm; + if (change == DESFIRE_SIM_AR_FREE) { + comm = DESFIRE_SIM_COMM_PLAIN; + } else { + if (st->authenticated == false || st->auth_keyno != change) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + comm = DESFIRE_SIM_COMM_FULL; + } + + uint8_t buf[DESFIRE_SIM_WRITE_MAX] = {0}; + if (inlen > sizeof(buf)) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + memcpy(buf, in, inlen); + uint16_t len = inlen; + + if (desfire_sim_unwrap(st, cmd, comm, buf, &len) == false) { + desfire_sim_auth_clear(st); + return desfire_sim_status(out, MFDES_E_INTEGRITY_ERROR); + } + + // file number, the new communication settings, then the new rights + if (len < 4) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + desfire_em_file_t *w = (desfire_em_file_t *)f; + w->flags = (w->flags & ~DESFIRE_EM_FILE_COMM_MASK) | (buf[1] & DESFIRE_EM_FILE_COMM_MASK); + w->rights = buf[2] | (buf[3] << 8); + + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + + case MFDES_DELETE_FILE: { + + if (inlen < 1) { + return desfire_sim_status(out, MFDES_E_LENGTH); + } + + if (st->selected == 0) { + return desfire_sim_status(out, MFDES_E_PERMISSION_DENIED); + } + + const desfire_em_app_t *app = &st->apps[st->selected]; + if ((app->keysettings & 0x04) == 0) { + if (st->authenticated == false || st->auth_keyno != 0) { + return desfire_sim_status(out, MFDES_E_AUTHENTICATION_ERROR); + } + } + + const desfire_em_file_t *f = desfire_sim_find_file(st, in[0]); + if (f == NULL) { + return desfire_sim_status(out, MFDES_E_FILE_NOT_FOUND); + } + + // a tombstone, like DeleteApplication: the memory stays spent and + // only FormatPICC hands it back + ((desfire_em_file_t *)f)->flags |= DESFIRE_EM_FILE_DELETED; + return desfire_sim_maced(st, out, MFDES_S_OPERATION_OK, NULL, 0); + } + case MFDES_CREATE_APPLICATION: { // "This command requires that the currently selected AID is diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index bb7ba778e..9bbfe6d15 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -9223,13 +9223,19 @@ static int CmdHF14ADesESave(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes esave", "Save the card image in emulator memory to a dump file.\n" - "Shows what a reader left behind if one has been talking to the simulation", - "hf mfdes esave -f myfile"); + "Shows what a reader left behind if one has been talking to the simulation.\n" + "A deleted application or file is kept in the image as a tombstone, because the\n" + "memory it held stays spent until a FormatPICC. By default those are left out, so\n" + "the dump is the card as a reader sees it. Use `--keep` to save them as well, which\n" + "is what you want to see everything a reader did rather than only the result", + "hf mfdes esave -f myfile\n" + "hf mfdes esave -f myfile --keep -> keep applications and files a reader deleted"); void *argtable[] = { arg_param_begin, arg_str0("f", "file", "", "Filename, if no UID will be used as filename"), arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "keep", "Keep applications and files that were deleted"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -9238,6 +9244,7 @@ static int CmdHF14ADesESave(const char *Cmd) { char filename[FILE_PATH_SIZE] = {0}; CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); bool verbose = arg_get_lit(ctx, 2); + bool keep_deleted = arg_get_lit(ctx, 3); CLIParserFree(ctx); size_t emsize = g_conn.em_size; @@ -9269,7 +9276,7 @@ static int CmdHF14ADesESave(const char *Cmd) { return PM3_EMALLOC; } - res = desfire_em_unpack(img, emsize, dump); + res = desfire_em_unpack_ex(img, emsize, dump, keep_deleted); free(img); if (res != PM3_SUCCESS) { diff --git a/client/src/mifare/desfireem.c b/client/src/mifare/desfireem.c index 7c0964408..2d45b31b6 100644 --- a/client/src/mifare/desfireem.c +++ b/client/src/mifare/desfireem.c @@ -431,6 +431,10 @@ int desfire_em_pack(const desfire_dump_t *dump, uint8_t *out, size_t outlen, siz } int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump) { + return desfire_em_unpack_ex(img, imglen, dump, false); +} + +int desfire_em_unpack_ex(const uint8_t *img, size_t imglen, desfire_dump_t *dump, bool keep_deleted) { if (img == NULL || dump == NULL || imglen < sizeof(desfire_em_hdr_t)) { return PM3_EINVARG; @@ -491,13 +495,39 @@ int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump) { return PM3_EINVARG; } - dump->appcount = hdr->appcount - 1; // app[0] is the PICC + // A deleted application or file is a tombstone in the image, so the memory + // it held stays spent, but it is gone as far as a reader is concerned and it + // does not belong in a dump of the card. Applications are therefore packed + // down as they are copied out, and appmap carries image index -> dump index + // so the key and file tables, which refer to applications by image index, + // can follow. + int appmap[DESFIRE_EM_MAX_APPS + 1]; + for (uint16_t i = 0; i < ARRAYLEN(appmap); i++) { + appmap[i] = -1; + } + + dump->appcount = 0; for (uint8_t i = 0; i < hdr->appcount; i++) { - desfire_dump_app_t *a = (i == 0) ? &dump->picc : &dump->app[i - 1]; const desfire_em_app_t *s = &apps[i]; + if (i > 0 && (s->flags & DESFIRE_EM_APP_DELETED) && (keep_deleted == false)) { + continue; + } + + desfire_dump_app_t *a; + if (i == 0) { + a = &dump->picc; // app[0] is the PICC, never deleted + } else { + if (dump->appcount >= DESFIRE_MAX_APP_COUNT) { + continue; + } + a = &dump->app[dump->appcount]; + appmap[i] = dump->appcount; + dump->appcount++; + } + a->aid = s->aid[0] | (s->aid[1] << 8) | (s->aid[2] << 16); a->isofid = s->isofid; a->keysettings = s->keysettings; @@ -517,7 +547,15 @@ int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump) { continue; } - desfire_dump_app_t *a = (s->app == 0) ? &dump->picc : &dump->app[s->app - 1]; + desfire_dump_app_t *a; + if (s->app == 0) { + a = &dump->picc; + } else { + if (appmap[s->app] < 0) { + continue; // its application was deleted + } + a = &dump->app[appmap[s->app]]; + } if (s->flags & DESFIRE_EM_KEY_VERKNOWN) { a->keys.versionknown[s->num] = 1; @@ -537,7 +575,15 @@ int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump) { continue; } - desfire_dump_app_t *a = &dump->app[s->app - 1]; + if ((s->flags & DESFIRE_EM_FILE_DELETED) && (keep_deleted == false)) { + continue; + } + + if (appmap[s->app] < 0) { + continue; // its application was deleted + } + + desfire_dump_app_t *a = &dump->app[appmap[s->app]]; if (a->filecount >= DESFIRE_MAX_FILE_COUNT) { continue; } diff --git a/client/src/mifare/desfireem.h b/client/src/mifare/desfireem.h index e1a74cf3a..fddde4b06 100644 --- a/client/src/mifare/desfireem.h +++ b/client/src/mifare/desfireem.h @@ -48,6 +48,11 @@ int desfire_em_pack(const desfire_dump_t *dump, uint8_t *out, size_t outlen, siz // Walk an image back into a desfire_dump_t. The caller owns the per-file heap // buffers afterwards and must release them with desfire_dump_free(). +// Unpack a card image into a dump. A deleted application or file is a tombstone +// in the image: the memory it held stays spent, but it is gone as far as a +// reader is concerned. `keep_deleted` decides which of those two views you get +// -- false for the card as a reader sees it, true to keep what was there. +int desfire_em_unpack_ex(const uint8_t *img, size_t imglen, desfire_dump_t *dump, bool keep_deleted); int desfire_em_unpack(const uint8_t *img, size_t imglen, desfire_dump_t *dump); // Print an image's structure. Does not need a device.