From 66dbf6ac5ca2c5c3b8ade36f8fae4eed67a158da Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 09:03:57 +0200 Subject: [PATCH 1/5] update --- doc/mfdes_dump_format.md | 397 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 378 insertions(+), 19 deletions(-) diff --git a/doc/mfdes_dump_format.md b/doc/mfdes_dump_format.md index dd44e3975..bd6520954 100644 --- a/doc/mfdes_dump_format.md +++ b/doc/mfdes_dump_format.md @@ -25,6 +25,11 @@ built on. - [Keys](#keys) - [The Read flag](#the-read-flag) - [Token spellings](#token-spellings) +- [A complete example](#a-complete-example) + - [The card](#the-card) + - [The key file](#the-key-file) + - [The dump file](#the-dump-file) + - [What `hf mfdes view` makes of it](#what-hf-mfdes-view-makes-of-it) - [In-memory representation](#in-memory-representation) - [Not in v1](#not-in-v1) @@ -40,6 +45,10 @@ hf mfdes dump -f myfile save under a name of your choosing hf mfdes view -f print a dump file, no device needed ``` +With no `--keys`, the dump looks for `hf-mfdes--keys.json` by itself, so a +`hf mfdes chk -j hf-mfdes--keys` run is picked up on the next dump without +naming the file again. + With no `--aid` / `--isoid` / `--dfname` the command walks every application the PICC lists. The default filename is `hf-mfdes--dump.json`; only json is written, there is no `.bin` companion. @@ -74,22 +83,35 @@ Everything under `$.Card` describes the PICC itself. | `Version` | hex, 28 bytes | raw `GetVersion` answer, hardware + software + production details concatenated | | `Signature` | hex, 56 bytes | NXP originality signature, absent when the card refused it | | `FreeMem` | int | bytes reported by `GetFreeMem`, absent when the card refused it | -| `KeySettings` | hex, 1 byte | PICC master key settings | -| `NumKeysRaw` | hex, 1 byte | raw key-count byte, carries the key type in the top bits | -| `NumKeys` | int | key count decoded from `NumKeysRaw` | -| `KeyVersion0` | hex, 1 byte | version of the PICC master key | -| `Keys` | object | see [Keys](#keys) | Absent means the field is not written at all. Do not read a missing field as a zero. +Nothing key related lives here. The PICC master key settings and keys belong to +application `000000` -- see [Applications](#applications) -- so every key in the +file states which AID it opens. + ## Applications ^[Top](#top) `$.Applications` is an object keyed by the 3-byte AID as 6 uppercase hex digits. +**The PICC level is application `000000`.** It carries the PICC master key +settings and keys and has no files. Giving it an AID of its own is the point: a +key in this file always says which application it opens. + ```json "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { "Version": "00", "Key": "00000000000000000000000000000000" } + } + }, "F51800": { "ISOFileID": "DF01", "DFName": "D2760000850100", @@ -97,7 +119,6 @@ zero. "NumKeysRaw": "81", "NumKeys": 1, "KeyType": "aes", - "KeyVersions": { "0": "00" }, "Authenticated": true, "Keys": { }, "Files": { } @@ -110,10 +131,9 @@ zero. | `ISOFileID` | hex, 2 bytes | ISO DF ID, absent when the application has none | | `DFName` | hex, 1-16 bytes | ISO DF name, absent when the application has none | | `KeySettings` | hex, 1 byte | | -| `NumKeysRaw` | hex, 1 byte | | -| `NumKeys` | int | | -| `KeyType` | token | `des`, `2tdea`, `3tdea` or `aes` | -| `KeyVersions` | object | key number -> 1 byte version | +| `NumKeysRaw` | hex, 1 byte | raw key-count byte, carries the key type in the top bits and the ISO-file-id flag in bit 5 | +| `NumKeys` | int | key count decoded from `NumKeysRaw` | +| `KeyType` | token | `des`, `2tdea`, `3tdea` or `aes`. One per application -- every key in an application shares it | | `Authenticated` | bool | whether the dump ran authenticated against this application | | `Keys` | object | see [Keys](#keys) | | `Files` | object | see [Files](#files) | @@ -194,21 +214,42 @@ Keys are part of the image, not a side file. A simulator cannot answer an authentication without them, and splitting them across two files means a card image that silently cannot be used. -Both `$.Card` and each application carry the same shape: +Every application, `000000` included, carries a `Keys` object keyed by key +number in decimal: ```json "Keys": { - "0": { "Algo": "aes", "Key": "E757178E13516A4F3171BC6EA85E165A" } + "0": { "Version": "00", "Key": "E757178E13516A4F3171BC6EA85E165A" }, + "1": { "Version": "03" } } ``` -Keyed by key number in decimal. `Algo` fixes the key length: `des` 8 bytes, -`2tdea` 16, `3tdea` 24, `aes` 16. Only key numbers actually known are written, -so an absent entry means "we do not have this key", never "the key is zero". +| Field | Meaning | +|---|---| +| `Version` | the key version, as read from the card. Present whenever we managed to read it | +| `Key` | the key itself. Present only when we actually have it | -`$.Card.Keys` holds the PICC master keys, which are the keys of AID `000000`. -Note the difference from the `mfdes v2` key recovery format, where PICC keys sit -under `Applications.000000` and are indexed by algorithm as well as key number. +A key version is readable without knowing the key, so the two are independent: + +* **`Version` and `Key`** -- we read the version and we have the key. +* **`Version` only** -- the key exists, we know its version, we could not + recover it. This is the normal case for every key but the one we authenticated + with. A missing `Key` never means the key is all zeros. +* **entry absent entirely** -- we know nothing about that key number. + +There is no per-key algorithm. Every key in an application uses the +application's `KeyType`, which fixes the length: `des` 8 bytes, `2tdea` 16, +`3tdea` 24, `aes` 16. + +Note the difference from the `mfdes v2` key recovery format written by +`hf mfdes chk`, which nests keys under an algorithm name +(`Applications.112233.AES.0.Key`) because during recovery the key type is not +yet known. In a dump it is, so the algorithm is stated once per application. + +`hf mfdes dump` reads a `mfdes v2` key file with `--keys `, and with no +`--keys` it looks for `hf-mfdes--keys.json` on its own -- the same filename +template it saves the dump under. Nothing is reported if that file does not +exist. ## The Read flag ^[Top](#top) @@ -251,7 +292,7 @@ of a dump file can be handed straight back to a command. `plain_rfu` is the card's second encoding for plain. It is kept distinct from `plain` so the file records what the card actually said. -| `Algo` / `KeyType` | key length | +| `KeyType` | key length | |---|---| | `des` | 8 | | `2tdea` | 16 | @@ -262,6 +303,324 @@ Hex strings are uppercase with no separators. Byte order is as the bytes travel on the wire, except `AccessRights` and the ISO file IDs, which are written big endian the way they are printed. +## A complete example +^[Top](#top) + +A real dump of a MIFARE DESFire EV2 2K, set up from blank with the commands +below. Every construct in this document appears in it: the PICC as application +`000000`, an AES application and a 2TDEA one, a standard data file, a value +file, a record file, and keys that are known by version but not by value. + +### The card +^[Top](#top) + +``` +# two applications, one AES with 3 keys, one 2TDEA with 2 +hf mfdes createapp -t 2tdea -k 00000000000000000000000000000000 --aid 112233 --fid 1122 --dfname pm3test1 --ks1 0F --ks2 A3 +hf mfdes createapp -t 2tdea -k 00000000000000000000000000000000 --aid 445566 --fid 4455 --dfname pm3test2 --ks1 0F --ks2 22 + +# ks2 carries the key type in the top two bits (0 = 2TDEA, 1 = 3TDEA, 2 = AES), +# the ISO-file-id flag in bit 5 and the key count in the low five. It overrides +# --dstalgo and --numkeys, so A3 is "AES, ISO file ids, 3 keys" + +# files in the AES application +hf mfdes createfile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 01 --isofid 0001 --size 000020 --amode encrypt --rrights key0 --wrights key0 --rwrights key0 --chrights key0 +hf mfdes createvaluefile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 02 --amode mac --lower 00000000 --upper 000003E8 --value 0000002A --lcredit 1 --rrights key0 --wrights key0 --rwrights key0 --chrights key0 +hf mfdes createrecordfile --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --isofid 0003 --size 000008 --maxrecord 000005 --amode plain --rrights free --wrights key0 --rwrights key0 --chrights key0 + +# and one in the 2TDEA application +hf mfdes createfile --aid 445566 -t 2tdea -k 00000000000000000000000000000000 --fid 00 --isofid 0010 --size 000010 --amode plain --rrights free --wrights key0 --rwrights key0 --chrights key0 + +# contents +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 01 -d 50726F786D61726B33204445534669726520746573742064617461212121 +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --type record -d 5245434F52443031 +hf mfdes write --aid 112233 -t aes -k 00000000000000000000000000000000 --fid 03 --type record -d 5245434F52443032 +hf mfdes write --aid 445566 -t 2tdea -k 00000000000000000000000000000000 --fid 00 -d 48454C4C4F2050524F584D41524B2133 + +# recover the application keys, saved under the name the dump will look for +hf mfdes chk -k 00000000000000000000000000000000 -j hf-mfdes-043240CAE45380-keys + +# and dump it +hf mfdes dump -t 2tdea -k 00000000000000000000000000000000 +``` + +Without that `chk` run, application `112233` cannot be opened with the 2TDEA +PICC key. The dump does not pretend otherwise: it records the application with +`"Authenticated": false` and no files, rather than inventing empty ones. + +### The key file +^[Top](#top) + +`hf-mfdes-043240CAE45380-keys.json`, written by `hf mfdes chk -j`. This is the +separate `mfdes v2` format, not part of the card image -- `hf mfdes dump` reads +it and folds the keys it contains into the dump. + +```json +{ + "Created": "proxmark3", + "FileType": "mfdes v2", + "Card": { + "UID": "043240CAE45380", + "SAK": "20", + "ATQA": "4403", + "ATS": "06757781028002F0" + }, + "Applications": { + "112233": { + "AES": { + "0": { + "Key": "00000000000000000000000000000000" + } + } + }, + "445566": { + "2TDEA": { + "0": { + "Key": "00000000000000000000000000000000" + } + } + } + } +} +``` + +Two differences from the way the dump stores keys: + +* Keys are nested under an **algorithm name** (`Applications.112233.AES.0.Key`) + because during key recovery the application's key type is not yet known. A + dump knows it, so it states `KeyType` once per application instead. +* PICC keys are not in this file at all. `hf mfdes chk` only walks the + application list; the PICC master key is the one you hand it with `-k`. + +The dump picks this file up without `--keys` because its name follows the same +`hf-mfdes--` template the dump itself is saved under: + +``` +[=] Loaded keys for 2 application(s) from `hf-mfdes-043240CAE45380-keys` +``` + +### The dump file +^[Top](#top) + +```json +{ + "Created": "proxmark3", + "FileType": "mfdes v1", + "Version": 1, + "Card": { + "UID": "043240CAE45380", + "ATQA": "4403", + "SAK": "20", + "ATS": "06757781028002F0", + "Version": "0401011200160504010102001605043240CAE45380CD651745414216", + "Signature": "035766BD56631ED57B614CE01A24372BDC29028A310937BC42EE998C66E56E6251083B723099D80EB77291B1A8BDB055C614EC944A11E38E", + "FreeMem": 896 + }, + "Applications": { + "000000": { + "KeySettings": "0F", + "NumKeysRaw": "01", + "NumKeys": 1, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + } + } + }, + "112233": { + "ISOFileID": "1122", + "DFName": "706D337465737431", + "KeySettings": "0F", + "NumKeysRaw": "83", + "NumKeys": 3, + "KeyType": "aes", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + }, + "1": { + "Version": "00" + }, + "2": { + "Version": "00" + } + }, + "Files": { + "01": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "encrypt", + "AccessRights": "0000", + "ISOFileID": "0001", + "FileSize": 32, + "Read": true, + "Data": "50726F786D61726B332044455346697265207465737420646174612121210000" + }, + "02": { + "Type": "value", + "TypeRaw": "02", + "CommMode": "mac", + "AccessRights": "0000", + "LowerLimit": 0, + "UpperLimit": 1000, + "LimitedCredit": "01", + "Value": 42, + "Read": true + }, + "03": { + "Type": "linear_record", + "TypeRaw": "03", + "CommMode": "plain", + "AccessRights": "E000", + "ISOFileID": "0003", + "RecordSize": 8, + "MaxRecords": 5, + "CurRecords": 2, + "Read": true, + "Records": { + "0": "5245434F52443031", + "1": "5245434F52443032" + } + } + } + }, + "445566": { + "ISOFileID": "4455", + "DFName": "706D337465737432", + "KeySettings": "0F", + "NumKeysRaw": "02", + "NumKeys": 2, + "KeyType": "2tdea", + "Authenticated": true, + "Keys": { + "0": { + "Version": "00", + "Key": "00000000000000000000000000000000" + }, + "1": { + "Version": "00" + } + }, + "Files": { + "00": { + "Type": "standard", + "TypeRaw": "00", + "CommMode": "plain", + "AccessRights": "E000", + "ISOFileID": "0010", + "FileSize": 16, + "Read": true, + "Data": "48454C4C4F2050524F584D41524B2133" + } + } + } + } +} +``` + +Things to read out of it: + +* **`FreeMem` is 896**, not the 2080 a blank card reports. The applications and + files took the rest. +* **`NumKeysRaw` `83`** decodes to `KeyType: aes` (top bits 10), ISO file ids + enabled (bit 5) and `NumKeys: 3`. +* **Keys 1 and 2 of `112233` have a `Version` but no `Key`.** They exist, we + read their version, we never recovered them. Key 0 is the one `hf mfdes chk` + found. +* **The value file has no `Data`**, only `Value`, `LowerLimit`, `UpperLimit` + and `LimitedCredit`. +* **The record file has `Records`, not `Data`** -- two records of 8 bytes in a + file with room for five. +* **File `01` reads 32 bytes** where only 30 were written; the card zero-pads to + the file size, and the dump stores what the card returned. + +### What `hf mfdes view` makes of it +^[Top](#top) + +``` +[=] --- Tag Information --------------------------- +[+] UID.............. 043240CAE45380 +[+] ATQA............. 03 44 +[+] SAK.............. 20 +[+] ATS.............. 06757781028002F0 +[+] Version.......... 0401011200160504010102001605043240CAE45380CD651745414216 +[+] Signature........ 035766BD56631ED57B614CE01A24372BDC29028A310937BC42EE998C66E56E62... +[+] Free memory...... 896 bytes + +[=] --- Applications ------------------------------ +[+] 2 application(s) plus the PICC level + +[=] --- AID 000000 ( PICC level ) --------------------- +[+] Key settings. 0F, 1 2tdea key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Files........ 0 + +[=] --- AID 112233 -------------------------------- +[+] ISO DF ID.... 1122 +[+] DF name...... pm3test1 ( 706D337465737431 ) +[+] Key settings. 0F, 3 aes key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Key 01 (ver 00). not recovered +[+] Key 02 (ver 00). not recovered +[+] Files........ 3 + +[+] File 01 - Standard data +[+] ISO file ID.. 0001 +[+] Comm mode.... encrypt +[+] Access rights 0000 +[+] File size.... 32 + +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 50 72 6F 78 6D 61 72 6B 33 20 44 45 53 46 69 72 | Proxmark3 DESFir +[=] 16/0x10 | 65 20 74 65 73 74 20 64 61 74 61 21 21 21 00 00 | e test data!!!.. + +[+] File 02 - Value +[+] Comm mode.... mac +[+] Access rights 0000 +[+] Limits....... 0 ... 1000 +[+] Value........ 42 (0x0000002A) + +[+] File 03 - Linear Record +[+] ISO file ID.. 0003 +[+] Comm mode.... plain +[+] Access rights E000 +[+] Records...... 2 of 5, 8 bytes each + +[+] Record 0 +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 52 45 43 4F 52 44 30 31 | RECORD01 +[+] Record 1 +[=] 0/0x00 | 52 45 43 4F 52 44 30 32 | RECORD02 + +[=] --- AID 445566 -------------------------------- +[+] ISO DF ID.... 4455 +[+] DF name...... pm3test2 ( 706D337465737432 ) +[+] Key settings. 0F, 2 2tdea key(s) +[+] Authenticated yes +[+] Key 00 (ver 00). 00000000000000000000000000000000 +[+] Key 01 (ver 00). not recovered +[+] Files........ 1 + +[+] File 00 - Standard data +[+] ISO file ID.. 0010 +[+] Comm mode.... plain +[+] Access rights E000 +[+] File size.... 16 + +[=] Offset | Data | Ascii +[=] ---------------------------------------------------------------------------- +[=] 0/0x00 | 48 45 4C 4C 4F 20 50 52 4F 58 4D 41 52 4B 21 33 | HELLO PROXMARK!3 +``` + ## In-memory representation ^[Top](#top) From 8fd9bcbebce0530780200b7c779d56eb3248d0c6 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 09:11:38 +0200 Subject: [PATCH 2/5] hf mfdes: dump a whole card to json, and view it back 'hf mfdes dump' walked one application and printed it. It now walks every application on the PICC, keeps what it reads, and saves a 'hf-mfdes--dump.json' card image. '--aid' / '--isoid' / '--dfname' still narrow it to one application, '--ns' skips the save. The format is 'mfdes v1', written and read in fileutils.c and documented in doc/mfdes_dump_format.md. Two decisions worth stating: - The PICC level is application 000000, so every key in the file says which AID it opens. Key version and key value are separate: a version with no key is the normal shape for a key that was found but never recovered, and a missing key never means the key is zero. - Every file carries a 'Read' flag. A file whose contents could not be fetched is recorded as unread with no data at all, rather than as a run of zeros. A simulator built on this must not confuse '8 bytes of 00' with 'we could not read 8 bytes'. 'hf mfdes view -f ' prints such a file with no device attached. With no '--keys', the dump looks for 'hf-mfdes--keys.json' by itself, so a 'hf mfdes chk -j' run is picked up on the next dump without naming the file again. Two fixes fell out of testing against a DESFire EV2: - DesfireSetKey() calls DesfireClearContext(), which wipes command set, comm mode, KDF and UID, not just the key. Swapping in a per-application key that way left the context at 'Communication mode: n/a' and DesfireFillFileList() then returned junk file ids. Use DesfireSetKeyNoClear(). - GetVersion and the originality signature are answered unauthenticated. Asking for them from inside the authenticated session produced a 'Wrong communication mode' warning and a run of MAC mismatches. hex_to_buffer() treats hex_max_len as a byte count while every sprint_hex* caller passes sizeof(buf) - 1, a character count, so it writes two or three times the buffer size. Measured, sprint_hex_inrow overflowed at 4098 input bytes. Doubling UTIL_BUFFER_SIZE_SPRINT to 16384 moves that to 8192; the mixed semantics still need auditing across ~30 call sites. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 3 + client/src/cmdhfmfdes.c | 866 ++++++++++++++++++++++++++++++++++++--- client/src/fileutils.c | 617 ++++++++++++++++++++++++++++ client/src/fileutils.h | 98 +++++ client/src/util.c | 2 +- doc/commands.json | 49 ++- doc/commands.md | 1 + doc/mfdes_dump_format.md | 10 +- 8 files changed, 1578 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e2c7eaff..cb82e055a 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 dump` - now walks the whole PICC and saves a `hf-mfdes--dump.json` card image, picking up `hf-mfdes--keys.json` on its own (@iceman1001) +- Added `hf mfdes view` - print a DESFire card dump file, no device needed (@iceman1001) +- Fixed `sprint_hex` - a buffer twice the old size, so printing a long block no longer runs off the end of the static buffer (@iceman1001) - Added `vigik_recover_pk.py` - recover public keys from RSA signatures (@iceman1001) - Fixed `hf mf autopwn` - a sector that cannot be cracked no longer discards the keys already recovered (@iceman1001) - Fixed `hf mf nested` - a NAK from the tag now ends the nonce collection instead of retrying until the client times out (@iceman1001) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 95aa11d35..cf8d95ea9 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -8229,11 +8229,380 @@ static int CmdHF14ADesLsApp(const char *Cmd) { return PM3_SUCCESS; } +//----------------------------------------------------------------------------- +// DESFire card image collection. +// +// `hf mfdes dump` walks the whole PICC into a desfire_dump_t and writes it out +// as a jsfMfDesfire_v1 json file. `hf mfdes view` reads one back. +// See doc/mfdes_dump_format.md for the on-disk schema. +//----------------------------------------------------------------------------- + +// the 14a select answer carries UID/ATQA/SAK/ATS, none of which the DESFire +// layer keeps around +static int DesfireDumpFillCardInfo(iso14a_card_select_t *card_info) { + + DropField(); + SendIso14aReader(ISO14A_CONNECT | ISO14A_CLEARTRACE, NULL, 0); + + PacketResponseNG resp; + uint8_t select_status = 0; + if (WaitForIso14aReply(&resp, 2500, NULL, &select_status) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for card select"); + return PM3_ETIMEOUT; + } + + // 0: couldn't read, 1: OK with ATS, 2: OK no ATS, 3: proprietary anticollision + if (select_status != 1 && select_status != 2) { + return PM3_ESOFT; + } + + memcpy(card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); + return PM3_SUCCESS; +} + +// record a key we authenticated with. The algo is the application's, not the +// key's, so it is not stored here -- see desfire_dump_app_t.keytype +static void DesfireDumpStoreKey(desfire_dump_app_t *app, uint8_t keyno, uint8_t algo, const uint8_t *key) { + + if (keyno >= DESFIRE_MAX_KEY_COUNT) { + return; + } + + app->keytype = algo; + app->keys.present[keyno] = 1; + memcpy(app->keys.key[keyno], key, desfire_get_key_length(algo)); +} + +// pull keyno for `aid` out of a `hf mfdes chk` key file, NULL when we have none +static const uint8_t *DesfireDumpFindKey(const desfire_keys_dump_t *keyfile, uint32_t aid, uint8_t algo, uint8_t keyno) { + + if (keyfile == NULL || keyno >= DESFIRE_MAX_KEY_COUNT || algo >= DESFIRE_MAX_ALGO_COUNT) { + return NULL; + } + + for (uint8_t i = 0; i < keyfile->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + if (keyfile->app[i].aid != aid) { + continue; + } + if (keyfile->app[i].keys[algo][keyno][0] == 0) { + return NULL; + } + return &keyfile->app[i].keys[algo][keyno][1]; + } + return NULL; +} + +static void DesfireDumpFillAppMeta(desfire_dump_app_t *app, const AppListElm_t *src) { + + app->aid = src->appNum; + app->isofid = src->appISONum; + app->keysettings = src->keySettings; + app->numkeysraw = src->numKeysRaw; + app->numkeys = src->numberOfKeys; + app->keytype = src->keyType; + app->settings_ok = (src->numKeysRaw != 0); + + for (uint8_t i = 0; i < src->numberOfKeys && i < DESFIRE_MAX_KEY_COUNT; i++) { + app->keys.version[i] = src->keyVersions[i]; + app->keys.versionknown[i] = 1; + } + + app->dfnamelen = str_nlen((char *)src->appDFName, sizeof(src->appDFName)); + memcpy(app->dfname, src->appDFName, app->dfnamelen); +} + +// find the application the user named on the command line in the PICC's own +// list, so an --isoid or --dfname dump still records the AID and key settings +static int DesfireDumpFindApp(const AppListS appList, size_t appcount, const DesfireContext_t *dctx, + DesfireISOSelectWay selectway, uint32_t id) { + + for (size_t i = 0; i < appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + + switch (selectway) { + case ISW6bAID: + if (appList[i].appNum == id) { + return i; + } + break; + case ISWIsoID: + if (appList[i].appISONum == id) { + return i; + } + break; + case ISWDFName: + if (dctx->selectedDFNameLen > 0 && + memcmp(appList[i].appDFName, dctx->selectedDFName, dctx->selectedDFNameLen) == 0) { + return i; + } + break; + case ISWMF: + break; + } + } + return -1; +} + +static void DesfireDumpFillFileSettings(const FileSettings_t *fs, desfire_dump_file_t *f) { + + f->type = fs->fileType; + f->commmode = fs->fileCommMode; + f->accessrights = fs->rawAccessRights; + f->size = fs->fileSize; + f->lowerlimit = fs->lowerLimit; + f->upperlimit = fs->upperLimit; + f->limitedcredit = fs->limitedCredit; + f->recordsize = fs->recordSize; + f->maxrecords = fs->maxRecordCount; + f->currecords = fs->curRecordCount; + + f->addrights_len = fs->additionalAccessRightsLength; + if (f->addrights_len > ARRAYLEN(f->addrights)) { + f->addrights_len = ARRAYLEN(f->addrights); + } + for (uint8_t i = 0; i < f->addrights_len; i++) { + f->addrights[i] = fs->additionalAccessRights[i]; + } + + f->settings_ok = true; +} + +// read one file into the image. Leaves f->read_ok false when the contents +// could not be fetched -- the caller must not turn that into zeroed data +static int DesfireDumpReadFile(DesfireContext_t *dctx, const FileSettings_t *fs, desfire_dump_file_t *f, + uint32_t maxdatafilelength, bool verbose) { + + f->read_ok = false; + + int filetype; + switch (fs->fileType) { + case 0x00: + case 0x01: + filetype = RFTData; + break; + case 0x02: + filetype = RFTValue; + break; + case 0x03: + case 0x04: + filetype = RFTRecord; + break; + case 0x05: + filetype = RFTMAC; + break; + default: + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + // iso chaining works in the lrp mode + dctx->isoChaining |= (dctx->secureChannel == DACLRP); + + DesfireCommunicationMode commMode; + if (filetype == RFTValue) { + commMode = DesfireValueOpCommMode(dctx, fs, MFDES_GET_VALUE); + } else { + const uint8_t rrights[] = { fs->rAccess, fs->rwAccess }; + commMode = DesfireEffectiveCommMode(dctx, fs->commMode, rrights, ARRAYLEN(rrights)); + } + + // lrp needs to point exact mode + if (dctx->secureChannel == DACLRP && fs->rAccess == 0x0e) { + commMode = DCMPlain; + } + + if (fs->rAccess == 0x0f && fs->rwAccess == 0x0f) { + if (verbose) { + PrintAndLogEx(INFO, "File 0x%02x read access is denied (0x0F), skipping contents", f->num); + } + // nothing was sent, the session is still good + return PM3_EINVARG; + } + + DesfireSetCommMode(dctx, commMode); + + if (filetype == RFTValue) { + uint32_t value = 0; + if (DesfireValueFileOperations(dctx, f->num, MFDES_GET_VALUE, &value) != PM3_SUCCESS) { + return PM3_ESOFT; + } + f->value = value; + f->read_ok = true; + return PM3_SUCCESS; + } + + uint8_t *resp = calloc(DESFIRE_BUFFER_SIZE, sizeof(uint8_t)); + if (resp == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + return PM3_EMALLOC; + } + size_t resplen = 0; + int res; + + if (filetype == RFTRecord) { + + size_t reclen = fs->recordSize; + res = DesfireReadRecords(dctx, f->num, 0, 0, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + + if (reclen == 0 && resplen > 0) { + reclen = resplen; + } + f->recordsize = reclen; + + } else { + uint32_t length = 0; + if (filetype == RFTData && maxdatafilelength && (maxdatafilelength < fs->fileSize)) { + length = maxdatafilelength; + } + + res = DesfireReadFile(dctx, f->num, 0, length, resp, &resplen); + if (res != PM3_SUCCESS) { + free(resp); + return PM3_ESOFT; + } + } + + if (resplen == 0) { + // an empty answer is a successful read of nothing, keep read_ok true + // so a reader can tell it apart from "we never got there" + free(resp); + f->read_ok = true; + return PM3_SUCCESS; + } + + f->data = calloc(resplen, sizeof(uint8_t)); + if (f->data == NULL) { + PrintAndLogEx(WARNING, "Failed to allocate memory"); + free(resp); + return PM3_EMALLOC; + } + + memcpy(f->data, resp, resplen); + f->datalen = resplen; + f->read_ok = true; + free(resp); + return PM3_SUCCESS; +} + +static void DesfireDumpPrintFile(const desfire_dump_file_t *f, bool isopresent) { + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", f->num); + PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), f->num); + if (isopresent) { + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, "File ISO ID : %04x", f->isofid); + } else { + PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); + } + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, "Contents : " _YELLOW_("not read")); + return; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, "Value : %u (0x%08x)", f->value, f->value); + return; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, "Contents : " _YELLOW_("empty")); + return; + } + + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + uint32_t reccount = f->datalen / f->recordsize; + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x, %u record(s) of %u bytes", f->datalen, f->num, reccount, f->recordsize); + for (uint32_t i = 0; i < reccount; i++) { + if (i != 0) { + PrintAndLogEx(SUCCESS, "Record %u", i); + } + print_buffer_with_offset(f->data + (i * f->recordsize), f->recordsize, 0, (i == 0)); + } + return; + } + + PrintAndLogEx(SUCCESS, "Read %u bytes from file 0x%02x", f->datalen, f->num); + print_buffer_with_offset(f->data, f->datalen, 0, true); +} + +// collect one application. The caller has already selected and authenticated +static int DesfireDumpCollectApp(DesfireContext_t *dctx, desfire_dump_app_t *app, uint32_t maxlength, + DesfireISOSelectWay selectway, uint32_t id, int securechann, + bool noauth, bool verbose) { + + FileList_t FileList = {{0}}; + size_t filescount = 0; + bool isopresent = false; + + int res = DesfireFillFileList(dctx, FileList, &filescount, &isopresent); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Can't get file list for application " _YELLOW_("%06X"), app->aid); + return res; + } + + // the ISO file id probe in DesfireFillFileList makes the PICC end the session on + // applications without ISO file ids, so get it back before reading the files + if (noauth == false && DesfireIsAuthenticated(dctx) == false) { + DesfireSetCommMode(dctx, DCMPlain); + res = DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + return res; + } + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + + if (selectway == ISW6bAID) { + DesfirePrintAIDFunctions(id); + } + + app->filecount = 0; + bool session_lost = false; + + for (size_t i = 0; i < filescount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + // a refused exchange ends the PICC session, re-open it before the next file. + // a file we chose not to read never reached the card and costs us nothing + if (session_lost) { + DesfireSetCommMode(dctx, DCMPlain); + if (DesfireSelectAndAuthenticateAppW(dctx, securechann, selectway, id, noauth, verbose) != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Lost the session on application " _YELLOW_("%06X") ", stopping here", app->aid); + break; + } + session_lost = false; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = FileList[i].fileNum; + f->isofid = FileList[i].fileISONum; + DesfireDumpFillFileSettings(&FileList[i].fileSettings, f); + app->filecount++; + + session_lost = (DesfireDumpReadFile(dctx, &FileList[i].fileSettings, f, maxlength, verbose) == PM3_ESOFT); + + DesfireDumpPrintFile(f, isopresent); + DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); + } + + return PM3_SUCCESS; +} + static int CmdHF14ADesDump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes dump", - "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/n" + "Dump a DESFire card to a json file. Walks every application and every file\n" + "unless an application is named with --aid / --isoid / --dfname.\n" + "Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command\n" + "hf mfdes dump --aid 123456 -> dump only application 123456\n" + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application\n" "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit"); void *argtable[] = { @@ -8253,6 +8622,9 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), arg_str0("l", "length", "", "Maximum length for read data files (3 hex bytes, big endian)"), arg_lit0(NULL, "no-auth", "Execute without authentication"), + arg_str0("f", "file", "", "Save dump to file, if no UID will be used as filename"), + arg_str0(NULL, "keys", "", "Load application keys from a `hf mfdes chk` key file"), + arg_lit0(NULL, "ns", "No save to file"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -8261,6 +8633,21 @@ static int CmdHF14ADesDump(const char *Cmd) { bool verbose = arg_get_lit(ctx, 2); bool noauth = arg_get_lit(ctx, 15); + // an application was named on the command line? then dump only that one + bool single_app = (arg_get_str(ctx, 11)->count > 0) || + (arg_get_str(ctx, 12)->count > 0) || + (arg_get_str(ctx, 13)->count > 0); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 16), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + int keyfnlen = 0; + char keyfilename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 17), (uint8_t *)keyfilename, FILE_PATH_SIZE, &keyfnlen); + + bool nosave = arg_get_lit(ctx, 18); + DesfireContext_t dctx = {0}; int securechann = defaultSecureChannel; uint32_t id = 0x000000; @@ -8280,70 +8667,444 @@ static int CmdHF14ADesDump(const char *Cmd) { SetAPDULogging(APDULogging); CLIParserFree(ctx); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; } - FileList_t FileList = {{0}}; - size_t filescount = 0; - bool isopresent = false; - res = DesfireFillFileList(&dctx, FileList, &filescount, &isopresent); - if (res != PM3_SUCCESS) { - DropField(); - return res; + // UID / ATQA / SAK / ATS come from the 14a layer, grab them before we talk DESFire + DesfireDumpFillCardInfo(&dump->card_info); + DropField(); + + // no --keys given? look for the key file this card would have been saved + // under, the same `hf-mfdes--...` template the dump itself uses + bool autokeys = false; + if (keyfnlen == 0 && dump->card_info.uidlen > 0) { + strcat(keyfilename, "hf-mfdes-"); + FillFileNameByUID(keyfilename, dump->card_info.uid, "-keys", dump->card_info.uidlen); + keyfnlen = strlen(keyfilename); + autokeys = true; } - // the ISO file id probe in DesfireFillFileList makes the PICC end the session on - // applications without ISO file ids, so get it back before reading the files - if (noauth == false && DesfireIsAuthenticated(&dctx) == false) { - DesfireSetCommMode(&dctx, DCMPlain); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + // optional key file from `hf mfdes chk` + desfire_keys_dump_t *keyfile = NULL; + if (keyfnlen > 0) { + keyfile = calloc(1, sizeof(desfire_keys_dump_t)); + if (keyfile == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + free(dump); + return PM3_EMALLOC; } - } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(SUCCESS, "Application " _CYAN_("%s") " have " _GREEN_("%zu") " files", DesfireWayIDStr(selectway, id), filescount); + // a key file we went looking for on our own is not expected to exist, + // so probe quietly first rather than let loadFileJSON complain + char *found = NULL; + bool exists = (searchFile(&found, RESOURCES_SUBDIR, keyfilename, ".json", autokeys) == PM3_SUCCESS); + free(found); - if (selectway == ISW6bAID) - DesfirePrintAIDFunctions(id); - - if (filescount == 0) { - PrintAndLogEx(INFO, "There is no files in the application %s", DesfireWayIDStr(selectway, id)); - DropField(); - return res; - } - - res = PM3_SUCCESS; - for (int i = 0; i < filescount; i++) { - if (res != PM3_SUCCESS) { - DesfireSetCommMode(&dctx, DCMPlain); - res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); - if (res != PM3_SUCCESS) { - DropField(); - return res; + size_t klen = 0; + if (exists == false || loadFileJSON(keyfilename, keyfile, sizeof(desfire_keys_dump_t), &klen, NULL) != PM3_SUCCESS) { + if (autokeys == false) { + PrintAndLogEx(WARNING, "Could not load key file `" _YELLOW_("%s") "`, continuing without it", keyfilename); + } else if (verbose) { + PrintAndLogEx(INFO, "No key file `" _YELLOW_("%s") "` found", keyfilename); } + free(keyfile); + keyfile = NULL; + } else { + PrintAndLogEx(INFO, "Loaded keys for " _YELLOW_("%u") " application(s) from `" _YELLOW_("%s") "`", keyfile->appcount, keyfilename); + } + } + + uint8_t buf[255] = {0}; + size_t buflen = 0; + + // GetVersion and the originality signature are answered unauthenticated. + // Asking for them from inside the authenticated session instead would put + // them in the wrong communication mode and every answer would come back + // looking like a MAC failure + DesfireContext_t plainctx = {0}; + plainctx.commMode = DCMPlain; + plainctx.cmdSet = DCCNative; + + if (DesfireAnticollision(verbose) == PM3_SUCCESS) { + + if (DesfireGetVersion(&plainctx, buf, &buflen) == PM3_SUCCESS && buflen <= sizeof(dump->version)) { + memcpy(dump->version, buf, buflen); + dump->versionlen = buflen; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--------------------------------- " _CYAN_("File %02x") " ----------------------------------", FileList[i].fileNum); - PrintAndLogEx(SUCCESS, "File ID : " _GREEN_("%02x"), FileList[i].fileNum); - if (isopresent) { - if (FileList[i].fileISONum != 0) - PrintAndLogEx(SUCCESS, "File ISO ID : %04x", FileList[i].fileISONum); - else - PrintAndLogEx(SUCCESS, "File ISO ID : " _YELLOW_("n/a")); + buflen = 0; + if (DesfireReadSignature(&plainctx, 0x00, buf, &buflen) == PM3_SUCCESS && buflen <= sizeof(dump->signature)) { + memcpy(dump->signature, buf, buflen); + dump->signaturelen = buflen; } - DesfirePrintFileSettingsExtended(&FileList[i].fileSettings); - - res = DesfileReadFileAndPrint(&dctx, FileList[i].fileNum, RFTAuto, 0, 0, maxlength, noauth, verbose); } DropField(); + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, 0x000000, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "PICC level select/auth " _RED_("failed")); + DropField(); + free(keyfile); + free(dump); + return res; + } + + // the PICC level is application 000000 + dump->picc.aid = 0x000000; + dump->picc.auth_ok = (noauth == false); + if (dump->picc.auth_ok) { + DesfireDumpStoreKey(&dump->picc, dctx.keyNum, dctx.keyType, dctx.key); + } + + // DesfireFillAppList() -> DesfireFillPICCInfo() already asks for free memory, + // key settings and key version 0, so don't ask a second time + PICCInfo_t PICCInfo = {0}; + AppListS AppList = {{0}}; + DesfireFillAppList(&dctx, &PICCInfo, AppList, false, false, true); + + // DesfireFillPICCInfo() reports a refused GetFreeMem as 0xffffffff + dump->freemem_ok = (PICCInfo.freemem != 0xffffffff); + if (dump->freemem_ok) { + dump->freemem = PICCInfo.freemem; + } + + dump->picc.keysettings = PICCInfo.keySettings; + dump->picc.numkeysraw = PICCInfo.numKeysRaw; + dump->picc.numkeys = PICCInfo.numberOfKeys; + dump->picc.settings_ok = true; + + // the PICC only hands out the version of key 0 + dump->picc.keys.version[0] = PICCInfo.keyVersion0; + dump->picc.keys.versionknown[0] = 1; + + PrintAndLogEx(NORMAL, ""); + DesfirePrintPICCInfo(&dctx, &PICCInfo); + + if (single_app) { + + // only the application the user named + desfire_dump_app_t *app = &dump->app[0]; + dump->appcount = 1; + + int idx = DesfireDumpFindApp(AppList, PICCInfo.appCount, &dctx, selectway, id); + if (idx >= 0) { + DesfireDumpFillAppMeta(app, &AppList[idx]); + } else { + // not in the PICC's list, record what the selector told us + app->aid = (selectway == ISW6bAID) ? id : 0; + app->isofid = (selectway == ISWIsoID) ? id : 0; + app->dfnamelen = dctx.selectedDFNameLen; + memcpy(app->dfname, dctx.selectedDFName, app->dfnamelen); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Select/auth of %s " _RED_("failed"), DesfireWayIDStr(selectway, id)); + DropField(); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return res; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, selectway, id, securechann, noauth, verbose); + + } else { + + uint8_t appcount = (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) ? DESFIRE_MAX_APP_COUNT : PICCInfo.appCount; + if (PICCInfo.appCount > DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "PICC has %zu applications, dumping the first %d", PICCInfo.appCount, DESFIRE_MAX_APP_COUNT); + } + + dump->appcount = appcount; + + // the key we authenticated the PICC with is the fallback for every + // application, so keep a copy -- picking a key out of the key file for + // one application must not carry over into the next + uint8_t basekey[DESFIRE_MAX_KEY_SIZE] = {0}; + memcpy(basekey, dctx.key, sizeof(basekey)); + DesfireCryptoAlgorithm basealgo = dctx.keyType; + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_dump_app_t *app = &dump->app[i]; + DesfireDumpFillAppMeta(app, &AppList[i]); + + // a key from the key file beats the one on the command line + // DesfireSetKey() would clear the whole context -- command set, + // comm mode, KDF and UID all came from the command line and have to + // survive, so only the key itself is swapped + const uint8_t *appkey = DesfireDumpFindKey(keyfile, app->aid, app->keytype, dctx.keyNum); + if (appkey != NULL) { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, app->keytype, (uint8_t *)appkey); + if (verbose) { + PrintAndLogEx(INFO, "Application " _YELLOW_("%06X") " using key %u from the key file", app->aid, dctx.keyNum); + } + } else { + DesfireSetKeyNoClear(&dctx, dctx.keyNum, basealgo, basekey); + } + + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, ISW6bAID, app->aid, noauth, verbose); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, "Application " _YELLOW_("%06X") " select/auth " _RED_("failed") ", skipping", app->aid); + continue; + } + + app->auth_ok = (noauth == false); + if (app->auth_ok) { + DesfireDumpStoreKey(app, dctx.keyNum, dctx.keyType, dctx.key); + } + + DesfireDumpCollectApp(&dctx, app, maxlength, ISW6bAID, app->aid, securechann, noauth, verbose); + } + } + + DropField(); + + if (nosave) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Called with no save option"); + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; + } + + if (fnlen < 1) { + if (dump->card_info.uidlen == 0) { + PrintAndLogEx(WARNING, "No UID to build a filename from, use " _YELLOW_("-f ")); + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_ESOFT; + } + PrintAndLogEx(INFO, "Using UID as filename"); + strcat(filename, "hf-mfdes-"); + FillFileNameByUID(filename, dump->card_info.uid, "-dump", dump->card_info.uidlen); + } + + PrintAndLogEx(NORMAL, ""); + pm3_save_dump_json(filename, (uint8_t *)dump, sizeof(desfire_dump_t), jsfMfDesfire_v1); + + desfire_dump_free(dump); + free(keyfile); + free(dump); + return PM3_SUCCESS; +} + +static void DesfireViewPrintKeys(const desfire_dump_app_t *app) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + const desfire_dump_keys_t *keys = &app->keys; + + if (keys->versionknown[keyno] == 0 && keys->present[keyno] == 0) { + continue; + } + + char ver[16] = "??"; + if (keys->versionknown[keyno]) { + snprintf(ver, sizeof(ver), "%02X", keys->version[keyno]); + } + + if (keys->present[keyno]) { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _GREEN_("%s") + , keyno + , ver + , sprint_hex_inrow(keys->key[keyno], desfire_get_key_length(app->keytype)) + ); + } else { + PrintAndLogEx(SUCCESS, " Key %02u (ver %s). " _YELLOW_("not recovered"), keyno, ver); + } + } +} + +// the PICC is application 000000 and prints the same way as the rest +static void DesfireViewPrintApp(const desfire_dump_app_t *app) { + + PrintAndLogEx(NORMAL, ""); + if (app->aid == 0x000000) { + PrintAndLogEx(INFO, "--- " _CYAN_("AID 000000") " ( PICC level ) ---------------------"); + } else { + PrintAndLogEx(INFO, "--- " _CYAN_("AID %06X") " --------------------------------", app->aid); + } + + if (app->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO DF ID.... %04X", app->isofid); + } + if (app->dfnamelen > 0) { + // DF names are often plain ascii, show both the way `lsapp` does + PrintAndLogEx(SUCCESS, " DF name...... " _YELLOW_("%s") " ( %s )" + , sprint_ascii(app->dfname, app->dfnamelen) + , sprint_hex_inrow(app->dfname, app->dfnamelen) + ); + } + if (app->settings_ok) { + PrintAndLogEx(SUCCESS, " Key settings. %02X, %u %s key(s)" + , app->keysettings + , app->numkeys + , CLIGetOptionListStr(DesfireAlgoOpts, app->keytype) + ); + } + PrintAndLogEx(SUCCESS, " Authenticated %s", app->auth_ok ? _GREEN_("yes") : _YELLOW_("no")); + + DesfireViewPrintKeys(app); + + PrintAndLogEx(SUCCESS, " Files........ %u", app->filecount); + + for (uint8_t n = 0; n < app->filecount && n < DESFIRE_MAX_FILE_COUNT; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, " File " _GREEN_("%02X") " - %s", f->num, GetDesfireFileType(f->type)); + + if (f->isofid != 0) { + PrintAndLogEx(SUCCESS, " ISO file ID.. %04X", f->isofid); + } + + if (f->settings_ok) { + // f->commmode is the raw file comm mode byte, not a DesfireCommunicationMode + PrintAndLogEx(SUCCESS, " Comm mode.... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, DesfireFileCommModeToCommMode(f->commmode))); + PrintAndLogEx(SUCCESS, " Access rights %04X", f->accessrights); + } + + switch (f->type) { + case 0x00: + case 0x01: + PrintAndLogEx(SUCCESS, " File size.... %u", f->size); + break; + case 0x02: + PrintAndLogEx(SUCCESS, " Limits....... %u ... %u", f->lowerlimit, f->upperlimit); + break; + case 0x03: + case 0x04: + PrintAndLogEx(SUCCESS, " Records...... %u of %u, %u bytes each", f->currecords, f->maxrecords, f->recordsize); + break; + default: + break; + } + + if (f->read_ok == false) { + PrintAndLogEx(WARNING, " Contents..... " _YELLOW_("not read")); + continue; + } + + if (f->type == 0x02) { + PrintAndLogEx(SUCCESS, " Value........ " _GREEN_("%u") " (0x%08X)", f->value, f->value); + continue; + } + + if (f->datalen == 0) { + PrintAndLogEx(SUCCESS, " Contents..... " _YELLOW_("empty")); + continue; + } + + PrintAndLogEx(NORMAL, ""); + if ((f->type == 0x03 || f->type == 0x04) && f->recordsize > 0 && (f->datalen % f->recordsize) == 0) { + for (uint32_t r = 0; r < f->datalen / f->recordsize; r++) { + PrintAndLogEx(SUCCESS, " Record %u", r); + print_buffer_with_offset(f->data + (r * f->recordsize), f->recordsize, 0, (r == 0)); + } + } else { + print_buffer_with_offset(f->data, f->datalen, 0, true); + } + } +} + +static int CmdHF14ADesView(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes view", + "Print a DESFire card dump file (json)", + "hf mfdes view -f hf-mfdes-01020304050607-dump.json"); + + void *argtable[] = { + arg_param_begin, + arg_str1("f", "file", "", "Filename of dump"), + arg_lit0("v", "verbose", "Verbose output"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + int fnlen = 0; + 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); + CLIParserFree(ctx); + + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + return PM3_EMALLOC; + } + + size_t dlen = 0; + int res = loadFileJSON(filename, dump, sizeof(desfire_dump_t), &dlen, NULL); + if (res != PM3_SUCCESS) { + free(dump); + return res; + } + + if (dlen != sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "`" _YELLOW_("%s") "` is not a DESFire card dump", filename); + desfire_dump_free(dump); + free(dump); + return PM3_EINVARG; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------"); + + if (dump->card_info.uidlen > 0) { + PrintAndLogEx(SUCCESS, "UID.............. " _GREEN_("%s"), sprint_hex_inrow(dump->card_info.uid, dump->card_info.uidlen)); + // the file keeps ATQA in wire order, `hf 14a info` prints it the other way round + PrintAndLogEx(SUCCESS, "ATQA............. %02X %02X", dump->card_info.atqa[1], dump->card_info.atqa[0]); + PrintAndLogEx(SUCCESS, "SAK.............. %02X", dump->card_info.sak); + if (dump->card_info.ats_len > 0) { + PrintAndLogEx(SUCCESS, "ATS.............. %s", sprint_hex_inrow(dump->card_info.ats, dump->card_info.ats_len)); + } + } + + if (dump->versionlen > 0) { + PrintAndLogEx(SUCCESS, "Version.......... %s", sprint_hex_inrow(dump->version, dump->versionlen)); + } + + if (dump->signaturelen > 0) { + PrintAndLogEx(SUCCESS, "Signature........ %s", sprint_hex_inrow(dump->signature, dump->signaturelen)); + } + + if (dump->freemem_ok) { + PrintAndLogEx(SUCCESS, "Free memory...... " _GREEN_("%u") " bytes", dump->freemem); + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Applications") " ------------------------------"); + PrintAndLogEx(SUCCESS, "%u application(s) plus the PICC level", dump->appcount); + + DesfireViewPrintApp(&dump->picc); + + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + DesfireViewPrintApp(&dump->app[i]); + } + + if (verbose) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "Loaded `" _YELLOW_("%s") "`", filename); + } + + PrintAndLogEx(NORMAL, ""); + desfire_dump_free(dump); + free(dump); return PM3_SUCCESS; } @@ -10000,6 +10761,7 @@ static command_t CommandTable[] = { {"getfileisoids", CmdHF14ADesGetFileISOIDs, IfPm3Iso14443a, "Get File ISO IDs list"}, {"lsfiles", CmdHF14ADesLsFiles, IfPm3Iso14443a, "Show all files list"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, + {"view", CmdHF14ADesView, AlwaysAvailable, "Display content from tag dump file"}, {"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/fileutils.c b/client/src/fileutils.c index 2c0f58a3c..750dbeb48 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -637,6 +637,503 @@ static void json15_save_tag(json_t *root, const iso15_tag_t *tag, size_t pagesco } } +//----------------------------------------------------------------------------- +// DESFire card image (jsfMfDesfire_v1) helpers. +// Token spellings match what the `hf mfdes` CLI already accepts, so a value +// read out of a dump file can be handed straight back to a command. +//----------------------------------------------------------------------------- +static const char *desfire_algo_name(uint8_t algo) { + static const char *tbl[] = {"des", "2tdea", "3tdea", "aes"}; + return (algo < ARRAYLEN(tbl)) ? tbl[algo] : "unknown"; +} + +static const char *desfire_comm_mode_name(uint8_t mode) { + static const char *tbl[] = {"plain", "mac", "plain_rfu", "encrypt"}; + return (mode < ARRAYLEN(tbl)) ? tbl[mode] : "unknown"; +} + +static const char *desfire_file_type_name(uint8_t type) { + static const char *tbl[] = { + "standard", "backup", "value", "linear_record", "cyclic_record", "transaction_mac" + }; + return (type < ARRAYLEN(tbl)) ? tbl[type] : "unknown"; +} + +// JsonSaveBufAsHexCompact() runs through sprint_hex_inrow(), which silently +// truncates past ~4 kbyte. File contents get that big, so build the hex +// string in a right-sized heap buffer instead +static int desfire_json_save_hex(json_t *root, const char *path, const uint8_t *data, size_t datalen) { + + if (data == NULL || datalen == 0) { + return PM3_EINVARG; + } + + char *hex = calloc((datalen * 2) + 1, sizeof(uint8_t)); + if (hex == NULL) { + return PM3_EMALLOC; + } + + for (size_t i = 0; i < datalen; i++) { + snprintf(hex + (i * 2), 3, "%02X", data[i]); + } + + int res = JsonSaveStr(root, path, hex); + free(hex); + return res; +} + +// JsonSaveHex() goes through JsonSaveBufAsHex(), which space-separates the +// bytes. Everything else in this format is compact, so keep 2-byte fields that +// way too +static int desfire_json_save_u16(json_t *root, const char *path, uint16_t value) { + uint8_t b[2] = { value >> 8, value & 0xFF }; + return JsonSaveBufAsHexCompact(root, path, b, sizeof(b)); +} + +static uint8_t desfire_algo_keylen(uint8_t algo) { + switch (algo) { + case T_DES: + return DES_KEY_LEN; + case T_3DES: + return T2DES_KEY_LEN; + case T_3K3DES: + return T3DES_KEY_LEN; + case T_AES: + return AES_KEY_LEN; + default: + return 0; + } +} + +// A key entry exists as soon as we know anything about the key. "Version" +// without "Key" is the normal shape for a key we saw but could not recover -- +// a missing "Key" never means the key is all zeros +static void desfire_json_save_keys(json_t *root, const char *prefix, uint8_t algo, const desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (keys->versionknown[keyno]) { + snprintf(path, sizeof(path), "%s.Keys.%u.Version", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&keys->version[keyno], 1); + } + + if (keys->present[keyno] && keylen) { + snprintf(path, sizeof(path), "%s.Keys.%u.Key", prefix, keyno); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)keys->key[keyno], keylen); + } + } +} + +// The PICC level is application 000000 and takes the same path through here +static void desfire_json_save_app(json_t *root, char *path, size_t pathlen, const desfire_dump_app_t *app) { + + char apath[PATH_MAX_LENGTH] = {0}; + snprintf(apath, sizeof(apath), "$.Applications.%06X", app->aid); + + if (app->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", apath); + desfire_json_save_u16(root, path, app->isofid); + } + + if (app->dfnamelen > 0) { + snprintf(path, pathlen, "%s.DFName", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)app->dfname, app->dfnamelen); + } + + if (app->settings_ok) { + snprintf(path, pathlen, "%s.KeySettings", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->keysettings, 1); + snprintf(path, pathlen, "%s.NumKeysRaw", apath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&app->numkeysraw, 1); + snprintf(path, pathlen, "%s.NumKeys", apath); + JsonSaveInt(root, path, app->numkeys); + snprintf(path, pathlen, "%s.KeyType", apath); + JsonSaveStr(root, path, desfire_algo_name(app->keytype)); + } + + snprintf(path, pathlen, "%s.Authenticated", apath); + JsonSaveBoolean(root, path, app->auth_ok); + + desfire_json_save_keys(root, apath, app->keytype, &app->keys); + + uint8_t filecount = app->filecount; + if (filecount > DESFIRE_MAX_FILE_COUNT) { + filecount = DESFIRE_MAX_FILE_COUNT; + } + + for (uint8_t n = 0; n < filecount; n++) { + + const desfire_dump_file_t *f = &app->files[n]; + char fpath[PATH_MAX_LENGTH] = {0}; + snprintf(fpath, sizeof(fpath), "%s.Files.%02X", apath, f->num); + + if (f->settings_ok) { + snprintf(path, pathlen, "%s.Type", fpath); + JsonSaveStr(root, path, desfire_file_type_name(f->type)); + snprintf(path, pathlen, "%s.TypeRaw", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->type, 1); + snprintf(path, pathlen, "%s.CommMode", fpath); + JsonSaveStr(root, path, desfire_comm_mode_name(f->commmode)); + snprintf(path, pathlen, "%s.AccessRights", fpath); + desfire_json_save_u16(root, path, f->accessrights); + + for (uint8_t a = 0; a < f->addrights_len && a < ARRAYLEN(f->addrights); a++) { + snprintf(path, pathlen, "%s.AdditionalAccessRights.%u", fpath, a); + desfire_json_save_u16(root, path, f->addrights[a]); + } + } + + if (f->isofid != 0) { + snprintf(path, pathlen, "%s.ISOFileID", fpath); + desfire_json_save_u16(root, path, f->isofid); + } + + switch (f->type) { + case 0x00: + case 0x01: { + snprintf(path, pathlen, "%s.FileSize", fpath); + JsonSaveInt(root, path, f->size); + break; + } + case 0x02: { + snprintf(path, pathlen, "%s.LowerLimit", fpath); + JsonSaveInt(root, path, f->lowerlimit); + snprintf(path, pathlen, "%s.UpperLimit", fpath); + JsonSaveInt(root, path, f->upperlimit); + snprintf(path, pathlen, "%s.LimitedCredit", fpath); + JsonSaveBufAsHexCompact(root, path, (uint8_t *)&f->limitedcredit, 1); + if (f->read_ok) { + snprintf(path, pathlen, "%s.Value", fpath); + JsonSaveInt(root, path, f->value); + } + break; + } + case 0x03: + case 0x04: { + snprintf(path, pathlen, "%s.RecordSize", fpath); + JsonSaveInt(root, path, f->recordsize); + snprintf(path, pathlen, "%s.MaxRecords", fpath); + JsonSaveInt(root, path, f->maxrecords); + snprintf(path, pathlen, "%s.CurRecords", fpath); + JsonSaveInt(root, path, f->currecords); + break; + } + default: { + break; + } + } + + // "Read" says whether we got the contents. A reader must not + // treat a missing "Data" as an empty file + snprintf(path, pathlen, "%s.Read", fpath); + JsonSaveBoolean(root, path, f->read_ok); + + if (f->read_ok == false || f->data == NULL || f->datalen == 0) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + // record files are stored one hex string per record + uint32_t reclen = f->recordsize; + if (reclen == 0 || (f->datalen % reclen) != 0) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } else { + for (uint32_t r = 0; r < f->datalen / reclen; r++) { + snprintf(path, pathlen, "%s.Records.%u", fpath, r); + desfire_json_save_hex(root, path, f->data + (r * reclen), reclen); + } + } + } else if (f->type != 0x02) { + snprintf(path, pathlen, "%s.Data", fpath); + desfire_json_save_hex(root, path, f->data, f->datalen); + } + } +} + +static uint8_t desfire_algo_from_name(const char *name) { + if (name == NULL) { + return T_DES; + } + for (uint8_t i = 0; i < DESFIRE_MAX_ALGO_COUNT; i++) { + if (strcmp(name, desfire_algo_name(i)) == 0) { + return i; + } + } + return T_DES; +} + +static uint8_t desfire_comm_mode_from_name(const char *name) { + if (name == NULL) { + return 0; + } + for (uint8_t i = 0; i < 4; i++) { + if (strcmp(name, desfire_comm_mode_name(i)) == 0) { + return i; + } + } + return 0; +} + +static uint32_t json_load_int(json_t *root, const char *path, uint32_t def) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_integer(elm) == false) { + return def; + } + return (uint32_t)json_integer_value(elm); +} + +static const char *json_load_str(json_t *root, const char *path) { + json_t *elm = json_path_get((const json_t *)root, path); + if (json_is_string(elm) == false) { + return NULL; + } + return json_string_value(elm); +} + +// read a hex string of unknown length into a freshly allocated buffer. +// *dst stays NULL when the element is missing or empty +static int desfire_json_load_hex_alloc(json_t *root, const char *path, uint8_t **dst, uint32_t *dstlen) { + + *dst = NULL; + *dstlen = 0; + + const char *hex = json_load_str(root, path); + if (hex == NULL) { + return PM3_SUCCESS; + } + + size_t n = strlen(hex) / 2; + if (n == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc(n, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %zu bytes for `%s`", n, path); + return PM3_EMALLOC; + } + + size_t len = 0; + if (JsonLoadBufAsHex(root, path, buf, n, &len) != 0) { + free(buf); + return PM3_SUCCESS; + } + + *dst = buf; + *dstlen = len; + return PM3_SUCCESS; +} + +// record files are stored one hex string per record. Concatenate them back +// into the flat buffer the rest of the client works with +static int desfire_json_load_records(json_t *root, desfire_dump_file_t *f) { + + char path[PATH_MAX_LENGTH] = {0}; + + // a record file we could not split stays a flat "Data" blob + json_t *recs = json_path_get((const json_t *)root, "$.Records"); + if (json_is_object(recs) == false && json_is_array(recs) == false) { + return desfire_json_load_hex_alloc(root, "$.Data", &f->data, &f->datalen); + } + + // a record file cannot hold more records than the PICC has bytes, so the + // container size is the bound. Records must be contiguous from 0 + size_t bound = json_is_array(recs) ? json_array_size(recs) : json_object_size(recs); + + uint32_t count = 0; + uint32_t reclen = 0; + for (uint32_t r = 0; r < bound; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + const char *hex = json_load_str(root, path); + if (hex == NULL) { + break; + } + if (r == 0) { + reclen = strlen(hex) / 2; + } + count++; + } + + if (count == 0 || reclen == 0) { + return PM3_SUCCESS; + } + + uint8_t *buf = calloc((size_t)count * reclen, sizeof(uint8_t)); + if (buf == NULL) { + PrintAndLogEx(ERR, "loadFileJSONex: failed to allocate %u bytes of record data", count * reclen); + return PM3_EMALLOC; + } + + for (uint32_t r = 0; r < count; r++) { + snprintf(path, sizeof(path), "$.Records.%u", r); + size_t len = 0; + JsonLoadBufAsHex(root, path, buf + ((size_t)r * reclen), reclen, &len); + } + + f->data = buf; + f->datalen = count * reclen; + if (f->recordsize == 0) { + f->recordsize = reclen; + } + return PM3_SUCCESS; +} + +static void desfire_json_load_keys(json_t *root, uint8_t algo, desfire_dump_keys_t *keys) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t keylen = desfire_algo_keylen(algo); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + size_t len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Version", keyno); + if (JsonLoadBufAsHex(root, path, &keys->version[keyno], 1, &len) == 0 && len == 1) { + keys->versionknown[keyno] = 1; + } + + if (keylen == 0) { + continue; + } + + len = 0; + snprintf(path, sizeof(path), "$.Keys.%u.Key", keyno); + if (JsonLoadBufAsHex(root, path, keys->key[keyno], keylen, &len) == 0 && len == keylen) { + keys->present[keyno] = 1; + } + } +} + +// read one application, PICC included, out of the Applications object +static int desfire_json_load_app(json_t *japp, const char *aidstr, desfire_dump_app_t *app) { + + char path[PATH_MAX_LENGTH] = {0}; + uint8_t tmp[2] = {0}; + size_t len = 0; + + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + JsonLoadBufAsHex(japp, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + app->isofid = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(japp, "$.DFName", app->dfname, sizeof(app->dfname), &len); + app->dfnamelen = len; + + len = 0; + JsonLoadBufAsHex(japp, "$.KeySettings", &app->keysettings, 1, &len); + app->settings_ok = (len == 1); + JsonLoadBufAsHex(japp, "$.NumKeysRaw", &app->numkeysraw, 1, &len); + app->numkeys = json_load_int(japp, "$.NumKeys", 0); + app->keytype = desfire_algo_from_name(json_load_str(japp, "$.KeyType")); + app->auth_ok = json_is_true(json_path_get((const json_t *)japp, "$.Authenticated")); + + desfire_json_load_keys(japp, app->keytype, &app->keys); + + json_t *files = json_object_get(japp, "Files"); + if (json_is_object(files) == false) { + return PM3_SUCCESS; + } + + const char *fidstr = NULL; + json_t *jfile = NULL; + + json_object_foreach(files, fidstr, jfile) { + + if (app->filecount >= DESFIRE_MAX_FILE_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d files in application %06X, ignoring the rest", DESFIRE_MAX_FILE_COUNT, app->aid); + break; + } + + desfire_dump_file_t *f = &app->files[app->filecount]; + f->num = strtoul(fidstr, NULL, 16) & 0xFF; + + len = 0; + JsonLoadBufAsHex(jfile, "$.TypeRaw", &f->type, 1, &len); + f->settings_ok = (len == 1); + + f->commmode = desfire_comm_mode_from_name(json_load_str(jfile, "$.CommMode")); + + len = 0; + JsonLoadBufAsHex(jfile, "$.AccessRights", tmp, sizeof(tmp), &len); + if (len == 2) { + f->accessrights = (tmp[0] << 8) | tmp[1]; + } + + len = 0; + JsonLoadBufAsHex(jfile, "$.ISOFileID", tmp, sizeof(tmp), &len); + if (len == 2) { + f->isofid = (tmp[0] << 8) | tmp[1]; + } + + for (uint8_t a = 0; a < ARRAYLEN(f->addrights); a++) { + snprintf(path, sizeof(path), "$.AdditionalAccessRights.%u", a); + len = 0; + JsonLoadBufAsHex(jfile, path, tmp, sizeof(tmp), &len); + if (len != 2) { + break; + } + f->addrights[a] = (tmp[0] << 8) | tmp[1]; + f->addrights_len = a + 1; + } + + f->size = json_load_int(jfile, "$.FileSize", 0); + f->lowerlimit = json_load_int(jfile, "$.LowerLimit", 0); + f->upperlimit = json_load_int(jfile, "$.UpperLimit", 0); + f->value = json_load_int(jfile, "$.Value", 0); + f->recordsize = json_load_int(jfile, "$.RecordSize", 0); + f->maxrecords = json_load_int(jfile, "$.MaxRecords", 0); + f->currecords = json_load_int(jfile, "$.CurRecords", 0); + JsonLoadBufAsHex(jfile, "$.LimitedCredit", &f->limitedcredit, 1, &len); + + f->read_ok = json_is_true(json_path_get((const json_t *)jfile, "$.Read")); + + app->filecount++; + + if (f->read_ok == false) { + continue; + } + + // value files carry their payload in "Value", nothing else to load + if (f->type == 0x02) { + continue; + } + + if (f->type == 0x03 || f->type == 0x04) { + if (desfire_json_load_records(jfile, f) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + continue; + } + + if (desfire_json_load_hex_alloc(jfile, "$.Data", &f->data, &f->datalen) != PM3_SUCCESS) { + return PM3_EMALLOC; + } + } + + return PM3_SUCCESS; +} + +void desfire_dump_free(desfire_dump_t *dump) { + + if (dump == NULL) { + return; + } + + for (uint8_t i = 0; i < DESFIRE_MAX_APP_COUNT; i++) { + for (uint8_t n = 0; n < DESFIRE_MAX_FILE_COUNT; n++) { + free(dump->app[i].files[n].data); + dump->app[i].files[n].data = NULL; + dump->app[i].files[n].datalen = 0; + } + } +} + int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, bool verbose, void (*callback)(json_t *)) { if (ftype != jsfCustom) { if (data == NULL || datalen == 0) { @@ -1062,6 +1559,52 @@ int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, } break; } + case jsfMfDesfire_v1: { + + if (datalen != sizeof(desfire_dump_t)) { + return PM3_EINVARG; + } + + const desfire_dump_t *dump = (const desfire_dump_t *)(const void *)data; + + JsonSaveStr(root, "FileType", "mfdes v1"); + JsonSaveInt(root, "$.Version", 1); + + // $.Card is card identity only. Key settings and keys belong to an + // application, and the PICC level is application 000000 + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", (uint8_t *)dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", (uint8_t *)dump->card_info.atqa, 2); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", (uint8_t *)&dump->card_info.sak, 1); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", (uint8_t *)dump->card_info.ats, dump->card_info.ats_len); + } + } + + if (dump->versionlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.Version", (uint8_t *)dump->version, dump->versionlen); + } + + if (dump->signaturelen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.Signature", (uint8_t *)dump->signature, dump->signaturelen); + } + + if (dump->freemem_ok) { + JsonSaveInt(root, "$.Card.FreeMem", dump->freemem); + } + + desfire_json_save_app(root, path, sizeof(path), &dump->picc); + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + desfire_json_save_app(root, path, sizeof(path), &dump->app[i]); + } + break; + } case jsfCustom: { (*callback)(root); break; @@ -2780,6 +3323,80 @@ int loadFileJSONex(const char *preferredName, void *data, size_t maxdatalen, siz goto out; } + if (!strcmp(ctype, "mfdes v1")) { + + if (maxdatalen < sizeof(desfire_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: buffer too small for a DESFire card image. %zu < %zu", maxdatalen, sizeof(desfire_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + desfire_dump_t *dump = udata.mfdesdump; + memset(dump, 0, sizeof(desfire_dump_t)); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.UID", dump->card_info.uid, sizeof(dump->card_info.uid), &len); + dump->card_info.uidlen = len; + + JsonLoadBufAsHex(root, "$.Card.ATQA", dump->card_info.atqa, sizeof(dump->card_info.atqa), &len); + JsonLoadBufAsHex(root, "$.Card.SAK", &dump->card_info.sak, 1, &len); + + len = 0; + JsonLoadBufAsHex(root, "$.Card.ATS", dump->card_info.ats, sizeof(dump->card_info.ats), &len); + dump->card_info.ats_len = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.Version", dump->version, sizeof(dump->version), &len); + dump->versionlen = len; + + len = 0; + JsonLoadBufAsHex(root, "$.Card.Signature", dump->signature, sizeof(dump->signature), &len); + dump->signaturelen = len; + + json_t *jfree = json_path_get(root, "$.Card.FreeMem"); + if (json_is_integer(jfree)) { + dump->freemem = json_integer_value(jfree); + dump->freemem_ok = true; + } + + dump->picc.aid = 0x000000; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps) == false) { + *datalen = sizeof(desfire_dump_t); + goto out; + } + + const char *aidstr = NULL; + json_t *japp = NULL; + + json_object_foreach(apps, aidstr, japp) { + + // AID 000000 is the PICC level, it is not one of the applications + uint32_t aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + desfire_dump_app_t *app = NULL; + + if (aid == 0x000000) { + app = &dump->picc; + } else { + if (dump->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + app = &dump->app[dump->appcount]; + dump->appcount++; + } + + if (desfire_json_load_app(japp, aidstr, app) != PM3_SUCCESS) { + retval = PM3_EMALLOC; + goto out; + } + } + + *datalen = sizeof(desfire_dump_t); + goto out; + } + if (!strcmp(ctype, "mfdes v2")) { if (maxdatalen < sizeof(desfire_keys_dump_t)) { diff --git a/client/src/fileutils.h b/client/src/fileutils.h index b53077d2e..92b3884cc 100644 --- a/client/src/fileutils.h +++ b/client/src/fileutils.h @@ -42,6 +42,102 @@ typedef struct { desfire_app_keys_t app[DESFIRE_MAX_APP_COUNT]; } desfire_keys_dump_t; +//----------------------------------------------------------------------------- +// DESFire card image, as written by `hf mfdes dump` and read back by +// `hf mfdes view`. See doc/mfdes_dump_format.md for the on-disk JSON schema. +// +// Contents of a file live in a heap buffer hanging off desfire_dump_file_t, +// so the image can hold real file sizes without a multi-megabyte struct. +// Whoever fills or loads one of these owns those buffers -- release them with +// desfire_dump_free() before dropping the image. +//----------------------------------------------------------------------------- + +// keys of one application. The key type is a property of the application, not +// of the individual key, so it lives in desfire_dump_app_t. +// +// A key version is readable without knowing the key, so the two are tracked +// separately: `versionknown` without `present` is the normal case for a key we +// found but could not recover +typedef struct { + uint8_t present[DESFIRE_MAX_KEY_COUNT]; // 1 = we have the key value + uint8_t versionknown[DESFIRE_MAX_KEY_COUNT]; // 1 = we read the key version + uint8_t version[DESFIRE_MAX_KEY_COUNT]; + uint8_t key[DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE]; +} desfire_dump_keys_t; + +typedef struct { + uint8_t num; // file number, 0x00 ... 0x1F + uint16_t isofid; // ISO file id, 0 = none + uint8_t type; // raw file type byte, 0x00 ... 0x05 + uint8_t commmode; // raw file communication mode + uint16_t accessrights; // raw access rights word + uint8_t addrights_len; + uint16_t addrights[16]; // additional access rights + + uint32_t size; // standard / backup data file size + uint32_t lowerlimit; // value file + uint32_t upperlimit; + uint32_t value; + uint8_t limitedcredit; + uint32_t recordsize; // record file + uint32_t maxrecords; + uint32_t currecords; + + bool settings_ok; // file settings were read + + // read_ok false means "we could not read it", which is not the same as + // "the file is empty". Never fill `data` with zeros to paper over it, a + // simulator would then confidently answer with contents the card never had. + bool read_ok; + uint32_t datalen; + uint8_t *data; // heap, NULL when read_ok is false +} desfire_dump_file_t; + +// One application. The PICC level is an application too -- AID 000000 -- and +// uses this same struct, so key settings and keys are always stated against an +// AID instead of floating loose at card level +typedef struct { + uint32_t aid; + uint16_t isofid; + uint8_t dfname[16]; + uint8_t dfnamelen; + + uint8_t keysettings; + uint8_t numkeysraw; + uint8_t numkeys; + uint8_t keytype; // DesfireCryptoAlgorithm, one per application + bool settings_ok; // key settings were read + bool auth_ok; // we authenticated to this application + + desfire_dump_keys_t keys; + + uint8_t filecount; + desfire_dump_file_t files[DESFIRE_MAX_FILE_COUNT]; +} desfire_dump_app_t; + +typedef struct { + // card identity only. Anything key related belongs to an application + iso14a_card_select_t card_info; + + uint8_t version[28]; // raw GetVersion answer + uint8_t versionlen; + uint8_t signature[56]; // NXP originality signature + uint8_t signaturelen; + + uint32_t freemem; + bool freemem_ok; + + desfire_dump_app_t picc; // AID 000000, written as Applications.000000 + + // real applications only, the PICC is not counted here + uint8_t appcount; + desfire_dump_app_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_dump_t; + +// release the per-file heap buffers inside an image. Safe on a NULL pointer +// and safe to call twice. Does not free the image itself. +void desfire_dump_free(desfire_dump_t *dump); + typedef union { void *v; uint8_t *bytes; @@ -51,6 +147,7 @@ typedef union { iso14a_mf_dump_ev1_t *mfc_ev1; iso15_tag_t *iso15; desfire_keys_dump_t *mfdes; + desfire_dump_t *mfdesdump; } udata_t; typedef enum { @@ -79,6 +176,7 @@ typedef enum { jsfCustom, jsfMfDesfireKeys, jsfMfDesfireKeys_v2, + jsfMfDesfire_v1, jsfEM4x05, jsfEM4x69, jsfEM4x50, diff --git a/client/src/util.c b/client/src/util.c index ece98c325..30ce4e0f3 100644 --- a/client/src/util.c +++ b/client/src/util.c @@ -36,7 +36,7 @@ #include "comms.h" // SendCommandNG / WaitForResponseTimeout (set_rgb) #include "pm3_cmd.h" // CMD_PM5_RGB_SET -#define UTIL_BUFFER_SIZE_SPRINT 8196 +#define UTIL_BUFFER_SIZE_SPRINT 16384 // global client debug variable uint8_t g_debugMode = 0; // global client enable/disable printing/logging/grabbing variable diff --git a/doc/commands.json b/doc/commands.json index de3f411ec..5b8bb2cdc 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -5996,9 +5996,10 @@ "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", "--ns no save to file", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--sk Save extracted keys to binary file" ], - "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns]" + "usage": "hf mf dump [-hv] [-f ] [-k ] [--mini] [--1k] [--2k] [--4k] [--ns] [--sk]" }, "hf mf ecfill": { "command": "hf mf ecfill", @@ -7145,16 +7146,18 @@ "command": "hf mf view", "description": "Print a MIFARE Classic dump file (bin/eml/json)", "notes": [ - "hf mf view -f hf-mf-01020304-dump.bin" + "hf mf view -f hf-mf-01020304-dump.bin", + "hf mf view --selftest" ], "offline": true, "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", "-v, --verbose verbose output", - "--sk Save extracted keys to binary file" + "--sk Save extracted keys to binary file", + "--selftest Run the dump parsers self tests and exit" ], - "usage": "hf mf view [-hv] -f [--sk]" + "usage": "hf mf view [-hv] [-f ] [--sk] [--selftest]" }, "hf mf wipe": { "command": "hf mf wipe", @@ -7853,9 +7856,12 @@ }, "hf mfdes dump": { "command": "hf mfdes dump", - "description": "For each application show fil list and then file content. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", + "description": "Dump a DESFire card to a json file. Walks every application and every file unless an application is named with --aid / --isoid / --dfname. Key needs to be provided for authentication or flag --no-auth set (depend on cards settings).", "notes": [ - "hf mfdes dump --aid 123456 -> show file dump for: app=123456 with channel defaults from `default` command/nhf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" + "hf mfdes dump -> dump the whole PICC with channel defaults from `default` command", + "hf mfdes dump --aid 123456 -> dump only application 123456", + "hf mfdes dump --keys hf-mfdes-0102030405-keys.json -> use recovered keys per application", + "hf mfdes dump --isoid df01 --schann lrp -t aes --length 000090 -> lrp default settings with length limit" ], "offline": false, "options": [ @@ -7874,9 +7880,12 @@ "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian)", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", "-l, --length Maximum length for read data files (3 hex bytes, big endian)", - "--no-auth Execute without authentication" + "--no-auth Execute without authentication", + "-f, --file Save dump to file, if no UID will be used as filename", + "--keys Load application keys from a `hf mfdes chk` key file", + "--ns No save to file" ], - "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth]" + "usage": "hf mfdes dump [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-l ] [--no-auth] [-f ] [--keys ] [--ns]" }, "hf mfdes formatpicc": { "command": "hf mfdes formatpicc", @@ -8189,7 +8198,7 @@ }, "hf mfdes help": { "command": "hf mfdes help", - "description": "help This help list List DESFire (ISO 14443A) history makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List DESFire (ISO 14443A) history view Display content from tag dump file makemfclicense Generate a Mifare Classic license for DESFire EV3C test Regression crypto tests --------------------------------------------------------------------------------------- hf mfdes list available offline: yes Alias of `trace list -t des -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf mfdes list --frame -> show frame delay times", "hf mfdes list -1 -> use trace buffer" @@ -8630,6 +8639,20 @@ ], "usage": "hf mfdes verifycert [-hav] [] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [--fid ] [--no-auth] [--ca ]... [--keyaid ] [--keyisoid ] [--keydfname ] [--keyidx ] [--validatemethod ] [--readmethod ]" }, + "hf mfdes view": { + "command": "hf mfdes view", + "description": "Print a DESFire card dump file (json)", + "notes": [ + "hf mfdes view -f hf-mfdes-01020304050607-dump.json" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-f, --file Filename of dump", + "-v, --verbose Verbose output" + ], + "usage": "hf mfdes view [-hv] -f " + }, "hf mfdes write": { "command": "hf mfdes write", "description": "Write data from file. Key needs to be provided or flag --no-auth set (depend on file settings).", @@ -16221,7 +16244,7 @@ "command": "smart raw", "description": "Sends raw bytes to card", "notes": [ - "smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", + "smart raw --t0 -s -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR", "smart raw --t0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory", "smart raw --t0 -t -d 00a4040007a0000000041010 -> Mastercard", "smart raw --t0 -t -d 00a4040007a0000000031010 -> Visa", @@ -16538,8 +16561,8 @@ } }, "metadata": { - "commands_extracted": 920, + "commands_extracted": 921, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-12T19:49:38+00:00" + "extracted_on": "2026-09-14T06:50:14+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 2153754e6..4f2c8c2d8 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -817,6 +817,7 @@ Check column "offline" for their availability. |`hf mfdes getfileisoids `|N |`Get File ISO IDs list` |`hf mfdes lsfiles `|N |`Show all files list` |`hf mfdes dump `|N |`Dump all files` +|`hf mfdes view `|Y |`Display content from tag dump file` |`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/doc/mfdes_dump_format.md b/doc/mfdes_dump_format.md index bd6520954..970d1605c 100644 --- a/doc/mfdes_dump_format.md +++ b/doc/mfdes_dump_format.md @@ -342,6 +342,9 @@ hf mfdes chk -k 00000000000000000000000000000000 -j hf-mfdes-043240CAE45380-keys # and dump it hf mfdes dump -t 2tdea -k 00000000000000000000000000000000 + +# to put the card back the way it was +hf mfdes formatpicc -t 2tdea -k 00000000000000000000000000000000 ``` Without that `chk` run, application `112233` cannot be opened with the 2TDEA @@ -525,8 +528,11 @@ The dump picks this file up without `--keys` because its name follows the same Things to read out of it: -* **`FreeMem` is 896**, not the 2080 a blank card reports. The applications and - files took the rest. +* **`FreeMem` is 896** with the two applications in place. Measured on this same + card: 2080 free before the example was built, 896 with it, and 2560 after + `hf mfdes formatpicc`. A format therefore reclaims space that creating and + deleting applications leaves behind -- 0 applications on its own does not mean + a fully free card. * **`NumKeysRaw` `83`** decodes to `KeyType: aes` (top bits 10), ISO file ids enabled (bit 5) and `NumKeys: 3`. * **Keys 1 and 2 of `112233` have a `Version` but no `Key`.** They exist, we From 82783eae26ceabdbe5118c3120d84cf01fc836ca Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 09:19:05 +0200 Subject: [PATCH 3/5] hf mf: decode the Hexact payload Sectors 9 and 11 were printed raw and marked 'not decoded'. - remove the XOR keystream and print the ten eight byte records - check the eighteen record bytes that are XOR combinations of sector 0, sector 15 and the UID, plus three record to record ties - 'hf mf view --selftest' now covers the decoder, using a synthetic card - sector 15 marker compare ignores case, factory blanks were not matched - an all FF or all 00 payload is named, not decrypted - sector 15 block 2 is text on a blank, so only read a serial there when the first four bytes are not printable Research. The remaining 58 payload bytes are issuer data and are printed without interpretation. Co-Authored-By: Claude Opus 5 (1M context) --- client/src/cmdhfmf.c | 6 +- client/src/parsers/parsehexact.c | 357 +++++++++++++++++++++++++++++-- client/src/parsers/parsehexact.h | 3 + 3 files changed, 344 insertions(+), 22 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index ce9eef35f..70e7401c7 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -8543,7 +8543,11 @@ static int CmdHF14AMfView(const char *Cmd) { CLIParserFree(ctx); if (selftest) { - return vigik_selftest(); + int res = vigik_selftest(); + if (res != PM3_SUCCESS) { + return res; + } + return hexact_selftest(); } if (fnlen == 0) { diff --git a/client/src/parsers/parsehexact.c b/client/src/parsers/parsehexact.c index abe2d4e85..7aeff6897 100644 --- a/client/src/parsers/parsehexact.c +++ b/client/src/parsers/parsehexact.c @@ -26,14 +26,25 @@ // the number printed on the fob, little endian // sector 16, 17 MIFARE Classic EV1 signature, not application data // -// The sector 9 and 11 payload is not decoded. It carries no structure in common -// between two cards, so it is enciphered with something not held here, and -// printing a guess at fields would be inventing them. +// The sector 9 and 11 payload is XORed with an estate wide keystream that is +// one seed byte per block rotated left by the byte index, +// +// mask[k] = rotl(seed, k mod 8) seed = base ^ (2 * block in sector) +// base = 0xB3 for sector 9, 0x5C for sector 11 +// +// so the whole eighty byte keystream comes from two bytes. Removing it leaves +// ten eight byte records. Eighteen of their eighty bytes are XOR combinations +// of data that is readable elsewhere on the card, and three more are fixed +// relations between the records themselves, which together make a consistency +// check: a card assembled from parts, or a payload copied onto a different +// UID, fails it. The other bytes are keyed issuer data and stay unexplained, +// so they are printed and not interpreted. //----------------------------------------------------------------------------- #include "parsehexact.h" #include +#include // tolower #include "commonutil.h" #include "ui.h" // PrintAndLogEx @@ -45,9 +56,14 @@ #define HEXACT_DATA_SECTOR_A 9 #define HEXACT_DATA_SECTOR_B 11 -// Sector 15 block 0 spells the system out and is identical on every card seen +// Sector 15 block 0 spells the system out. The text is the same on every card +// but the case is not: factory blanks of an older generation carry +// "HEXACT - COGELEC" and the personalised fobs carry "hExact - COGELEC", so the +// compare has to ignore case or it misses half the cards. Sector 15 is written +// at the factory and then locked read only, which is why one card cannot have +// both spellings. static const uint8_t hexact_marker[] = { - 'h', 'E', 'x', 'a', 'c', 't', ' ', '-', ' ', 'C', 'O', 'G', 'E', 'L', 'E', 'C' + 'h', 'e', 'x', 'a', 'c', 't', ' ', '-', ' ', 'c', 'o', 'g', 'e', 'l', 'e', 'c' }; // Block 0 of these cards advertises SAK 0x88 while the tag itself answers 0x08. @@ -55,6 +71,140 @@ static const uint8_t hexact_marker[] = { // which is how the readers spot a clone. #define HEXACT_BLOCK0_SAK 0x88 +// The payload keystream. One seed byte per block, rotated left by the byte +// index, so it repeats every eight bytes and the whole eighty byte stream comes +// from the two base values below. +#define HEXACT_SEED_BASE_A 0xB3 +#define HEXACT_SEED_BASE_B 0x5C + +// The five payload blocks, in the order the cross checks below index them +static const struct { + uint8_t sector; + uint8_t blk; +} hexact_payload[] = { + {HEXACT_DATA_SECTOR_A, 0}, {HEXACT_DATA_SECTOR_A, 1}, {HEXACT_DATA_SECTOR_A, 2}, + {HEXACT_DATA_SECTOR_B, 0}, {HEXACT_DATA_SECTOR_B, 1}, +}; +#define HEXACT_PAYLOAD_BLOCKS ARRAYLEN(hexact_payload) + +// Where a recovered byte has to come from. idx picks the identifier byte, and +// for HX_ID_SER the serial byte at the same index. The record adds a fixed +// constant on top, which is why xr is there. +typedef enum { + HX_ID, // identifier[idx] + HX_ID_SER, // identifier[idx] ^ serial[idx] + HX_ID_UID, // identifier[idx] ^ uid[0] ^ uid[2] +} hexact_src_t; + +typedef struct { + uint8_t rec; + uint8_t pos; + hexact_src_t src; + uint8_t idx; + uint8_t xr; +} hexact_check_t; + +static const hexact_check_t hexact_checks[] = { + {0, 0, HX_ID_SER, 0, 0xFF}, {0, 1, HX_ID_SER, 1, 0xFF}, + {0, 4, HX_ID, 4, 0xFE}, {0, 7, HX_ID_UID, 7, 0x00}, + {1, 1, HX_ID, 1, 0x00}, {1, 4, HX_ID, 4, 0x00}, + {1, 15, HX_ID_UID, 7, 0x00}, + {2, 0, HX_ID, 0, 0x00}, {2, 1, HX_ID, 1, 0x00}, + {2, 4, HX_ID, 4, 0x00}, {2, 7, HX_ID, 7, 0x00}, + {3, 0, HX_ID, 0, 0x36}, {3, 1, HX_ID, 1, 0x80}, + {3, 7, HX_ID_UID, 7, 0x00}, {3, 13, HX_ID, 5, 0x00}, + {4, 1, HX_ID, 1, 0x00}, {4, 13, HX_ID, 5, 0x00}, + {4, 15, HX_ID_UID, 7, 0x00}, +}; + +static uint8_t hexact_rotl(uint8_t v, uint8_t n) { + n &= 7; + if (n == 0) { + return v; + } + return (uint8_t)((v << n) | (v >> (8 - n))); +} + +static uint8_t hexact_seed(uint8_t sector, uint8_t blk) { + uint8_t base = (sector == HEXACT_DATA_SECTOR_A) ? HEXACT_SEED_BASE_A : HEXACT_SEED_BASE_B; + return base ^ (uint8_t)(2 * blk); +} + +// Strip the keystream from one payload block +static void hexact_decrypt(const uint8_t *in, uint8_t sector, uint8_t blk, uint8_t *out) { + uint8_t s = hexact_seed(sector, blk); + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + out[k] = in[k] ^ hexact_rotl(s, k); + } +} + +static uint8_t hexact_expect(const hexact_check_t *c, const uint8_t *idn, + const uint8_t *uid, const uint8_t *ser) { + uint8_t v = idn[c->idx] ^ c->xr; + if (c->src == HX_ID_SER && c->idx < 4) { + v ^= ser[c->idx]; + } else if (c->src == HX_ID_UID) { + v ^= uid[0] ^ uid[2]; + } + return v; +} + + +// Run the 21 checks. Eighteen tie a record byte to card data held elsewhere, +// three tie the records to each other. Returns how many passed. +#define HEXACT_MAX_SHOWN 5 + +static uint8_t hexact_cross_check(const uint8_t rec[][MFBLOCK_SIZE], const uint8_t *idn, + const uint8_t *uid, const uint8_t *ser, + uint8_t *total, bool verbose) { + uint8_t pass = 0, shown = 0; + *total = 0; + + for (size_t i = 0; i < ARRAYLEN(hexact_checks); i++) { + const hexact_check_t *c = &hexact_checks[i]; + uint8_t want = hexact_expect(c, idn, uid, ser); + (*total)++; + if (rec[c->rec][c->pos] == want) { + pass++; + } else if (verbose && shown++ < HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " mismatch......... sector %2u blk %u byte %2u is %02X, expected %02X", + hexact_payload[c->rec].sector, hexact_payload[c->rec].blk, + c->pos, rec[c->rec][c->pos], want); + } + } + + // byte 7 of the records is a lag two sliding window over two seeds, one of + // them idn[7]; these three ties are what is left of it after the card data + // checks above have taken the rest + const uint8_t tie_got[3] = { rec[2][15], rec[0][15], rec[3][15] }; + const uint8_t tie_want[3] = { rec[1][7], + (uint8_t)(rec[1][7] ^ uid[1] ^ 0xD0), + (uint8_t)(rec[0][15] ^ 0xB1) }; + for (size_t i = 0; i < ARRAYLEN(tie_got); i++) { + (*total)++; + if (tie_got[i] == tie_want[i]) { + pass++; + } else if (verbose && shown++ < HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " mismatch......... record tie %zu is %02X, expected %02X", + i, tie_got[i], tie_want[i]); + } + } + + if (verbose && shown > HEXACT_MAX_SHOWN) { + PrintAndLogEx(INFO, " ................. and %u more", shown - HEXACT_MAX_SHOWN); + } + return pass; +} + +static bool hexact_all_printable(const uint8_t *p, size_t len) { + for (size_t i = 0; i < len; i++) { + if (isprint(p[i]) == 0) { + return false; + } + } + return true; +} + static const uint8_t *hexact_sector(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block) { size_t off = (mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE; if (off + MFBLOCK_SIZE > dumplen) { @@ -68,7 +218,12 @@ bool is_valid_hexact_card(const uint8_t *dump, size_t dumplen) { if (p == NULL) { return false; } - return (memcmp(p, hexact_marker, sizeof(hexact_marker)) == 0); + for (size_t i = 0; i < sizeof(hexact_marker); i++) { + if (tolower(p[i]) != hexact_marker[i]) { + return false; + } + } + return true; } int hexact_parser_parse(const uint8_t *dump, size_t dumplen) { @@ -87,7 +242,7 @@ int hexact_parser_parse(const uint8_t *dump, size_t dumplen) { // The sector spells the system out across its three blocks and it reads as // one line, so join them. Each block pads its text with spaces, and the // last one keeps four bytes of its own before the text starts. - char system[16 + 16 + 12 + 3] = {0}; + char system[16 + 16 + 16 + 3] = {0}; str_append(system, sizeof(system), "%.16s", (const char *)id0); str_trim(system); @@ -96,17 +251,25 @@ int hexact_parser_parse(const uint8_t *dump, size_t dumplen) { str_trim(system); } + // Sector 15 block 2 holds the number engraved on the fob, little endian, + // in front of the INTRATONE text. Checked against the engraving on four + // fobs, all four matched. A card that was never personalised carries text + // all the way across instead, and reading its first four bytes as a number + // gives nonsense, so let the data say which shape this is. + bool has_serial = (id2 != NULL) && (hexact_all_printable(id2, 4) == false); + if (id2) { - str_append(system, sizeof(system), " %.12s", (const char *)(id2 + 4)); + if (has_serial) { + str_append(system, sizeof(system), " %.12s", (const char *)(id2 + 4)); + } else { + str_append(system, sizeof(system), " %.16s", (const char *)id2); + } str_trim(system); } PrintAndLogEx(INFO, "System............. " _YELLOW_("%s"), system); - // Sector 15 block 2 keeps the number engraved on the fob as a little endian - // value in front of the INTRATONE text. Checked against the engraving on - // four fobs, all four matched. - if (id2) { + if (has_serial) { PrintAndLogEx(INFO, "Printed serial..... " _YELLOW_("%u"), MemLeToUint4byte(id2)); } @@ -122,19 +285,171 @@ int hexact_parser_parse(const uint8_t *dump, size_t dumplen) { PrintAndLogEx(INFO, " the tag answers 0x08, a clone written with this block 0 answers 0x88"); } - const uint8_t *a = hexact_sector(dump, dumplen, HEXACT_DATA_SECTOR_A, 0); - const uint8_t *b = hexact_sector(dump, dumplen, HEXACT_DATA_SECTOR_B, 0); - if (a == NULL || b == NULL) { + if (s0b2 == NULL || id2 == NULL) { return PM3_SUCCESS; } - PrintAndLogEx(INFO, "Payload............ sector %u and %u, " _YELLOW_("not decoded"), + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + const uint8_t *p = hexact_sector(dump, dumplen, hexact_payload[i].sector, hexact_payload[i].blk); + if (p == NULL) { + return PM3_SUCCESS; + } + hexact_decrypt(p, hexact_payload[i].sector, hexact_payload[i].blk, rec[i]); + } + + // Two states are not a payload at all and decrypting them just prints the + // keystream back with every check failing. All zero means the dump never + // read those sectors. All FF means the card was never personalised: a + // factory blank has its payload erased, and sector 15 block 2 says so. + bool all_zero = true, all_ff = true; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + const uint8_t *p = hexact_sector(dump, dumplen, hexact_payload[i].sector, hexact_payload[i].blk); + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + if (p[k] != 0x00) { + all_zero = false; + } + if (p[k] != 0xFF) { + all_ff = false; + } + } + } + if (all_zero || all_ff) { + PrintAndLogEx(INFO, "Payload............ sector %u and %u, " _YELLOW_("%s"), + HEXACT_DATA_SECTOR_A, HEXACT_DATA_SECTOR_B, + all_ff ? "erased, card not personalised" : "not read"); + return PM3_SUCCESS; + } + + PrintAndLogEx(INFO, "Payload............ sector %u and %u, " _YELLOW_("mask removed"), HEXACT_DATA_SECTOR_A, HEXACT_DATA_SECTOR_B); - for (uint8_t blk = 0; blk < 3; blk++) { - PrintAndLogEx(INFO, " sector %2u blk %u.. %s", HEXACT_DATA_SECTOR_A, blk, sprint_hex_inrow(a + (blk * MFBLOCK_SIZE), MFBLOCK_SIZE)); - } - for (uint8_t blk = 0; blk < 3; blk++) { - PrintAndLogEx(INFO, " sector %2u blk %u.. %s", HEXACT_DATA_SECTOR_B, blk, sprint_hex_inrow(b + (blk * MFBLOCK_SIZE), MFBLOCK_SIZE)); + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + // the two eight byte records of the block, kept apart on the line. + // sprint_hex_inrow hands back one static buffer, so the first half has + // to be copied out before the second call overwrites it + char line[(2 * 16) + 4] = {0}; + str_append(line, sizeof(line), "%s ", sprint_hex_inrow(rec[i], 8)); + str_append(line, sizeof(line), "%s", sprint_hex_inrow(rec[i] + 8, 8)); + PrintAndLogEx(INFO, " sector %2u blk %u.. %s", + hexact_payload[i].sector, hexact_payload[i].blk, line); } + + // Eighteen of those bytes have to equal card data held in sector 0 and + // sector 15, and three more tie the records to each other. Together they + // say whether the payload was issued for this fob: a payload copied onto + // another UID breaks the uid terms, a rewritten sector 0 breaks the rest. + const uint8_t *uid = dump; + uint8_t ser[4]; + memcpy(ser, id2, sizeof(ser)); + + uint8_t total = 0; + uint8_t pass = hexact_cross_check(rec, s0b2, uid, ser, &total, true); + + // Say what this does and does not mean. The 21 checks read 22 of the 80 + // payload bytes, so a random single byte change anywhere in the payload is + // caught 27.5% of the time, and a payload assembled from two fobs can pass. + // Only uid1 and uid0^uid2 enter, so 2^16 of the 2^32 UIDs accept a copy of + // this payload unaltered. It is an integrity check, not an authenticity one. + PrintAndLogEx(INFO, "Cross checks....... %u / %u ( %s )", pass, total, + (pass == total) ? _GREEN_("bound bytes agree with sector 0, 15 and the UID") + : _RED_("bound bytes disagree, see above")); + PrintAndLogEx(INFO, " %u of 80 payload bytes are issuer data and unchecked", + 80 - 22); + return PM3_SUCCESS; +} + +// Build a card from the model rather than from a real fob: the record bytes +// that the checks look at are filled in from a made up UID, identifier and +// serial, the rest with a pattern, and the whole payload is then masked. No +// resident's credential goes into the tree. This exercises the mask and the +// cross check; the printing path is covered by running the parser on a dump. +static void hexact_build_selftest_card(uint8_t *dump, uint8_t v1) { + static const uint8_t uid[4] = {0x1A, 0x2B, 0x3C, 0x61}; + static const uint8_t idn[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; + static const uint8_t ser[4] = {0xD2, 0x04, 0x00, 0x00}; // 1234 little endian + + memcpy(dump, uid, sizeof(uid)); + dump[4] = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]; + dump[5] = HEXACT_BLOCK0_SAK; + dump[6] = 0x04; + memcpy(dump + (2 * MFBLOCK_SIZE), idn, sizeof(idn)); + memcpy(dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) * MFBLOCK_SIZE), + hexact_marker, sizeof(hexact_marker)); + memcpy(dump + ((mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE), + ser, sizeof(ser)); + + uint8_t v3 = v1 ^ uid[1] ^ 0xD0; + + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + rec[i][k] = (uint8_t)(0xA0 + (i * MFBLOCK_SIZE) + k); // filler + } + } + for (size_t i = 0; i < ARRAYLEN(hexact_checks); i++) { + const hexact_check_t *c = &hexact_checks[i]; + rec[c->rec][c->pos] = hexact_expect(c, idn, uid, ser); + } + rec[1][7] = v1; + rec[2][15] = v1; + rec[4][7] = v1; + rec[0][15] = v3; + rec[3][15] = v3 ^ 0xB1; + + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + uint8_t seed = hexact_seed(hexact_payload[i].sector, hexact_payload[i].blk); + uint8_t *dst = dump + ((mfFirstBlockOfSector(hexact_payload[i].sector) + + hexact_payload[i].blk) * MFBLOCK_SIZE); + for (uint8_t k = 0; k < MFBLOCK_SIZE; k++) { + dst[k] = rec[i][k] ^ hexact_rotl(seed, k); + } + } +} + +int hexact_selftest(void) { + + PrintAndLogEx(INFO, "Testing Hexact payload mask and cross checks"); + + uint8_t dump[MIFARE_1K_MAX_BYTES] = {0}; + hexact_build_selftest_card(dump, 0x5A); + + if (is_valid_hexact_card(dump, sizeof(dump)) == false) { + PrintAndLogEx(FAILED, " card not recognised ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + // the decoder has to recover the records the builder put in + uint8_t rec[HEXACT_PAYLOAD_BLOCKS][MFBLOCK_SIZE]; + for (uint8_t i = 0; i < HEXACT_PAYLOAD_BLOCKS; i++) { + hexact_decrypt(dump + ((mfFirstBlockOfSector(hexact_payload[i].sector) + + hexact_payload[i].blk) * MFBLOCK_SIZE), + hexact_payload[i].sector, hexact_payload[i].blk, rec[i]); + } + + uint8_t total = 0; + uint8_t pass = hexact_cross_check(rec, dump + (2 * MFBLOCK_SIZE), dump, + dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE, + &total, false); + PrintAndLogEx(INFO, " intact card........ %u / %u ( %s )", pass, total, + (pass == total) ? _GREEN_("ok") : _RED_("fail")); + if (pass != total) { + return PM3_ESOFT; + } + + // and a negative, so a decoder that always says yes cannot pass this test. + // Flipping a bit in uid0 must break exactly the four positions that carry + // uid0^uid2. uid1 enters only through a record tie, which reads the card's + // own bytes and so is unaffected here. + dump[0] ^= 0x01; + uint8_t broken = hexact_cross_check(rec, dump + (2 * MFBLOCK_SIZE), dump, + dump + (mfFirstBlockOfSector(HEXACT_ID_SECTOR) + 2) * MFBLOCK_SIZE, + &total, false); + PrintAndLogEx(INFO, " one UID bit flipped %u / %u ( %s )", broken, total, + (broken == total - 4) ? _GREEN_("ok") : _RED_("fail")); + if (broken != total - 4) { + return PM3_ESOFT; + } + + PrintAndLogEx(SUCCESS, "Hexact self test " _GREEN_("passed")); return PM3_SUCCESS; } diff --git a/client/src/parsers/parsehexact.h b/client/src/parsers/parsehexact.h index 5c387d795..66eaebaaf 100644 --- a/client/src/parsers/parsehexact.h +++ b/client/src/parsers/parsehexact.h @@ -27,4 +27,7 @@ bool is_valid_hexact_card(const uint8_t *dump, size_t dumplen); // Print what is known about the layout of a Hexact card int hexact_parser_parse(const uint8_t *dump, size_t dumplen); +// Decode a card built from the model and check the decoder agrees, both ways +int hexact_selftest(void); + #endif From 9b60b1b2186e6acce9f6ec0b18ecb6840a5b678f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 09:19:17 +0200 Subject: [PATCH 4/5] missing define --- include/desfire.h | 1 + 1 file changed, 1 insertion(+) diff --git a/include/desfire.h b/include/desfire.h index 298acc069..7e3e7a0fe 100644 --- a/include/desfire.h +++ b/include/desfire.h @@ -33,6 +33,7 @@ typedef enum { #define DESFIRE_MAX_ALGO_COUNT 4 // T_DES ... T_AES #define DESFIRE_MAX_KEY_COUNT 0x0E // key numbers 0x00 ... 0x0D #define DESFIRE_MAX_APP_COUNT 64 // applications we keep track of per PICC +#define DESFIRE_MAX_FILE_COUNT 32 // file numbers 0x00 ... 0x1F // Keys recovered for one application. // keys[algo][keyno][0] is the found flag, keys[algo][keyno][1..] the key itself. From cac7378e95421ffa2df1e7d7d2eddbba05ae904e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 14 Sep 2026 09:19:29 +0200 Subject: [PATCH 5/5] text --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb82e055a..26416eb99 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] +- Changed `hf mf view --selftest` - now also checks the Hexact payload decoder, both ways (@iceman1001) +- Changed `hf mf view` - Hexact sector 9,11 payload is now decoded and cross checked against sector 0,15 and UID (@iceman1001) - Added `hf mfdes dump` - now walks the whole PICC and saves a `hf-mfdes--dump.json` card image, picking up `hf-mfdes--keys.json` on its own (@iceman1001) - Added `hf mfdes view` - print a DESFire card dump file, no device needed (@iceman1001) - Fixed `sprint_hex` - a buffer twice the old size, so printing a long block no longer runs off the end of the static buffer (@iceman1001)