From 6150d8fc572c258df93318d44e15c66fea901cd5 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 19 Sep 2026 21:02:07 +0200 Subject: [PATCH 01/11] "Starting today in version 2.1.277, if there is no CLAUDE.md in a folder, Claude will check for and use AGENTS.md." --- CLAUDE.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 28470f8d2..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,3 +0,0 @@ -# Instructions - -See [AGENTS.md](./AGENTS.md) for coding, build, and PR guidelines. This project keeps a single source of truth in AGENTS.md rather than duplicating instructions per tool. From 4ea8207400d405753cea3818426a4287661f7016 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Tue, 22 Sep 2026 04:32:14 +0800 Subject: [PATCH 02/11] doc: 15693 magic card --- doc/magic_cards_notes.md | 101 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 2 deletions(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 2d5a7d1de..89cf88314 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -2685,9 +2685,95 @@ More commands to follow. Be careful with some. ^[Top](#top) +Three kinds of UID changeable ISO15693 tags are known, called V1 (Gen1), V2 (Gen2) and V3 (Gen3) here. +`hf 15 info` only matches the UID prefix against its vendor list, so it can't tell them apart from genuine tags. + ### Identify -**TODO** +^[Top](#top) + +| Kind | Blocks on tags tested | Set UID with | +|------|-----------------------|--------------| +| V1 (Gen1) | 28/40/56 | `hf 15 csetuid` | +| V2 (Gen2) | 64 | `hf 15 csetuid --v2` | +| V3 (Gen3) | 80 | `hf 15 csetuid --v3`, then `hf 15 cfinalize` | + +The block counts come from the few tags tested, they are only a hint. + +The same kind of magic can behave a bit differently between manufacturers, for example the block layout, +or how the V1 backdoor blocks answer to read and write commands. What is described here comes from the tags tested. + +V1: no reliable way to identify it, the only sure check is to set a UID and see if it changes. +On the V1 tags tested, reading blocks `0x38`, `0x39`, `0x3E` and `0x3F` fails while writing `0x38` and `0x39` works. That may be a hint but it is not confirmed. + +``` +hf 15 raw -ac -d 022038 # command failed on the V1 tags tested +``` + +V2: no passive identification known. It uses the custom command `0xE0`, which genuine tags do not implement. + +V3: blocks `0x14` and `0x15` hold a signature while the tag is not finalized. + +``` +hf 15 raw -ac -d 022014 # A5 2B 44 2C +hf 15 raw -ac -d 022015 # 21 AE 93 00 (69 E2 5D 00 after finalize) +``` + + + +### V1 (Gen1) + +^[Top](#top) + +The UID is written to blocks `0x38` and `0x39` with plain `WRITEBLOCK`, each holding four UID bytes in reverse order. +Blocks `0x3E` and `0x3F` are written first as an unlock, this is what `hf 15 csetuid` sends for `E011223344556677`: + +``` +hf 15 raw -acw -d 02213E00000000 +hf 15 raw -acw -d 02213F69960000 +hf 15 raw -acw -d 02213877665544 +hf 15 raw -acw -d 022139332211E0 +``` + +On the tags tested, writing only `0x38` and `0x39` is enough, the new UID is active immediately. +`0x3E` and `0x3F` accept the unlock values once, later writes fail with `command failed`. + +### V2 (Gen2) + +^[Top](#top) + +Uses the custom command `0xE0`, this is what `hf 15 csetuid --v2` sends for `E011223344556677`: + +``` +hf 15 raw -acw -d 02E009473F038B00 +hf 15 raw -acw -d 02E0095200000000 +hf 15 raw -acw -d 02E0094077665544 +hf 15 raw -acw -d 02E00941332211E0 +``` + +On the V2 tag tested, block `0x38` reads as normal memory, a `WRITEBLOCK` to it is refused with error code 3 (option not supported) unless the request flags carry the option flag (`42` instead of `02`). + +### V3 (Gen3) + +^[Top](#top) + +The UID sits in blocks `0x10` (last four bytes, reversed) and `0x11` (first four bytes, reversed). +It can be rewritten as often as needed until the tag is finalized: + +``` +hf 15 raw -acw -d 02211077665544 +hf 15 raw -acw -d 022111332211E0 +``` + +Finalize locks the UID for good and can't be undone, block `0x15` changes to `69 E2 5D 00`: + +``` +hf 15 raw -acw -d 022114A52B442C +hf 15 raw -acw -d 02211569E25D00 +``` + +**WARNING!** Writing anything other than these two finalize values to blocks `0x14` and `0x15` bricks the tag. + ### Proxmark3 commands @@ -2696,9 +2782,20 @@ More commands to follow. Be careful with some. Always set a UID starting with `E0`. ``` -hf 15 csetuid E011223344556677 +hf 15 csetuid -u E011223344556677 # V1 +hf 15 csetuid -u E011223344556677 --v2 # V2 +hf 15 csetuid -u E011223344556677 --v3 # V3 +hf 15 cfinalize -y # V3, irreversible ``` +Before writing, `csetuid` checks that the tag looks like the selected kind: + +* V1 reads blocks `0x38`, `0x39`, `0x3E`, `0x3F` and stops if one holds data other than `00000000` (or `69960000` in `0x3F`), + or if a read fails other than with no answer / block not available. + If the write or the UID check fails and the tag still shows its original UID, it writes those four blocks back to `00000000`. +* V3 stops unless blocks `0x14` and `0x15` still hold the un-finalized signature, `cfinalize` does the same. +* V2 has no check, the `0xE0` command is ignored by genuine tags. + or (ignore errors): ``` From 6775a78a10532ccdbff15591b02b2a839c8d0043 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Tue, 22 Sep 2026 05:37:09 +0800 Subject: [PATCH 03/11] fix: preserve UTF-8 in generated command docs Transcode the MinGW client's CP850 output before writing command documentation and force Python to read the converted stream as UTF-8. Normalize the remaining escaped Greek mu strings to the project's micro sign convention. Co-Authored-By: OpenAI Codex --- Makefile | 11 +++++++++-- client/src/cmdlfhitag.c | 7 +++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 556ee5341..3ef4f1ab4 100644 --- a/Makefile +++ b/Makefile @@ -354,13 +354,20 @@ style: commands --style=google --unpad-paren --pad-header \ --align-pointer=name {} \; +COMMANDS_UTF8_FILTER := cat +COMMANDS_PYTHON := python3 +ifdef IS_MINGW + COMMANDS_UTF8_FILTER := iconv -f CP850 -t UTF-8 + COMMANDS_PYTHON := PYTHONIOENCODING=utf-8 python3 +endif + commands: client # Update commands.md - [ -x client/proxmark3 ] && client/proxmark3 -m | tr -d '\r' > doc/commands.md + [ -x client/proxmark3 ] && client/proxmark3 -m | $(COMMANDS_UTF8_FILTER) | tr -d '\r' > doc/commands.md # Make sure python3 is installed @command -v python3 >/dev/null || ( echo "Please install 'python3' package first" ; exit 1 ) # Update commands.json, patch port in case it was run under Windows - [ -x client/proxmark3 ] && client/proxmark3 --fulltext | sed 's#com[0-9]#/dev/ttyACM0#'|python3 client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json + [ -x client/proxmark3 ] && client/proxmark3 --fulltext | $(COMMANDS_UTF8_FILTER) | sed 's#com[0-9]#/dev/ttyACM0#'|$(COMMANDS_PYTHON) client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json # Detecting weird codepages and tabs. diff --git a/client/src/cmdlfhitag.c b/client/src/cmdlfhitag.c index 8772c8742..c7aa90f08 100644 --- a/client/src/cmdlfhitag.c +++ b/client/src/cmdlfhitag.c @@ -1940,7 +1940,7 @@ static int CmdLFHitagEload(const char *Cmd) { arg_lit0("1", "ht1", "Card type Hitag 1"), arg_lit0("2", "ht2", "Card type Hitag 2"), arg_lit0("s", "hts", "Card type Hitag S"), - arg_lit0("m", "htm", "Card type Hitag \xce\xbc"), // μ + arg_lit0("m", "htm", "Card type Hitag µ"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -1990,7 +1990,7 @@ static int CmdLFHitagEload(const char *Cmd) { } else if (use_htm) { // a u dump is sized by the tag's ICR, so accept anything that fits expected = 0; - tname = "Hitag \xce\xbc"; + tname = "Hitag µ"; } if (use_htm) { @@ -2053,7 +2053,7 @@ static int CmdLFHitagEview(const char *Cmd) { arg_lit0("1", "ht1", "Card type Hitag 1"), arg_lit0("2", "ht2", "Card type Hitag 2 (default)"), arg_lit0("s", "hts", "Card type Hitag S"), - arg_lit0("m", "htm", "Card type Hitag \xce\xbc"), + arg_lit0("m", "htm", "Card type Hitag µ"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -2933,4 +2933,3 @@ int CmdLFHitag(const char *Cmd) { return CmdsParse(CommandTable, Cmd); } - From 4cca8df3a0e93f1431f8dc5f468d5969c635b618 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Wed, 16 Sep 2026 19:05:55 +0200 Subject: [PATCH 04/11] hf mfu: support UL-AES in restore, fix info config output restore refused UL-AES outright. The generic page plan assumes the last four pages are cfg0/cfg1/PWD/PACK, which on UL-AES are the AES keys, so the data loop walked over the lock page, both config pages and the key lock bits at 0x2D. Give UL-AES its own plan: user memory 0x04..0x27, and lock/cfg0/cfg1 behind -s. Key pages 0x30..0x37 are left alone, the dump only ever carries AESKey0 and 0x34..0x37 read back as zeros. info never printed the UL-AES config. ulaes_print_configuration() is called with 0x29 but its first branch tested for 0x2C, so cfg0 and cfg1 fell through to the bare return and only the CMAC page showed up. info also read page 0x34 as if it were an EV1 config page. That is the UIDRetrKey. Genuine silicon NAKs the read, but a magic or simulated card would have had its key printed as cfg0/cfg1/PWD/PACK. Tested on a UL-AES with AUTH0=4, PROT set and secure messaging on. Restore of an unmodified dump comes back byte identical; a dump carrying DEADBEEF at 0x27 and CAFEBABE at 0x2B writes 0x27 and leaves 0x2B alone. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 4 ++++ client/src/cmdhfmfu.c | 54 +++++++++++++++++++++++++++++++++++-------- doc/commands.json | 3 ++- 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1b5fd6b6..800061191 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... +## [unreleased][unreleased] +- Fixed `hf mfu restore` to support Ultralight AES (@iceman1001) +- Fixed `hf mfu info` to print UL-AES config pages again (@iceman1001) + ## [Frosty Lemon.4.23346][2026-09-18] - Fixed `hf mfdes sim` - the ATS now advertises 106 kbit/s only, PPS to a higher rate is refused, a selected card ignores REQA/WUPA, and ISO-DEP block recovery now follows the card sequence (@mistial-dev) - Added `hf mfdes sim` - answers ISO 7816 SELECT by DF name or file id with real status words, so a reader that opens with a SELECT reaches the card (@mistial-dev) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 96531ce6b..58d3d8764 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -65,6 +65,14 @@ #define MAX_ST25TN512 0x3F #define MAX_ST25TN01K 0x3F +// UL-AES fixed memory map, MF0AES(H)20 +#define MFU_AES_USER_FIRST 0x04 +#define MFU_AES_USER_LAST 0x27 +#define MFU_AES_LOCK_PAGE 0x28 +#define MFU_AES_CFG0_PAGE 0x29 +#define MFU_AES_CFG1_PAGE 0x2A +#define MFU_AES_KEY0_PAGE 0x30 + #define MIFAREU3P_KEY_SIZE 16 #define MIFAREULC_KEY_INDEX 3 #define MFU_DEFAULT_KEY_DIC "mfulc_default_keys.dic" @@ -4043,6 +4051,7 @@ static int CmdHF14AMfURestore(const char *Cmd) { "hf mfu restore -f myfile -s -> special write\n" "hf mfu restore -f myfile -k AABBCCDD -s -> special write, use key\n" "hf mfu restore -f myfile -k AABBCCDD -ser -> special write, use key, write dump pwd, ...\n" + "hf mfu restore -f myfile -k 00112233445566778899AABBCCDDEEFF -> UL-C / UL-AES, use key\n" "\n" "Note: Restoring a NTAG/UL dump to a UMC will likely result in incorrect PWD and PACK\n" ); @@ -4050,7 +4059,7 @@ static int CmdHF14AMfURestore(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_str1("f", "file", "", "Specify a filename for dump file"), - arg_str0("k", "key", "", "key for authentication (UL-C 16 bytes, EV1/NTAG 4 bytes)"), + arg_str0("k", "key", "", "key for authentication (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)"), arg_lit0("l", NULL, "swap entered key's endianness"), arg_lit0("s", NULL, "enable special write UID -MAGIC TAG ONLY-"), arg_lit0("e", NULL, "enable special write version/signature -MAGIC NTAG 21* ONLY-"), @@ -4142,6 +4151,8 @@ static int CmdHF14AMfURestore(const char *Cmd) { return PM3_ESOFT; } + bool is_ulaes = ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES); + if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { if ((has_key == true) && (ak_len != 16)) { PrintAndLogEx(ERR, "UL-C key must be 16 bytes"); @@ -4172,12 +4183,6 @@ static int CmdHF14AMfURestore(const char *Cmd) { } } - if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { - PrintAndLogEx(ERR, "Sorry, UL-AES not yet supported. Feel free to implement!"); - free(dump); - return PM3_ENOTIMPL; - } - PrintAndLogEx(INFO, "Restoring " _YELLOW_("%s")" to card", filename); mfu_print_dump(mem, pages, 0, dense_output); @@ -4279,7 +4284,19 @@ static int CmdHF14AMfURestore(const char *Cmd) { // write all other data // Skip block 0,1,2,3 (only magic tags can write to them) // Skip last 5 blocks usually is configuration - for (uint8_t b = 4; b < pages - 5; b++) { + uint8_t first_page = 4; + uint8_t last_page = pages - 5; + + if (is_ulaes) { + // UL-AES user memory stops before the lock, config and key pages + first_page = MFU_AES_USER_FIRST; + last_page = MFU_AES_USER_LAST + 1; + if (pages < last_page) { + last_page = pages; + } + } + + for (uint8_t b = first_page; b < last_page; b++) { //Send write Block memcpy(packetw.data, mem->data + (b * 4), 4); @@ -4306,8 +4323,19 @@ static int CmdHF14AMfURestore(const char *Cmd) { // otp, uid, lock, dynlockbits, cfg0, cfg1 uint8_t blocks[] = {3, 0, 1, 2, pages - 5, pages - 4, pages - 3}; #endif - for (uint8_t i = 0; i < ARRAYLEN(blocks); i++) { - uint8_t b = blocks[i]; + // otp, uid, lock, cfg0, cfg1. + // RFU pages (0x2B, 0x2C) and the key lock bits (0x2D) are left alone, they are one way + uint8_t ulaes_blocks[] = {3, 0, 1, 2, MFU_AES_LOCK_PAGE, MFU_AES_CFG0_PAGE, MFU_AES_CFG1_PAGE}; + + uint8_t *pblocks = blocks; + uint8_t blockcnt = ARRAYLEN(blocks); + if (is_ulaes) { + pblocks = ulaes_blocks; + blockcnt = ARRAYLEN(ulaes_blocks); + } + + for (uint8_t i = 0; i < blockcnt; i++) { + uint8_t b = pblocks[i]; memcpy(packetw.data, mem->data + (b * 4), 4); packetw.block_no = b; clearCommandBuffer(); @@ -4319,6 +4347,12 @@ static int CmdHF14AMfURestore(const char *Cmd) { DropField(); free(dump); + + if (is_ulaes) { + PrintAndLogEx(INFO, "Key pages 0x%02X..0x%02X not restored", MFU_AES_KEY0_PAGE, MAX_UL_AES); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu setkey -k <16 hex bytes>") "` to restore the AES keys"); + } + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu dump --ns") "` to verify"); PrintAndLogEx(INFO, "Done!"); return PM3_SUCCESS; diff --git a/doc/commands.json b/doc/commands.json index 7e9fdb119..364afb575 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -9636,6 +9636,7 @@ "hf mfu restore -f myfile -s -> special write", "hf mfu restore -f myfile -k AABBCCDD -s -> special write, use key", "hf mfu restore -f myfile -k AABBCCDD -ser -> special write, use key, write dump pwd, ...", + "hf mfu restore -f myfile -k 00112233445566778899AABBCCDDEEFF -> UL-C / UL-AES, use key", "", "Note: Restoring a NTAG/UL dump to a UMC will likely result in incorrect PWD and PACK" ], @@ -9643,7 +9644,7 @@ "options": [ "-h, --help This help", "-f, --file Specify a filename for dump file", - "-k, --key key for authentication (UL-C 16 bytes, EV1/NTAG 4 bytes)", + "-k, --key key for authentication (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", "-l swap entered key's endianness", "-s enable special write UID -MAGIC TAG ONLY-", "-e enable special write version/signature -MAGIC NTAG 21* ONLY-", From 5360980b485e6dd6847e20b1645019035aec01d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Tue, 22 Sep 2026 07:14:31 +0800 Subject: [PATCH 05/11] doc: 15693 wipe command would brick the v3 tag for now --- doc/magic_cards_notes.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 89cf88314..d3f49444a 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -2772,8 +2772,10 @@ hf 15 raw -acw -d 022114A52B442C hf 15 raw -acw -d 02211569E25D00 ``` -**WARNING!** Writing anything other than these two finalize values to blocks `0x14` and `0x15` bricks the tag. - +> [!WARNING] +> Writing anything other than these two finalize values to blocks `0x14` and `0x15` bricks the tag. +> +> `hf 15 wipe` may brick v3 tag. ### Proxmark3 commands From 940f26ce373a004207dcb9131c29ac7c5a616fc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Tue, 22 Sep 2026 07:24:43 +0800 Subject: [PATCH 06/11] build: centralize Python executable definition Co-Authored-By: OpenAI Codex --- Makefile | 6 +++--- Makefile.defs | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 3ef4f1ab4..b5536fad4 100644 --- a/Makefile +++ b/Makefile @@ -355,17 +355,17 @@ style: commands --align-pointer=name {} \; COMMANDS_UTF8_FILTER := cat -COMMANDS_PYTHON := python3 +COMMANDS_PYTHON := $(PYTHON3) ifdef IS_MINGW COMMANDS_UTF8_FILTER := iconv -f CP850 -t UTF-8 - COMMANDS_PYTHON := PYTHONIOENCODING=utf-8 python3 + COMMANDS_PYTHON := PYTHONIOENCODING=utf-8 $(PYTHON3) endif commands: client # Update commands.md [ -x client/proxmark3 ] && client/proxmark3 -m | $(COMMANDS_UTF8_FILTER) | tr -d '\r' > doc/commands.md # Make sure python3 is installed - @command -v python3 >/dev/null || ( echo "Please install 'python3' package first" ; exit 1 ) + @command -v $(PYTHON3) >/dev/null || ( echo "Please install '$(PYTHON3)' package first" ; exit 1 ) # Update commands.json, patch port in case it was run under Windows [ -x client/proxmark3 ] && client/proxmark3 --fulltext | $(COMMANDS_UTF8_FILTER) | sed 's#com[0-9]#/dev/ttyACM0#'|$(COMMANDS_PYTHON) client/pyscripts/pm3_help2json.py - - | tr -d '\r' > doc/commands.json diff --git a/Makefile.defs b/Makefile.defs index 8cfcce10e..7304bb5f6 100644 --- a/Makefile.defs +++ b/Makefile.defs @@ -53,6 +53,7 @@ USERMOD = usermod -aG ADDUSER = adduser GETENT_BL = getent group bluetooth +PYTHON3 ?= python3 PYTHON3_PKGCONFIG ?= python3 PATHSEP=/ From 3f8edc5563b007ec20a9347b0bf2fd5d7931cfec Mon Sep 17 00:00:00 2001 From: Axi-ohm <290742193+Axi-ohm@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:34:23 -0500 Subject: [PATCH 07/11] BigBuf: widen BIGBUF_ALIGN_MASK to 32-bit for PM5 Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 1 + armsrc/BigBuf.c | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad7b664cb..c457ebacf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed `hf 14a sim` - a dynamic response now gets a modulation buffer sized to fit it, instead of one 68 bytes too small (or 1788 too large for ST25TA) (@iceman1001) - Fixed `BigBuf_malloc` - takes a uint32_t, so a request of 64KB or more fails instead of wrapping to zero (@iceman1001) - Fixed `BigBuf_max_traceLen` - returns a uint32_t, so LF sampling on a device with more than 64KB of BigBuf is not handed a truncated buffer (@iceman1001) +- Fixed PM5 BigBuf allocation - Changed `hf mf view` - now show which VIGIK fields are RSA signed (@iceman1001) - Changed `hw status` - now reports EMULATOR memory (@iceman1001) - Changed `hf mf view` - Urmet Captiv cards now decode their number field and data regions (@iceman1001) diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 6ec041ec8..a3172ffb5 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -23,7 +23,7 @@ #include "util.h" // nbytes #define BIGBUF_ALIGN_BYTES (4) -#define BIGBUF_ALIGN_MASK (0xFFFF + 1 - BIGBUF_ALIGN_BYTES) +#define BIGBUF_ALIGN_MASK (~(uint32_t)(BIGBUF_ALIGN_BYTES - 1)) extern uint32_t _stack_start[], __bss_end__[]; From 82597a32c5707014b0809c7b30a6e9c186ac88b0 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 22 Sep 2026 11:05:07 +0200 Subject: [PATCH 08/11] fix: don't treat a RATS NAK as a successful ISO14443-4 activation iso14443a_select_cardEx() only rejected silence after RATS. A card that answered with a 4 bit NAK came back as Demod.len == 1, was stored as a one byte ATS and reported to the client as select status 1, meaning L4 activated. The client then sent GetVersion (90 60 00 00 00) as an I-block to a card that never left ISO14443-3, and every caller ended with 'timeout while waiting for reply' / 'No tag detected or other tag communication error (-4)'. The bogus TL of 0x04 also made iso14a_set_ATS_times() look for a T0 and read past the single received byte. Check that the answer to RATS is a well formed ATS, TL plus the bytes TL counts plus the two CRC bytes, before accepting it. Anything else returns 2, selected but ISO14443-3 only, so the card stays usable over the Classic path instead of failing detection. The client side 'try to request ATS even if the tag claims not to support it' retry had the same hole and stored whatever came back in card.ats, so guard all four copies of it the same way. Reported on a clone with ATQA 0004 / SAK 28 that advertises ISO14443-4 it does not implement. hf mf autopwn on it needed hf 14a config --rats skip to get past detection; with this it takes the Classic path on its own. Fixes #3659 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + armsrc/iso14443a.c | 9 +++++++++ client/src/cmdhf14a.c | 8 +++++--- client/src/cmdhfmf.c | 24 +++++++++++++++--------- 4 files changed, 30 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4214034d..229ccb8d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf 14a info` now correctly handles NAK when receiving RATS (@iceman1001) - Fixed `hf mfu restore` to support Ultralight AES (@iceman1001) - Fixed `hf mfu info` to print UL-AES config pages again (@iceman1001) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index e0af71124..c89130d95 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -4076,6 +4076,15 @@ int iso14443a_select_cardEx(uint8_t *uid_ptr, iso14a_card_select_t *p_card, uint return 0; } + // An ATS is TL, the bytes TL counts, and two CRC bytes on top. + // Anything shorter, like a 4 bit NAK is not ATS + if (len < 3 || resp[0] != len - 2) { + if (g_dbglevel >= DBG_INFO) { + Dbprintf("Card answered RATS with %i byte(s), not an ATS. Staying at ISO14443-3", len); + } + return 2; + } + if (p_card) { memcpy(p_card->ats, resp, sizeof(p_card->ats)); p_card->ats_len = len; diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index ba3b0bf73..dfac1011e 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -2994,9 +2994,11 @@ int infoHF14A(bool verbose, bool do_nack_test, bool do_aid_search) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_2863); - card.ats_len = rlen_2863; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_2863 > 3) && (resp.data.asBytes[0] == rlen_2863 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_2863); + card.ats_len = rlen_2863; // note: ats_len includes CRC Bytes select_status = 4; } } diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index b37506de7..7d3f8b6fc 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -405,9 +405,11 @@ int mf_read_uid(uint8_t *uid, int *uidlen, int *nxptype) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_398); - card.ats_len = rlen_398; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_398 > 3) && (resp.data.asBytes[0] == rlen_398 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_398); + card.ats_len = rlen_398; // note: ats_len includes CRC Bytes select_status = 4; } } @@ -3199,9 +3201,11 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_3120); - card.ats_len = rlen_3120; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_3120 > 3) && (resp.data.asBytes[0] == rlen_3120 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_3120); + card.ats_len = rlen_3120; // note: ats_len includes CRC Bytes select_status = 4; } } @@ -11458,9 +11462,11 @@ static int CmdHF14AMfInfo(const char *Cmd) { return PM3_ETIMEOUT; } - memcpy(card.ats, resp.data.asBytes, rlen_11266); - card.ats_len = rlen_11266; // note: ats_len includes CRC Bytes - if (card.ats_len > 3) { + // Only a well formed ATS, TL plus the bytes TL counts plus CRC, means the + // PICC entered ISO14443-4. A 4 bit NAK to RATS is not an ATS. + if ((rlen_11266 > 3) && (resp.data.asBytes[0] == rlen_11266 - 2)) { + memcpy(card.ats, resp.data.asBytes, rlen_11266); + card.ats_len = rlen_11266; // note: ats_len includes CRC Bytes select_status = 4; } } From 28d49510e29eeda9d70367e98108358f21ace074 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 22 Sep 2026 11:14:44 +0200 Subject: [PATCH 09/11] hf mf: add RKF travel card parser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The RKF travel card (Resekortsföreningen i Norden) is the Nordic public transport card, specified 2001-2002 on MIFARE Classic and deployed by Västtrafik, SL Stockholm, Länstrafiken and the Danish Rejsekort. Decodes the card issuer and support layers (CMI, TCCI, TCAS, TCDI) and every application object the specification pins down: TCPU purse, TCEL event log, TCDB, TCCP, TCST, and TCTI/TCCO through an identifier chain walker covering all 18 data element groups. AID owners are named from RKF-0019. Three things the specification does not state, determined from 21 cards: - RKF-0022 7.7.1 calls the block checksum 'standard CRC-8' without naming the parameters. It is CRC-8/MIFARE-MAD, poly 0x1D init 0xC7, which the tree already ships as CRC8Mad(). - The MAC trio is the final 24 bits of a MACed object. The RKF-0023 tables list Free (bits) as a trailing summary row, which reads as if the authenticator follows a gap after the key identifier; it does not. Measured on the fact that MACAlgorithmIdentifier must be 0: TCST 42/42 against 15/42, TCCP 20/20 against 13/20. - TCPU version 4 drops EndDate and moves Value to bit 16. Cards reporting a version other than 2 are flagged, and a MAC algorithm the specification does not define is reported as a layout failure rather than printed as data. MAC values are not verified. The master key is in RKF-0018, which was never published. des_mac() is added to libpcrypto for when that changes, with the FIPS 113 worked example as its test. Verified against a Danish Rejsekort whose provenance notes give the purchase timestamp, card number and balance; the parser reproduces all three. 48 self test checks on 'hf mf view --selftest', no false positives across 460 local dumps. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + client/CMakeLists.txt | 2 +- client/Makefile | 1 + client/experimental_lib/CMakeLists.txt | 1 + client/src/cmdhfmf.c | 1 + client/src/crypto/libpcrypto.c | 101 ++ client/src/crypto/libpcrypto.h | 9 + client/src/emv/test/cryptotest.c | 6 + client/src/parsers/parserkf.c | 2034 ++++++++++++++++++++++++ client/src/parsers/parserkf.h | 42 + 10 files changed, 2197 insertions(+), 1 deletion(-) create mode 100644 client/src/parsers/parserkf.c create mode 100644 client/src/parsers/parserkf.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 229ccb8d1..efb62414c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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 mf view` - decodes RKF travel cards, the Nordic public transport card (Resekortsföreningen i Norden) on MIFARE Classic (@iceman1001) - Fixed `hf 14a info` now correctly handles NAK when receiving RATS (@iceman1001) - Fixed `hf mfu restore` to support Ultralight AES (@iceman1001) - Fixed `hf mfu info` to print UL-AES config pages again (@iceman1001) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index fa73ebd35..4d8808073 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -514,6 +514,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/parsers/parsehexact.c ${PM3_ROOT}/client/src/parsers/parsemykey.c ${PM3_ROOT}/client/src/parsers/parseproac.c + ${PM3_ROOT}/client/src/parsers/parserkf.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c @@ -521,7 +522,6 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/pm3_binlib.c ${PM3_ROOT}/client/src/pm3_bitlib.c ${PM3_ROOT}/client/src/pm3_dsp.c - ${PM3_ROOT}/client/src/pm3_fit.c ${PM3_ROOT}/client/src/pm3line.c ${PM3_ROOT}/client/src/pm3line_vocabulary.c diff --git a/client/Makefile b/client/Makefile index e2c518f22..24a471d61 100644 --- a/client/Makefile +++ b/client/Makefile @@ -912,6 +912,7 @@ SRCS = mifare/aiddesfire.c \ parsers/parsehexact.c \ parsers/parsemykey.c \ parsers/parseproac.c \ + parsers/parserkf.c \ parsers/hrtparser/hrtparser.c \ pm3.c \ pm3_binlib.c \ diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index 2b5f21330..a7a6d0001 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -441,6 +441,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/parsers/parsehexact.c ${PM3_ROOT}/client/src/parsers/parsemykey.c ${PM3_ROOT}/client/src/parsers/parseproac.c + ${PM3_ROOT}/client/src/parsers/parserkf.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 7d3f8b6fc..21203793b 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -47,6 +47,7 @@ #include "parsers/parsevigik.h" #include "parsers/parsehexact.h" #include "parsers/parseproac.h" +#include "parsers/parserkf.h" #include "generator.h" // keygens. #include "fpga.h" #include "mifare/mifarehost.h" diff --git a/client/src/crypto/libpcrypto.c b/client/src/crypto/libpcrypto.c index 0cce8d54b..3f38787eb 100644 --- a/client/src/crypto/libpcrypto.c +++ b/client/src/crypto/libpcrypto.c @@ -795,6 +795,44 @@ void des_decrypt_cbc(void *out, const void *in, const int length, const void *ke mbedtls_des_crypt_cbc(&ctx, MBEDTLS_DES_DECRYPT, length, iv, in, out); } +// FIPS PUB 113 - Computer Data Authentication. +// https://csrc.nist.gov/files/pubs/fips/113/final/docs/fips113.pdf +int des_mac(const void *key, const void *input, size_t length, uint8_t *mac, size_t mac_len) { + + if (key == NULL || mac == NULL || mac_len == 0 || mac_len > 8) { + return PM3_EINVARG; + } + + if (length && input == NULL) { + return PM3_EINVARG; + } + + // zero pad up to a whole number of blocks, an empty message is one block + size_t n = (length + 7) & ~(size_t)7; + if (n == 0) { + n = 8; + } + + uint8_t *buf = calloc(n * 2, sizeof(uint8_t)); + if (buf == NULL) { + return PM3_EMALLOC; + } + + uint8_t *out = buf + n; + if (length) { + memcpy(buf, input, length); + } + + uint8_t iv[8] = {0}; + des_encrypt_cbc(out, buf, (int)n, key, iv); + + // the MAC is the leading bits of the last cipher block + memcpy(mac, out + n - 8, mac_len); + + free(buf); + return PM3_SUCCESS; +} + void des3_encrypt(void *out, const void *in, const void *key, uint8_t keycount) { switch (keycount) { case 1: @@ -1280,6 +1318,69 @@ int ecdsa_signature_r_s_verify(mbedtls_ecp_group_id curveid, uint8_t *key_xy, ui #define T_R "2B42F576D07F4165FF65D1F3B1500F81E44C316F1F0B3EF57325B69ACA46104F" #define T_S "DC42C2122D6392CD3E3A993A89502A8198C1886FE69D262C4B329BDB6B63FAF1" +static int des_mac_test_one(const char *name, const uint8_t key[8], const uint8_t *data, + size_t len, const uint8_t *expect, size_t expect_len, bool verbose) { + + uint8_t mac[8] = {0}; + int res = des_mac(key, data, len, mac, expect_len); + if (res != PM3_SUCCESS) { + return res; + } + + if (memcmp(mac, expect, expect_len) != 0) { + if (verbose) { + PrintAndLogEx(FAILED, " %s got %s", name, sprint_hex_inrow(mac, expect_len)); + } + return PM3_ESOFT; + } + + if (verbose) { + PrintAndLogEx(INFO, " %s %s ( %s )", name, sprint_hex_inrow(mac, expect_len), _GREEN_("ok")); + } + return PM3_SUCCESS; +} + +int des_mac_test(bool verbose) { + + if (verbose) { + PrintAndLogEx(INFO, "DES-MAC FIPS 113 test"); + } else { + PrintAndLogEx(INFO, "DES-MAC FIPS 113 test " NOLF); + } + + const uint8_t key[8] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}; + + // the worked example of FIPS PUB 113, which publishes the 32 bit MAC + const uint8_t msg[] = "7654321 Now is the time for "; + const uint8_t full[8] = {0xF1, 0xD3, 0x0F, 0x68, 0x49, 0x31, 0x2C, 0xA4}; + + int res = des_mac_test_one("FIPS 113, 64 bit", key, msg, sizeof(msg) - 1, full, 8, verbose); + if (res == PM3_SUCCESS) { + res = des_mac_test_one("FIPS 113, 32 bit", key, msg, sizeof(msg) - 1, full, 4, verbose); + } + if (res == PM3_SUCCESS) { + res = des_mac_test_one("FIPS 113, 16 bit", key, msg, sizeof(msg) - 1, full, 2, verbose); + } + + // one block of zero padding only + if (res == PM3_SUCCESS) { + const uint8_t empty[8] = {0xD5, 0xD4, 0x4F, 0xF7, 0x20, 0x68, 0x3D, 0x0D}; + res = des_mac_test_one("empty message...", key, NULL, 0, empty, 8, verbose); + } + + // exactly one block, so no padding is added + if (res == PM3_SUCCESS) { + const uint8_t one[8] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; + const uint8_t want[8] = {0xCA, 0xDB, 0x67, 0x82, 0xEE, 0x2B, 0x48, 0x23}; + res = des_mac_test_one("one whole block.", key, one, sizeof(one), want, 8, verbose); + } + + if (verbose == false) { + PrintAndLogEx(NORMAL, (res == PM3_SUCCESS) ? "( " _GREEN_("ok") " )" : "( " _RED_("fail") " )"); + } + return res; +} + int ecdsa_nist_test(bool verbose) { int res; uint8_t input[] = "Example of ECDSA with P-256"; diff --git a/client/src/crypto/libpcrypto.h b/client/src/crypto/libpcrypto.h index 0b10f32ad..0485ce5fa 100644 --- a/client/src/crypto/libpcrypto.h +++ b/client/src/crypto/libpcrypto.h @@ -49,6 +49,15 @@ void des_decrypt_cbc(void *out, const void *in, const int length, const void *ke void des3_encrypt(void *out, const void *in, const void *key, uint8_t keycount); void des3_decrypt(void *out, const void *in, const void *key, uint8_t keycount); +// desMAC according to [FIPS 113]. The data is zero padded to a multiple of the +// DES block size and encrypted in CBC mode with a zero IV; the MAC is the most +// significant mac_len bytes of the final cipher block. key is 8 bytes, mac_len +// is 1..8. +int des_mac(const void *key, const void *input, size_t length, uint8_t *mac, size_t mac_len); + +// Check des_mac against the worked example of [FIPS 113] +int des_mac_test(bool verbose); + int aes_encode(uint8_t *iv, const uint8_t *key, uint8_t *input, uint8_t *output, int length); int aes_decode(uint8_t *iv, const uint8_t *key, uint8_t *input, uint8_t *output, int length); diff --git a/client/src/emv/test/cryptotest.c b/client/src/emv/test/cryptotest.c index ff8743563..e1221bda4 100644 --- a/client/src/emv/test/cryptotest.c +++ b/client/src/emv/test/cryptotest.c @@ -84,6 +84,12 @@ int ExecuteCryptoTests(bool verbose, bool ignore_time, bool include_slow_tests) res = mbedtls_cmac_self_test(verbose); if (res) TestFail = true; + res = des_mac_test(verbose); + if (res) { + return res; + } + PrintAndLogEx(NORMAL, ""); + res = ecdsa_nist_test(verbose); if (res) TestFail = true; diff --git a/client/src/parsers/parserkf.c b/client/src/parsers/parserkf.c new file mode 100644 index 000000000..e45e72450 --- /dev/null +++ b/client/src/parsers/parserkf.c @@ -0,0 +1,2034 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// RKF travel card parser for MIFARE Classic dumps +//----------------------------------------------------------------------------- + +#include "parserkf.h" + +#include // snprintf +#include + +#include "commonutil.h" // ARRAYLEN +#include "crc.h" // CRC8Mad +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow +#include "mifare/mifaredefault.h" // MFBLOCK_SIZE +#include "mifare/mifare4.h" // mfFirstBlockOfSector + +#define RKF_SECTORS 16 +#define RKF_BLOCK_BITS 128 + +// The last byte of a block that carries no MAC authenticator is a checksum, so +// a data element group spanning blocks sees only 120 bits per block +#define RKF_USABLE_BITS 120 + +// Fixed positions of the travel card support layer +#define RKF_CMI_SECTOR 0 +#define RKF_CMI_BLOCK 0 +#define RKF_TCCI_BLOCK 1 +#define RKF_TCAS_BLOCK 2 +#define RKF_TCDI_SECTOR 1 + +// Directory AID values with a fixed meaning, RKF-0022 section 8.2 +#define RKF_AID_FREE 0x000 +#define RKF_AID_DEFECTIVE 0x001 +#define RKF_AID_RESERVED 0x002 +#define RKF_AID_TCAS2 0x005 +#define RKF_AID_TCDI 0x006 +#define RKF_AID_TCEL 0x00A +#define RKF_AID_TCPU 0x00B +#define RKF_AID_TCPU_DATA 0x00C + +// Directory PIX value marking a continuation sector, RKF-0022 section 8.3 +#define RKF_PIX_CONT 0x001 + +// Data element group identifiers, RKF-0022 section 8.1 +#define RKF_ID_TCEL_RECORD 0x84 +#define RKF_ID_TCPU_STATIC 0x85 +#define RKF_ID_TCTI_HEADER 0x86 +#define RKF_ID_TCCO_HEADER 0x87 +#define RKF_ID_DYN_MULTI 0x88 +#define RKF_ID_MANDATORY 0x89 +#define RKF_ID_DYN_SINGLE 0x8A +#define RKF_ID_MAC 0x93 +#define RKF_ID_PRICE 0x94 +#define RKF_ID_ISSUER 0x95 +#define RKF_ID_TCCO_PERIOD 0x96 +#define RKF_ID_VAL_DISTANCE 0x97 +#define RKF_ID_VAL_ROUTE 0x98 +#define RKF_ID_VAL_ZONE 0x99 +#define RKF_ID_TCCO_ISSUING 0x9A +#define RKF_ID_CUSTOMER 0x9B +#define RKF_ID_CLASS 0x9C +#define RKF_ID_TCTI_PERIOD 0x9D +#define RKF_ID_TCTI_ISSUING 0x9E +#define RKF_ID_VALIDATION 0x9F +#define RKF_ID_TCDB 0xA1 +#define RKF_ID_TCCP 0xA2 +#define RKF_ID_TCST 0xA3 + +// Days from 1970-01-01 to the DateCompact epoch of 1997-01-01 +#define RKF_DAYS_TO_1997 9862 +// Days from 1970-01-01 to the DateTime epoch of 2000-01-01 +#define RKF_DAYS_TO_2000 10957 + +#define RKF_LABEL "%-18s" + +//----------------------------------------------------------------------------- +// Bit access +// +// RKF-0022 section 7.4.1: the bits of byte 0 precede the bits of byte 1, and +// within a byte the least significant bit comes first. An unsigned number is +// read with its least significant bit first. +//----------------------------------------------------------------------------- + +static uint64_t rkf_bits(const uint8_t *buf, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + if ((buf[b >> 3] >> (b & 7)) & 1) { + v |= (uint64_t)1 << k; + } + } + return v; +} + +static void rkf_set_bits(uint8_t *buf, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + if ((v >> k) & 1) { + buf[b >> 3] |= (uint8_t)(1 << (b & 7)); + } else { + buf[b >> 3] &= (uint8_t)~(1 << (b & 7)); + } + } +} + +// Twos complement, the sign living in the last bit of the section +static int32_t rkf_signed(uint64_t v, uint8_t len) { + if (v & ((uint64_t)1 << (len - 1))) { + return (int32_t)(v - ((uint64_t)1 << len)); + } + return (int32_t)v; +} + +// A run of data blocks holding one or more application elements. Bit p of the +// run lives in data block p / 120 at bit p % 120, so the checksum byte of every +// block is stepped over, per RKF-0022 section 7.4.1. Sector trailers are not +// part of the run. +typedef struct { + const uint8_t *dump; + size_t dumplen; + uint8_t sector; + uint8_t nblocks; +} rkf_run_t; + +static const uint8_t *rkf_block(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block); +static uint8_t rkf_data_blocks(uint8_t sector); + +static const uint8_t *rkf_run_block(const rkf_run_t *run, uint8_t idx) { + uint8_t s = run->sector; + while (idx >= rkf_data_blocks(s)) { + idx -= rkf_data_blocks(s); + s++; + } + return rkf_block(run->dump, run->dumplen, s, idx); +} + +static uint64_t rkf_run_bits(const rkf_run_t *run, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + + uint16_t p = off + k; + uint8_t idx = (uint8_t)(p / RKF_USABLE_BITS); + if (idx >= run->nblocks) { + break; + } + + const uint8_t *blk = rkf_run_block(run, idx); + if (blk == NULL) { + break; + } + + uint16_t b = p % RKF_USABLE_BITS; + if ((blk[b >> 3] >> (b & 7)) & 1) { + v |= (uint64_t)1 << k; + } + } + return v; +} + +// Only used to build the self test card, which keeps its run inside one sector +static void rkf_run_set_bits(uint8_t *base, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t p = off + k; + uint16_t blk = p / RKF_USABLE_BITS; + rkf_set_bits(base, (uint16_t)((p % RKF_USABLE_BITS) + (blk * RKF_BLOCK_BITS)), 1, (v >> k) & 1); + } +} + +//----------------------------------------------------------------------------- +// Value decoding +//----------------------------------------------------------------------------- + +static void rkf_civil_from_days(int32_t z, int *year, unsigned *month, unsigned *day) { + z += 719468; + int32_t era = ((z >= 0) ? z : (z - 146096)) / 146097; + uint32_t doe = (uint32_t)(z - (era * 146097)); + uint32_t yoe = (doe - (doe / 1460) + (doe / 36524) - (doe / 146096)) / 365; + int32_t y = (int32_t)yoe + (era * 400); + uint32_t doy = doe - ((365 * yoe) + (yoe / 4) - (yoe / 100)); + uint32_t mp = ((5 * doy) + 2) / 153; + *day = doy - (((153 * mp) + 2) / 5) + 1; + *month = (mp < 10) ? (mp + 3) : (mp - 9); + *year = y + ((*month <= 2) ? 1 : 0); +} + +// DateCompact, day 0 is 1 January 1997 +static void rkf_date_str(uint16_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + rkf_civil_from_days((int32_t)v + RKF_DAYS_TO_1997, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u", y, m, d); +} + +// TimeCompact, 'hhhhhmmmmmmsssss' with a 2 second resolution +static void rkf_time_str(uint16_t v, char *out, size_t outlen) { + uint8_t h = (v >> 11) & 0x1F; + uint8_t m = (v >> 5) & 0x3F; + uint8_t s = (v & 0x1F) * 2; + + if (h > 23 || m > 59) { + snprintf(out, outlen, "%04X invalid", v); + return; + } + snprintf(out, outlen, "%02u:%02u:%02u", h, m, s); +} + +// DateTime, minute 1 is 0:01 on 1 January 2000 +static void rkf_datetime_str(uint32_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + rkf_civil_from_days((int32_t)(v / 1440) + RKF_DAYS_TO_2000, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u %02u:%02u", y, m, d, (v % 1440) / 60, (v % 1440) % 60); +} + +// DateMonth11, month 1 is January 1900 +static void rkf_month11_str(uint16_t v, char *out, size_t outlen) { + if (v == 0) { + snprintf(out, outlen, "undefined"); + return; + } + snprintf(out, outlen, "%04u-%02u", 1900 + ((v - 1) / 12), ((v - 1) % 12) + 1); +} + +// DateMonth8, month 1 is January 2000 +static void rkf_month8_str(uint16_t v, char *out, size_t outlen) { + if (v == 0) { + snprintf(out, outlen, "undefined"); + return; + } + snprintf(out, outlen, "%04u-%02u", 2000 + ((v - 1) / 12), ((v - 1) % 12) + 1); +} + +static const char *rkf_currency_name(uint16_t code) { + switch (code) { + case 208: + return "DKK"; + case 246: + return "FIM"; + case 352: + return "ISK"; + case 578: + return "NOK"; + case 752: + return "SEK"; + case 826: + return "GBP"; + case 840: + return "USD"; + case 978: + return "EUR"; + default: + return NULL; + } +} + +// CurrencyUnit is BCD(4) coded 'xyyy', x the unit and yyy the ISO 4217 currency +static void rkf_currency_str(uint16_t cu, char *out, size_t outlen) { + uint8_t unit = (cu >> 12) & 0x0F; + uint16_t code = (((cu >> 8) & 0x0F) * 100) + (((cu >> 4) & 0x0F) * 10) + (cu & 0x0F); + const char *name = rkf_currency_name(code); + + const char *scale; + switch (unit) { + case 0: + scale = "main unit"; + break; + case 1: + scale = "1/10 of main unit"; + break; + case 2: + scale = "1/100 of main unit"; + break; + case 9: + scale = "1/2 of main unit"; + break; + default: + scale = "provider specific unit"; + break; + } + + if (name) { + snprintf(out, outlen, "%s, %s", name, scale); + } else { + snprintf(out, outlen, "currency %03u, %s", code, scale); + } +} + +// Money amounts are stored in the unit named by CardCurrencyUnit of TCCI +static void rkf_money_str(int32_t v, uint16_t cu, char *out, size_t outlen) { + uint8_t unit = (cu >> 12) & 0x0F; + uint16_t code = (((cu >> 8) & 0x0F) * 100) + (((cu >> 4) & 0x0F) * 10) + (cu & 0x0F); + const char *name = rkf_currency_name(code); + char cur[8]; + + if (name) { + snprintf(cur, sizeof(cur), "%s", name); + } else { + snprintf(cur, sizeof(cur), "%03u", code); + } + + const char *sign = (v < 0) ? "-" : ""; + uint32_t a = (uint32_t)((v < 0) ? -(int64_t)v : v); + + switch (unit) { + case 1: + snprintf(out, outlen, "%s%u.%01u %s", sign, a / 10, a % 10, cur); + break; + case 2: + snprintf(out, outlen, "%s%u.%02u %s", sign, a / 100, a % 100, cur); + break; + case 9: + snprintf(out, outlen, "%s%u.%s %s", sign, a / 2, (a % 2) ? "5" : "0", cur); + break; + default: + snprintf(out, outlen, "%s%u %s", sign, a, cur); + break; + } +} + +// Status values are chosen so the ASCII character is itself the signal +static const char *rkf_status_name(uint8_t s) { + switch (s) { + case 0x00: + return "undefined"; + case 0x01: + return "ok, enabled"; + case 0x21: + return "disabled, action pending"; + case 0x3F: + return "temporarily disabled"; + case 0x58: + return "not ok, disabled"; + default: + return "unknown"; + } +} + +static const char *rkf_sector_status_name(uint8_t s) { + switch (s) { + case 1: + return "AT1/AT5, 1st dynamic element current"; + case 2: + return "AT1/AT5, 2nd dynamic element current"; + case 3: + return "AT2"; + default: + return "undefined"; + } +} + +static const char *rkf_passenger_type_name(uint8_t t) { + switch (t) { + case 0: + return "unspecified"; + case 1: + return "adult"; + case 2: + return "child"; + case 3: + return "student"; + case 4: + return "old age pensioner"; + default: + return (t >= 32) ? "PTA specific" : "RFU"; + } +} + +static const char *rkf_passenger_class_name(uint8_t c) { + switch (c) { + case 1: + return "first class"; + case 2: + return "second class"; + case 3: + return "provider specific"; + default: + return "not specified"; + } +} + +static const char *rkf_validation_model_name(uint8_t m) { + switch (m) { + case 1: + return "ci/co"; + case 2: + return "ci-dest"; + case 3: + return "RFU"; + default: + return "undefined"; + } +} + +static const char *rkf_validation_status_name(uint8_t s) { + switch (s) { + case 1: + return "open, after check-in"; + case 2: + return "closed, after check-out"; + case 3: + return "RFU"; + default: + return "undefined"; + } +} + +static const char *rkf_supplement_status_name(uint8_t s) { + switch (s) { + case 1: + return "counting from origin"; + case 2: + return "accumulating distance"; + case 3: + return "counting and accumulating"; + default: + return "not counting"; + } +} + +static const char *rkf_mac_alg_name(uint8_t a) { + return (a == 0) ? "DES-MAC" : "RFU"; +} + +// AID owners, RKF-0019 2.00 edition B section 5 +static const struct { + uint16_t aid; + const char *name; +} rkf_aid_owners[] = { + {0x064, "Stockholms Lans Landsting"}, + {0x065, "SL - Storstockholms Lokaltrafik AB"}, + {0x066, "SL Flygbussar AB"}, + {0x067, "Waxholms Angfartygs AB"}, + {0x06E, "Lanstrafiken i Vasterbotten AB"}, + {0x06F, "Umea Lokaltrafik AB"}, + {0x078, "Lanstrafiken i Norrbotten AB"}, + {0x079, "Lulea Lokaltrafik AB"}, + {0x082, "Upplands Lokaltrafik AB"}, + {0x083, "Uppsalabuss AB"}, + {0x08C, "LTS - Lanstrafiken Sormland AB"}, + {0x096, "Ostgotatrafiken AB"}, + {0x097, "Norrkopings Kommun"}, + {0x0A0, "Jonkopings Lanstrafik AB"}, + {0x0AA, "Lanstrafiken Kronoberg"}, + {0x0B4, "Kalmar Lans Trafik AB"}, + {0x0BE, "Gotlands Kommun, Kollektivtrafiken"}, + {0x0BF, "Destination Gotland"}, + {0x0C8, "Blekingetrafiken"}, + {0x0DD, "Helsingborgs Kommun"}, + {0x0DE, "Lunds kommun"}, + {0x0E0, "Skanetrafiken"}, + {0x0E6, "Hallandstrafiken AB"}, + {0x0F0, "Vasttrafik"}, + {0x10E, "Varmlandstrafik AB"}, + {0x10F, "Karlstads kommun"}, + {0x118, "LTO - Lanstrafiken Orebro AB"}, + {0x122, "Vastmanlands Lokaltrafik AB"}, + {0x12C, "Dalatrafik, AB"}, + {0x136, "X-Trafik AB"}, + {0x137, "Gavle Kommun"}, + {0x140, "Vasternorrlands lans Trafik AB"}, + {0x14A, "Lanstrafiken i Jamtlands Lan AB"}, + {0x1F4, "SJ"}, + {0x1F5, "TIM - Trafik i Malardalen"}, + {0x3E9, "AS Oslo Sporveier"}, + {0x3EA, "Norges Statsbaner"}, + {0x3EB, "SL - Stor-Oslo Lokaltrafikk A.S."}, + {0x7D1, "HUR - Hovedstadens Udviklingsraad"}, + {0x7D2, "DSB"}, + {0x7D3, "OSS/Metro"}, + {0x7D4, "STS"}, + {0x7D5, "VT"}, +}; + +// The block an AID falls in when no owner is registered for it, RKF-0019 +static const char *rkf_aid_range(uint16_t aid) { + if (aid <= 0x063) { + return "system value"; + } + if (aid <= 0x1F3) { + return "Swedish PTA, county or municipal"; + } + if (aid <= 0x3E7) { + return "Swedish PTA, national or regional"; + } + if (aid <= 0x7CF) { + return "Norwegian PTA"; + } + if (aid <= 0xBB7) { + return "Danish PTA"; + } + return "reserved"; +} + +static const char *rkf_aid_name(uint16_t aid) { + switch (aid) { + case RKF_AID_FREE: + return "sector free"; + case RKF_AID_DEFECTIVE: + return "sector defective"; + case RKF_AID_RESERVED: + return "sector reserved"; + case RKF_AID_TCAS2: + return "TCAS (2), applications status"; + case RKF_AID_TCDI: + return "TCDI, directory"; + case RKF_AID_TCEL: + return "TCEL, event log"; + case RKF_AID_TCPU: + return "TCPU, purse"; + case RKF_AID_TCPU_DATA: + return "PTA area bound to the purse"; + default: + break; + } + + for (size_t i = 0; i < ARRAYLEN(rkf_aid_owners); i++) { + if (rkf_aid_owners[i].aid == aid) { + return rkf_aid_owners[i].name; + } + } + + if (aid >= 0x020 && aid <= 0x02F) { + return "test and validation"; + } + return rkf_aid_range(aid); +} + +// Event codes and the event data layout each one uses, RKF-0023 section 3.4.2 +typedef enum { + RKF_EVD_NONE = 0, + RKF_EVD_A, // pointer and price + RKF_EVD_B, // ticket pointer and contract pointer + RKF_EVD_C, // ticket pointer and PTA specific data + RKF_EVD_D, // money amount +} rkf_evdata_t; + +static const struct { + uint8_t code; + rkf_evdata_t kind; + const char *name; +} rkf_event_codes[] = { + {0x00, RKF_EVD_NONE, "undefined"}, + {0x01, RKF_EVD_A, "purchase of TCTI using TCPU"}, + {0x02, RKF_EVD_A, "purchase of TCCO using TCPU"}, + {0x03, RKF_EVD_A, "purchase of TCTI, other payment"}, + {0x04, RKF_EVD_A, "purchase of TCCO, other payment"}, + {0x05, RKF_EVD_B, "TCTI issued by a TCCO"}, + {0x06, RKF_EVD_C, "validation of TCTI / TCCO"}, + {0x07, RKF_EVD_C, "extension of TCTI / TCCO"}, + {0x08, RKF_EVD_D, "charge of the TCPU"}, + {0x09, RKF_EVD_C, "TCTI removed"}, + {0x0A, RKF_EVD_C, "TCCO removed"}, + {0x0B, RKF_EVD_C, "TCPU removed"}, + {0x0C, RKF_EVD_C, "TCST-ci/co removed"}, + {0x0D, RKF_EVD_C, "TCCP removed"}, + {0x0E, RKF_EVD_C, "TCDB removed"}, + {0x0F, RKF_EVD_C, "TCRE removed"}, + {0x16, RKF_EVD_A, "card initialised"}, + {0x17, RKF_EVD_C, "application object created"}, + {0x18, RKF_EVD_A, "application object repurchased"}, + {0x19, RKF_EVD_C, "TCCO activated"}, + {0x1A, RKF_EVD_A, "purchase of paper ticket using TCPU"}, + {0x1B, RKF_EVD_C, "check-in validation of TCST-ci/co"}, + {0x1C, RKF_EVD_C, "check-out validation of TCST-ci/co"}, + {0x1D, RKF_EVD_C, "control validation"}, + {0x1E, RKF_EVD_C, "supplement validation"}, + {0x1F, RKF_EVD_D, "charge of the TCPU using autoload"}, +}; + +static rkf_evdata_t rkf_event_kind(uint8_t code, const char **name) { + for (size_t i = 0; i < ARRAYLEN(rkf_event_codes); i++) { + if (rkf_event_codes[i].code == code) { + *name = rkf_event_codes[i].name; + return rkf_event_codes[i].kind; + } + } + *name = (code >= 0x30) ? "PTA specific" : "RFU"; + return RKF_EVD_NONE; +} + +//----------------------------------------------------------------------------- +// Block access +//----------------------------------------------------------------------------- + +static const uint8_t *rkf_block(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t block) { + size_t off = (size_t)(mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE; + if (off + MFBLOCK_SIZE > dumplen) { + return NULL; + } + return dump + off; +} + +// RKF-0022 section 7.7.1: every byte of a block feeds the checksum except the +// checksum byte itself. The "standard CRC-8" it names is CRC-8/MIFARE-MAD. +static bool rkf_checksum_ok(const uint8_t *blk) { + uint8_t d[MFBLOCK_SIZE - 1]; + memcpy(d, blk, sizeof(d)); + return ((uint8_t)CRC8Mad(d, sizeof(d)) == blk[MFBLOCK_SIZE - 1]); +} + +static const char *rkf_checksum_str(const uint8_t *blk) { + return rkf_checksum_ok(blk) ? _GREEN_("ok") : _RED_("fail"); +} + +static uint8_t rkf_sector_count(size_t dumplen) { + if (dumplen >= MIFARE_4K_MAX_BYTES) { + return 40; + } + if (dumplen >= MIFARE_2K_MAX_BYTES) { + return 32; + } + if (dumplen >= MIFARE_1K_MAX_BYTES) { + return RKF_SECTORS; + } + return (uint8_t)(dumplen / (4 * MFBLOCK_SIZE)); +} + +// Data blocks of a sector, the trailer excluded +static uint8_t rkf_data_blocks(uint8_t sector) { + return (uint8_t)(mfNumBlocksPerSector(sector) - 1); +} + +// The specification fixes TCAS (1) at S0:B2, but a card may carry the support +// layer elsewhere, so fall back to a scan for the identifier. +static bool rkf_find_tcas(const uint8_t *dump, size_t dumplen, uint8_t skip_sector, + uint8_t skip_block, uint8_t *sector, uint8_t *block) { + + uint8_t nsectors = rkf_sector_count(dumplen); + + for (uint8_t s = 0; s < nsectors; s++) { + for (uint8_t b = 0; b < rkf_data_blocks(s); b++) { + + if (s == skip_sector && b == skip_block) { + continue; + } + + const uint8_t *blk = rkf_block(dump, dumplen, s, b); + if (blk == NULL) { + continue; + } + + uint8_t version = (uint8_t)rkf_bits(blk, 8, 6); + if (blk[0] == RKF_TCAS_IDENTIFIER && version > 0 && version < 16) { + *sector = s; + *block = b; + return true; + } + } + } + return false; +} + +// RKF-0022 7.3.4 places the MAC authenticator in the last bits of the last +// block. On every card tested the algorithm and key identifiers sit immediately +// before it, so the final 24 bits of a MACed object are +// MACAlgorithmIdentifier(2) | MACKeyIdentifier(6) | MACAuthenticator16(16). +static void rkf_read_mac(const uint8_t *buf, uint16_t nbits, uint8_t *alg, uint8_t *key, uint16_t *mac) { + *alg = (uint8_t)rkf_bits(buf, nbits - 24, 2); + *key = (uint8_t)rkf_bits(buf, nbits - 22, 6); + *mac = (uint16_t)rkf_bits(buf, nbits - 16, 16); +} + +static void rkf_print_aid(const char *label, uint16_t aid) { + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("0x%03X") " ( %s )", label, aid, rkf_aid_name(aid)); +} + +static void rkf_print_mac(uint8_t alg, uint8_t key, uint16_t mac) { + + // DES-MAC is the only algorithm the specification defines, so anything else + // means these bits are not the MAC trio on this card + if (alg != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( " _YELLOW_("not a defined algorithm") " )", + "MAC", mac, alg); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("the MAC trio is not at the expected offsets here"), ""); + return; + } + + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( %s ), key id %u", + "MAC", mac, alg, rkf_mac_alg_name(alg), key); +} + +//----------------------------------------------------------------------------- +// Detection +//----------------------------------------------------------------------------- + +bool is_valid_rkf_card(const uint8_t *dump, size_t dumplen) { + + if (dump == NULL || dumplen < MIFARE_1K_MAX_BYTES) { + return false; + } + + // TCCI is always the second block of sector 0. Its MADInfoByte is 0 because + // the travel card does not use a MAD, and its CardProvider must be an AID + // that RKF-0019 has handed to a transport authority. + const uint8_t *tcci = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_TCCI_BLOCK); + if (tcci == NULL || tcci[0] != 0x00 || tcci[1] != 0x00) { + return false; + } + + uint8_t version = (uint8_t)rkf_bits(tcci, 16, 6); + uint16_t provider = (uint16_t)rkf_bits(tcci, 22, 12); + + if (version == 0 || provider < 0x064 || provider > 0x0BB7) { + return false; + } + + // and the card must carry an applications status block somewhere + uint8_t s, b; + return rkf_find_tcas(dump, dumplen, 0xFF, 0xFF, &s, &b); +} + +//----------------------------------------------------------------------------- +// Card issuer and travel card support layer +//----------------------------------------------------------------------------- + +static void rkf_print_cmi(const uint8_t *blk) { + + uint32_t csn = (uint32_t)rkf_bits(blk, 0, 32); + uint8_t chk = (uint8_t)rkf_bits(blk, 32, 8); + uint8_t calc = blk[0] ^ blk[1] ^ blk[2] ^ blk[3]; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("CMI, card manufacturer information") " ---"); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%08X") " ( %s )", "Card serial no", csn, sprint_hex_inrow(blk, 4)); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Check byte", chk, + (chk == calc) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Manufacturer data", sprint_hex_inrow(blk + 5, 11)); +} + +typedef struct { + uint16_t mad_info; + uint8_t card_version; + uint16_t card_provider; + uint16_t validity_end; + uint8_t card_status; + uint16_t currency_unit; + uint8_t event_log_version; + uint8_t mac_alg; + uint8_t mac_key; + uint16_t mac; +} rkf_tcci_t; + +static void rkf_read_tcci(const uint8_t *blk, rkf_tcci_t *t) { + t->mad_info = (uint16_t)rkf_bits(blk, 0, 16); + t->card_version = (uint8_t)rkf_bits(blk, 16, 6); + t->card_provider = (uint16_t)rkf_bits(blk, 22, 12); + t->validity_end = (uint16_t)rkf_bits(blk, 34, 14); + t->card_status = (uint8_t)rkf_bits(blk, 48, 8); + t->currency_unit = (uint16_t)rkf_bits(blk, 56, 16); + t->event_log_version = (uint8_t)rkf_bits(blk, 72, 6); + rkf_read_mac(blk, RKF_BLOCK_BITS, &t->mac_alg, &t->mac_key, &t->mac); +} + +static void rkf_print_tcci(const rkf_tcci_t *t) { + + char buf[32]; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCCI, card information") " ---"); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "MAD info byte", t->mad_info, + (t->mad_info == 0) ? "MAD not available" : "unknown"); + PrintAndLogEx(INFO, RKF_LABEL " %u%s", "Card version", t->card_version, + (t->card_version == 2) ? "" : _YELLOW_(" ( RKF-0022/0023 describe version 2 )")); + rkf_print_aid("Card provider", t->card_provider); + + rkf_date_str(t->validity_end, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), "Valid until", buf); + + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Card status", t->card_status, + rkf_status_name(t->card_status)); + + rkf_currency_str(t->currency_unit, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %04X ( %s )", "Currency unit", t->currency_unit, buf); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Event log version", t->event_log_version); + rkf_print_mac(t->mac_alg, t->mac_key, t->mac); +} + +typedef struct { + uint8_t identifier; + uint8_t version; + uint8_t sector_status[RKF_SECTORS]; + uint8_t transaction_no; + uint8_t event_log_record; + uint8_t log_area; + uint8_t log_pointer[8]; + uint8_t mac_alg; + uint8_t mac_key; + uint16_t mac; +} rkf_tcas_t; + +static const char *rkf_log_slot(const rkf_tcas_t *t, uint8_t sector) { + static const char *slot[] = { + "current ticket", "previous ticket", "log ticket 1", "log ticket 2", + "log ticket 3", "log ticket 4", "log ticket 5", "log ticket 6" + }; + for (uint8_t i = 0; i < ARRAYLEN(slot); i++) { + if (t->log_pointer[i] == sector) { + return slot[i]; + } + } + return "not referenced by TCAS"; +} + +static void rkf_read_tcas(const uint8_t *blk, rkf_tcas_t *t) { + t->identifier = (uint8_t)rkf_bits(blk, 0, 8); + t->version = (uint8_t)rkf_bits(blk, 8, 6); + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + t->sector_status[s] = (uint8_t)rkf_bits(blk, 14 + (2 * s), 2); + } + t->transaction_no = (uint8_t)rkf_bits(blk, 46, 8); + t->event_log_record = (uint8_t)rkf_bits(blk, 54, 4); + t->log_area = (uint8_t)rkf_bits(blk, 58, 4); + for (uint8_t i = 0; i < 8; i++) { + t->log_pointer[i] = (uint8_t)rkf_bits(blk, 62 + (4 * i), 4); + } + rkf_read_mac(blk, RKF_BLOCK_BITS, &t->mac_alg, &t->mac_key, &t->mac); +} + +static void rkf_print_tcas(const rkf_tcas_t *t, uint8_t instance, uint8_t sector, uint8_t block) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCAS (%u), applications status") " --- S%u:B%u", + instance, sector, block); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Identifier", t->identifier, + (t->identifier == RKF_TCAS_IDENTIFIER) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Version", t->version); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Transaction no", t->transaction_no); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Event log record", t->event_log_record); + + if (t->log_area == 0) { + PrintAndLogEx(INFO, RKF_LABEL " none", "Ticket/log area"); + } else { + PrintAndLogEx(INFO, RKF_LABEL " first sector %u", "Ticket/log area", t->log_area); + for (uint8_t i = 0; i < ARRAYLEN(t->log_pointer); i++) { + if (t->log_pointer[i] != 0) { + PrintAndLogEx(INFO, RKF_LABEL " sector %2u ( %s )", "", t->log_pointer[i], + rkf_log_slot(t, t->log_pointer[i])); + } + } + } + + rkf_print_mac(t->mac_alg, t->mac_key, t->mac); + + uint8_t defined = 0; + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + if (t->sector_status[s] != 0) { + defined++; + } + } + + PrintAndLogEx(INFO, RKF_LABEL " %u of %u sectors defined", "Sector status", defined, RKF_SECTORS); + for (uint8_t s = 0; s < RKF_SECTORS; s++) { + if (t->sector_status[s] != 0) { + PrintAndLogEx(INFO, RKF_LABEL " sector %2u %u ( %s )", "", s, + t->sector_status[s], rkf_sector_status_name(t->sector_status[s])); + } + } +} + +// The directory covers sectors 1..15, five entries to a block +static void rkf_read_tcdi(const uint8_t *dump, size_t dumplen, uint16_t *aid, uint16_t *pix) { + + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + aid[s] = RKF_AID_FREE; + pix[s] = 0; + } + + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, RKF_TCDI_SECTOR, b); + if (blk == NULL) { + continue; + } + for (uint8_t i = 0; i < 5; i++) { + uint8_t s = 1 + (5 * b) + i; + aid[s] = (uint16_t)rkf_bits(blk, 24 * i, 12); + pix[s] = (uint16_t)rkf_bits(blk, (24 * i) + 12, 12); + } + } +} + +static void rkf_print_tcdi(const uint8_t *dump, size_t dumplen, const uint16_t *aid, const uint16_t *pix) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCDI, directory") " ---"); + PrintAndLogEx(INFO, " sector | AID | PIX | interpretation"); + PrintAndLogEx(INFO, "--------+------+------+---------------------------------------------"); + + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + + const char *what; + if (pix[s] == RKF_PIX_CONT && aid[s] > RKF_AID_RESERVED) { + what = "continuation of the preceding sector"; + } else { + what = rkf_aid_name(aid[s]); + } + + PrintAndLogEx(INFO, " %2u | %03X | %03X | %s", s, aid[s], pix[s], what); + } + + PrintAndLogEx(INFO, "--------+------+------+---------------------------------------------"); + + char line[96] = {0}; + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, RKF_TCDI_SECTOR, b); + if (blk) { + str_append(line, sizeof(line), "%02X ( %s ) ", blk[MFBLOCK_SIZE - 1], rkf_checksum_str(blk)); + } + } + PrintAndLogEx(INFO, RKF_LABEL " %s", "Checksums", line); +} + +//----------------------------------------------------------------------------- +// TCPU, purse +//----------------------------------------------------------------------------- + +static void rkf_print_tcpu(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t current, uint16_t cu) { + + char buf[40]; + + const uint8_t *st = rkf_block(dump, dumplen, sector, 0); + if (st == NULL) { + return; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCPU, purse") " --- sector %u", sector); + + uint8_t version = (uint8_t)rkf_bits(st, 8, 6); + + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(st, 0, 8), version); + rkf_print_aid("Purse provider", (uint16_t)rkf_bits(st, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%08X"), "Purse serial no", (uint32_t)rkf_bits(st, 26, 32)); + + rkf_date_str((uint16_t)rkf_bits(st, 58, 14), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Start date", buf); + + uint8_t dp = (uint8_t)rkf_bits(st, 72, 4); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Data pointer", dp, + (dp == 0) ? "unused" : "PTA area sector"); + + rkf_money_str(rkf_signed(rkf_bits(st, 76, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Minimum value", buf); + + rkf_money_str(rkf_signed(rkf_bits(st, 100, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Autoload value", buf); + + for (uint8_t b = 1; b <= 2; b++) { + + const uint8_t *dy = rkf_block(dump, dumplen, sector, b); + if (dy == NULL) { + continue; + } + + bool live = (current == b); + PrintAndLogEx(INFO, " " _CYAN_("dynamic data (%u)") " %s", b, + live ? _GREEN_("<- current") : ""); + + PrintAndLogEx(INFO, RKF_LABEL " %u", " Transaction no", (uint16_t)rkf_bits(dy, 0, 16)); + + // version 4 drops EndDate and moves Value up against the transaction + // number; the rest of the block is not known + if (version == 4) { + + rkf_money_str(rkf_signed(rkf_bits(dy, 16, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Value", buf); + PrintAndLogEx(INFO, RKF_LABEL " %s " _YELLOW_("not decoded"), " Bits 40..103", + sprint_hex_inrow(dy + 5, 8)); + + uint8_t valg, vkey; + uint16_t vmac; + rkf_read_mac(dy, RKF_BLOCK_BITS, &valg, &vkey, &vmac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", vmac, valg, vkey); + continue; + } + + rkf_date_str((uint16_t)rkf_bits(dy, 16, 14), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " End date", buf); + + rkf_money_str(rkf_signed(rkf_bits(dy, 30, 24), 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Value", buf); + + uint8_t status = (uint8_t)rkf_bits(dy, 54, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", " Status", status, rkf_status_name(status)); + + rkf_money_str((int32_t)rkf_bits(dy, 62, 20), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " Deposit", buf); + + uint8_t al = (uint8_t)rkf_bits(dy, 82, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", " Autoload", al, + (al == 1) ? "enabled" : ((al == 0) ? "disabled" : "RFU")); + + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", + (uint16_t)rkf_bits(dy, 112, 16), + (uint8_t)rkf_bits(dy, 84, 2), + (uint8_t)rkf_bits(dy, 86, 6)); + } +} + +//----------------------------------------------------------------------------- +// TCEL, event log +//----------------------------------------------------------------------------- + +static void rkf_print_event_record(const uint8_t *blk, uint8_t record, bool newest, uint16_t cu) { + + char date[16], time[16], buf[40]; + + uint8_t id = (uint8_t)rkf_bits(blk, 0, 8); + uint8_t code = (uint8_t)rkf_bits(blk, 90, 6); + uint32_t data = (uint32_t)rkf_bits(blk, 96, 24); + + const char *name = NULL; + rkf_evdata_t kind = rkf_event_kind(code, &name); + + if (code == 0) { + PrintAndLogEx(INFO, " record %-2u " _YELLOW_("unused") " ( event code 00, checksum %02X %s )", + record, blk[MFBLOCK_SIZE - 1], rkf_checksum_ok(blk) ? "ok" : "not set"); + return; + } + (void)id; + + rkf_date_str((uint16_t)rkf_bits(blk, 8, 14), date, sizeof(date)); + rkf_time_str((uint16_t)rkf_bits(blk, 22, 16), time, sizeof(time)); + + PrintAndLogEx(INFO, " record %-2u %s %s %02X %s %s", record, date, time, code, name, + newest ? _GREEN_("<- most recent") : ""); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X ( %s ), device %04X, device txn %u", "", + (uint16_t)rkf_bits(blk, 38, 12), + rkf_aid_name((uint16_t)rkf_bits(blk, 38, 12)), + (uint16_t)rkf_bits(blk, 50, 16), + (uint32_t)rkf_bits(blk, 66, 24)); + + switch (kind) { + case RKF_EVD_A: + rkf_money_str((int32_t)((data >> 4) & 0xFFFFF), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " sector %u, price %s", "", data & 0x0F, buf); + break; + case RKF_EVD_B: + PrintAndLogEx(INFO, RKF_LABEL " ticket sector %u, contract sector %u", "", + data & 0x0F, (data >> 4) & 0x0F); + break; + case RKF_EVD_C: + PrintAndLogEx(INFO, RKF_LABEL " ticket sector %u, PTA data %05X", "", + data & 0x0F, (data >> 4) & 0xFFFFF); + break; + case RKF_EVD_D: + rkf_money_str(rkf_signed(data, 24), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " amount %s", "", buf); + break; + case RKF_EVD_NONE: + default: + PrintAndLogEx(INFO, RKF_LABEL " event data %06X", "", data); + break; + } + + PrintAndLogEx(INFO, RKF_LABEL " checksum %02X ( %s )", "", + blk[MFBLOCK_SIZE - 1], rkf_checksum_str(blk)); +} + +static void rkf_print_tcel(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint8_t newest, uint16_t cu) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCEL, event log") " --- sector %u..%u", + sector, sector + nsectors - 1); + + for (uint8_t s = 0; s < nsectors; s++) { + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, sector + s, b); + if (blk) { + uint8_t record = (3 * s) + b; + rkf_print_event_record(blk, record, (record == newest), cu); + } + } + } +} + +//----------------------------------------------------------------------------- +// Fixed layout application objects +//----------------------------------------------------------------------------- + +static void rkf_print_subgroup(const uint8_t *buf, uint16_t off, uint8_t n) { + for (uint8_t i = 0; i < n; i++) { + uint8_t type = (uint8_t)rkf_bits(buf, off + (14 * i), 8); + uint8_t total = (uint8_t)rkf_bits(buf, off + (14 * i) + 8, 6); + if (total != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %u x %s ( type %u )", "", total, + rkf_passenger_type_name(type), type); + } + } +} + +static void rkf_print_tcdb(const uint8_t *dump, size_t dumplen, uint8_t sector, uint8_t current) { + + char buf[32]; + + const uint8_t *st = rkf_block(dump, dumplen, sector, 0); + if (st == NULL) { + return; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCDB, discount basis") " --- sector %u", sector); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(st, 0, 8), (uint8_t)rkf_bits(st, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(st, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " %u, %u, %u", "Discount types", + (uint8_t)rkf_bits(st, 26, 8), + (uint8_t)rkf_bits(st, 34, 8), + (uint8_t)rkf_bits(st, 42, 8)); + + for (uint8_t b = 1; b <= 2; b++) { + + const uint8_t *dy = rkf_block(dump, dumplen, sector, b); + if (dy == NULL) { + continue; + } + + PrintAndLogEx(INFO, " " _CYAN_("dynamic data (%u)") " %s", b, + (current == b) ? _GREEN_("<- current") : ""); + + uint8_t status = (uint8_t)rkf_bits(dy, 0, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", " Status", status, rkf_status_name(status)); + + rkf_month8_str((uint8_t)rkf_bits(dy, 8, 8), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", " First month", buf); + + for (uint8_t i = 0; i < 3; i++) { + uint16_t off = 16 + (29 * i); + PrintAndLogEx(INFO, RKF_LABEL " block %u counters %u / %u, levels %u %u %u", "", i + 1, + (uint8_t)rkf_bits(dy, off, 8), + (uint16_t)rkf_bits(dy, off + 8, 12), + (uint8_t)rkf_bits(dy, off + 20, 3), + (uint8_t)rkf_bits(dy, off + 23, 3), + (uint8_t)rkf_bits(dy, off + 26, 3)); + } + + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(dy, RKF_BLOCK_BITS, &alg, &key, &mac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u, key id %u", " MAC", mac, alg, key); + } +} + +static void rkf_print_tccp(const uint8_t *dump, size_t dumplen, uint8_t sector) { + + char buf[32]; + uint8_t d[2 * MFBLOCK_SIZE]; + + const uint8_t *b0 = rkf_block(dump, dumplen, sector, 0); + const uint8_t *b1 = rkf_block(dump, dumplen, sector, 1); + if (b0 == NULL || b1 == NULL) { + return; + } + memcpy(d, b0, MFBLOCK_SIZE); + memcpy(d + MFBLOCK_SIZE, b1, MFBLOCK_SIZE); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCCP, customer profile") " --- sector %u", sector); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(d, 0, 8), (uint8_t)rkf_bits(d, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(d, 14, 12)); + + uint8_t status = (uint8_t)rkf_bits(d, 26, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Status", status, rkf_status_name(status)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%010llu"), "Customer no", + (unsigned long long)rkf_bits(d, 34, 34)); + + uint8_t pclass = (uint8_t)rkf_bits(d, 68, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Passenger class", pclass, + rkf_passenger_class_name(pclass)); + rkf_print_subgroup(d, 70, 3); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Validation level", (uint8_t)rkf_bits(d, 112, 2)); + + rkf_month11_str((uint16_t)rkf_bits(d, 114, 11), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " %s", "Birth month", buf); + + PrintAndLogEx(INFO, RKF_LABEL " %u", "Language", (uint8_t)rkf_bits(d, 125, 4)); + PrintAndLogEx(INFO, RKF_LABEL " %02X", "Dialogue prefs", (uint8_t)rkf_bits(d, 129, 8)); + rkf_print_aid("Subscr. company", (uint16_t)rkf_bits(d, 137, 12)); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Subscr. type", (uint8_t)rkf_bits(d, 149, 8)); + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(d, 2 * RKF_BLOCK_BITS, &alg, &key, &mac); + rkf_print_mac(alg, key, mac); +} + +static void rkf_print_tcst(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint16_t cu, const char *role) { + + char buf[40]; + uint8_t d[3 * MFBLOCK_SIZE]; + + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *p = rkf_block(dump, dumplen, sector, b); + if (p == NULL) { + return; + } + memcpy(d + (b * MFBLOCK_SIZE), p, MFBLOCK_SIZE); + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("TCST-ci/co, special ticket") " --- sector %u ( %s )", sector, role); + PrintAndLogEx(INFO, RKF_LABEL " %02X, version %u", "Identifier", + (uint8_t)rkf_bits(d, 0, 8), (uint8_t)rkf_bits(d, 8, 6)); + rkf_print_aid("Provider", (uint16_t)rkf_bits(d, 14, 12)); + PrintAndLogEx(INFO, RKF_LABEL " 0x%03X", "PIX", (uint16_t)rkf_bits(d, 26, 12)); + + uint8_t status = (uint8_t)rkf_bits(d, 38, 8); + PrintAndLogEx(INFO, RKF_LABEL " %02X ( %s )", "Status", status, rkf_status_name(status)); + + uint8_t pclass = (uint8_t)rkf_bits(d, 46, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s )", "Passenger class", pclass, + rkf_passenger_class_name(pclass)); + rkf_print_subgroup(d, 48, 3); + + PrintAndLogEx(INFO, RKF_LABEL " %s, %s", "Validation", + rkf_validation_model_name((uint8_t)rkf_bits(d, 90, 2)), + rkf_validation_status_name((uint8_t)rkf_bits(d, 92, 2))); + PrintAndLogEx(INFO, RKF_LABEL " %u", "Validation level", (uint8_t)rkf_bits(d, 94, 2)); + + rkf_money_str((int32_t)rkf_bits(d, 96, 20), cu, buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s") ", modification level %u", "Price", + buf, (uint8_t)rkf_bits(d, 116, 6)); + + rkf_datetime_str((uint32_t)rkf_bits(d, 148, 24), buf, sizeof(buf)); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u at %s", "Origin", + (uint16_t)rkf_bits(d, 122, 12), (uint16_t)rkf_bits(d, 134, 14), buf); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Furthest", + (uint16_t)rkf_bits(d, 172, 12), (uint16_t)rkf_bits(d, 184, 14), + (uint16_t)rkf_bits(d, 198, 10)); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Destination", + (uint16_t)rkf_bits(d, 208, 12), (uint16_t)rkf_bits(d, 220, 14), + (uint16_t)rkf_bits(d, 234, 10)); + + uint8_t sup = (uint8_t)rkf_bits(d, 244, 2); + PrintAndLogEx(INFO, RKF_LABEL " %u ( %s ), type %u, AID 0x%03X place %u, distance %u", "Supplement", + sup, rkf_supplement_status_name(sup), + (uint8_t)rkf_bits(d, 246, 6), + (uint16_t)rkf_bits(d, 252, 12), + (uint16_t)rkf_bits(d, 264, 14), + (uint16_t)rkf_bits(d, 278, 12)); + + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u, +%u min", "Latest control", + (uint16_t)rkf_bits(d, 290, 12), (uint16_t)rkf_bits(d, 302, 14), + (uint16_t)rkf_bits(d, 316, 10)); + + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(d, 3 * RKF_BLOCK_BITS, &alg, &key, &mac); + rkf_print_mac(alg, key, mac); +} + +//----------------------------------------------------------------------------- +// TCTI / TCCO, a chain of identifier prefixed data element groups +//----------------------------------------------------------------------------- + +// Total size of each group in bits, identifier byte included, RKF-0023 3.4.3 +static uint8_t rkf_group_size(uint8_t id) { + switch (id) { + case RKF_ID_TCTI_HEADER: + case RKF_ID_TCCO_HEADER: + case RKF_ID_VALIDATION: + return 14; + case RKF_ID_DYN_MULTI: + return 20; + case RKF_ID_MANDATORY: + return 88; + case RKF_ID_DYN_SINGLE: + return 8; + case RKF_ID_MAC: + case RKF_ID_VAL_ROUTE: + return 32; + case RKF_ID_PRICE: + return 28; + case RKF_ID_ISSUER: + return 12; + case RKF_ID_TCCO_PERIOD: + return 114; + case RKF_ID_VAL_DISTANCE: + return 142; + case RKF_ID_VAL_ZONE: + return 34; + case RKF_ID_TCCO_ISSUING: + return 54; + case RKF_ID_CUSTOMER: + return 42; + case RKF_ID_CLASS: + return 52; + case RKF_ID_TCTI_PERIOD: + return 68; + case RKF_ID_TCTI_ISSUING: + return 38; + default: + return 0; + } +} + +static void rkf_print_group(const rkf_run_t *run, uint16_t off, uint8_t id, uint16_t cu) { + + char a[16], b[16], c[16], d[16]; + + switch (id) { + + case RKF_ID_TCTI_HEADER: + PrintAndLogEx(INFO, RKF_LABEL " version %u", " TCTI header", + (uint8_t)rkf_run_bits(run, off + 8, 6)); + break; + + case RKF_ID_TCCO_HEADER: + PrintAndLogEx(INFO, RKF_LABEL " version %u", " TCCO header", + (uint8_t)rkf_run_bits(run, off + 8, 6)); + break; + + case RKF_ID_DYN_MULTI: + PrintAndLogEx(INFO, RKF_LABEL " transaction no %u", " Dynamic info", + (uint16_t)rkf_run_bits(run, off + 8, 12)); + break; + + case RKF_ID_DYN_SINGLE: + PrintAndLogEx(INFO, RKF_LABEL " single block", " Dynamic info"); + break; + + case RKF_ID_MANDATORY: { + uint16_t aid = (uint16_t)rkf_run_bits(run, off + 8, 12); + uint8_t status = (uint8_t)rkf_run_bits(run, off + 80, 8); + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X ( %s ), PIX 0x%03X", " Mandatory", + aid, rkf_aid_name(aid), (uint16_t)rkf_run_bits(run, off + 20, 12)); + PrintAndLogEx(INFO, RKF_LABEL " sale device %04X, serial " _YELLOW_("%08X") ", status %02X ( %s )", "", + (uint16_t)rkf_run_bits(run, off + 32, 16), + (uint32_t)rkf_run_bits(run, off + 48, 32), + status, rkf_status_name(status)); + break; + } + + case RKF_ID_MAC: { + // the authenticator is the last 16 bits of the block, past the checksum position + const uint8_t *last = rkf_run_block(run, (uint8_t)(off / RKF_USABLE_BITS)); + if (last == NULL) { + break; + } + uint8_t alg, key; + uint16_t mac; + rkf_read_mac(last, RKF_BLOCK_BITS, &alg, &key, &mac); + PrintAndLogEx(INFO, RKF_LABEL " %04X, algorithm %u ( %s ), key id %u", " MAC", + mac, alg, rkf_mac_alg_name(alg), key); + break; + } + + case RKF_ID_PRICE: + rkf_money_str((int32_t)rkf_run_bits(run, off + 8, 20), cu, a, sizeof(a)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s"), " Price", a); + break; + + case RKF_ID_ISSUER: + PrintAndLogEx(INFO, RKF_LABEL " sector %u", " Issued by", + (uint8_t)rkf_run_bits(run, off + 8, 4)); + break; + + case RKF_ID_TCCO_PERIOD: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 38, 14), c, sizeof(c)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 52, 16), d, sizeof(d)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s %s") " .. " _YELLOW_("%s %s"), + " TCCO validity", a, b, c, d); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 76, 14), a, sizeof(a)); + PrintAndLogEx(INFO, RKF_LABEL " duration %u, first use by %s, %u journeys", "", + (uint8_t)rkf_run_bits(run, off + 68, 8), a, + (uint8_t)rkf_run_bits(run, off + 90, 8)); + PrintAndLogEx(INFO, RKF_LABEL " not valid on days %02X, time codes %02X", "", + (uint8_t)rkf_run_bits(run, off + 98, 8), + (uint8_t)rkf_run_bits(run, off + 106, 8)); + break; + + case RKF_ID_TCTI_PERIOD: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + rkf_date_str((uint16_t)rkf_run_bits(run, off + 38, 14), c, sizeof(c)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 52, 16), d, sizeof(d)); + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%s %s") " .. " _YELLOW_("%s %s"), + " TCTI validity", a, b, c, d); + break; + + case RKF_ID_VAL_DISTANCE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X place %u -> AID 0x%03X place %u", " Distance", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 14), + (uint16_t)rkf_run_bits(run, off + 34, 12), + (uint16_t)rkf_run_bits(run, off + 46, 14)); + PrintAndLogEx(INFO, RKF_LABEL " distance %u, run %u, interchanges %u", "", + (uint16_t)rkf_run_bits(run, off + 60, 12), + (uint16_t)rkf_run_bits(run, off + 72, 12), + (uint8_t)rkf_run_bits(run, off + 136, 6)); + PrintAndLogEx(INFO, RKF_LABEL " via AID 0x%03X place %u, AID 0x%03X place %u", "", + (uint16_t)rkf_run_bits(run, off + 84, 12), + (uint16_t)rkf_run_bits(run, off + 96, 14), + (uint16_t)rkf_run_bits(run, off + 110, 12), + (uint16_t)rkf_run_bits(run, off + 122, 14)); + break; + + case RKF_ID_VAL_ROUTE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X route %u", " Route", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 12)); + break; + + case RKF_ID_VAL_ZONE: + PrintAndLogEx(INFO, RKF_LABEL " AID 0x%03X zone %u", " Zone", + (uint16_t)rkf_run_bits(run, off + 8, 12), + (uint16_t)rkf_run_bits(run, off + 20, 14)); + break; + + case RKF_ID_TCCO_ISSUING: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 24, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 38, 16), b, sizeof(b)); + PrintAndLogEx(INFO, RKF_LABEL " %u journeys issued, %u in period, last %s %s", " TCCO issuing", + (uint8_t)rkf_run_bits(run, off + 8, 8), + (uint8_t)rkf_run_bits(run, off + 16, 8), a, b); + break; + + case RKF_ID_TCTI_ISSUING: + rkf_date_str((uint16_t)rkf_run_bits(run, off + 8, 14), a, sizeof(a)); + rkf_time_str((uint16_t)rkf_run_bits(run, off + 22, 16), b, sizeof(b)); + PrintAndLogEx(INFO, RKF_LABEL " last validation %s %s", " TCTI issuing", a, b); + break; + + case RKF_ID_CUSTOMER: + PrintAndLogEx(INFO, RKF_LABEL " " _YELLOW_("%010llu"), " Customer no", + (unsigned long long)rkf_run_bits(run, off + 8, 34)); + break; + + case RKF_ID_CLASS: { + uint8_t pclass = (uint8_t)rkf_run_bits(run, off + 8, 2); + PrintAndLogEx(INFO, RKF_LABEL " %s", " Class", rkf_passenger_class_name(pclass)); + for (uint8_t i = 0; i < 3; i++) { + uint8_t type = (uint8_t)rkf_run_bits(run, off + 10 + (14 * i), 8); + uint8_t total = (uint8_t)rkf_run_bits(run, off + 18 + (14 * i), 6); + if (total != 0) { + PrintAndLogEx(INFO, RKF_LABEL " %u x %s ( type %u )", "", total, + rkf_passenger_type_name(type), type); + } + } + break; + } + + case RKF_ID_VALIDATION: + PrintAndLogEx(INFO, RKF_LABEL " %s, %s, level %u", " Validation", + rkf_validation_model_name((uint8_t)rkf_run_bits(run, off + 8, 2)), + rkf_validation_status_name((uint8_t)rkf_run_bits(run, off + 10, 2)), + (uint8_t)rkf_run_bits(run, off + 12, 2)); + break; + + default: + break; + } +} + +// Walk the identifier chain over a run of sectors. An element ends at the MAC +// group, which the specification pins to the last block of the element, so the +// next element starts at the following block boundary. +static bool rkf_block_is_blank(const uint8_t *blk) { + for (uint8_t i = 0; i < MFBLOCK_SIZE; i++) { + if (blk[i] != 0x00 && blk[i] != 0xFF) { + return false; + } + } + return true; +} + +static void rkf_print_chain(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint16_t aid, uint16_t pix, uint16_t cu) { + + if (rkf_block(dump, dumplen, sector, 0) == NULL) { + return; + } + + uint8_t total = 0; + for (uint8_t k = 0; k < nsectors; k++) { + total += rkf_data_blocks(sector + k); + } + + rkf_run_t run = { .dump = dump, .dumplen = dumplen, .sector = sector, .nblocks = total }; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("application object") " --- sector %u..%u, AID 0x%03X ( %s ), PIX 0x%03X", + sector, sector + nsectors - 1, aid, rkf_aid_name(aid), pix); + + uint16_t off = 0; + uint8_t element = 1; + bool started = false; + + while (off < (uint16_t)run.nblocks * RKF_USABLE_BITS) { + + uint8_t id = (uint8_t)rkf_run_bits(&run, off, 8); + uint8_t size = rkf_group_size(id); + + if (size == 0 || (off + size) > ((uint16_t)run.nblocks * RKF_USABLE_BITS)) { + // not a group, resume at the next block boundary + uint16_t blk = off / RKF_USABLE_BITS; + if (off % RKF_USABLE_BITS == 0) { + const uint8_t *raw = rkf_run_block(&run, (uint8_t)blk); + if (raw != NULL && rkf_block_is_blank(raw) == false) { + PrintAndLogEx(INFO, " block %u " _YELLOW_("not decoded") " %s checksum ( %s )", blk, + sprint_hex_inrow(raw, MFBLOCK_SIZE), rkf_checksum_str(raw)); + } + } + blk++; + if (blk >= run.nblocks) { + break; + } + off = blk * RKF_USABLE_BITS; + started = false; + continue; + } + + if (started == false) { + PrintAndLogEx(INFO, " " _CYAN_("element %u") " from block %u", element, off / RKF_USABLE_BITS); + element++; + started = true; + } + + rkf_print_group(&run, off, id, cu); + + if (id == RKF_ID_MAC) { + uint16_t blk = (off / RKF_USABLE_BITS) + 1; + if (blk >= run.nblocks) { + break; + } + off = blk * RKF_USABLE_BITS; + started = false; + continue; + } + + off += size; + } +} + +//----------------------------------------------------------------------------- +// Top level +//----------------------------------------------------------------------------- + +static void rkf_print_application(const uint8_t *dump, size_t dumplen, uint8_t sector, + uint8_t nsectors, uint16_t aid, uint16_t pix, + const rkf_tcas_t *tcas, uint16_t cu) { + + const uint8_t *first = rkf_block(dump, dumplen, sector, 0); + uint8_t id = (first != NULL) ? first[0] : 0; + uint8_t status = (sector < RKF_SECTORS) ? tcas->sector_status[sector] : 0; + + switch (id) { + case RKF_ID_TCPU_STATIC: + rkf_print_tcpu(dump, dumplen, sector, status, cu); + break; + case RKF_ID_TCDB: + rkf_print_tcdb(dump, dumplen, sector, status); + break; + case RKF_ID_TCCP: + rkf_print_tccp(dump, dumplen, sector); + break; + case RKF_ID_TCST: + for (uint8_t k = 0; k < nsectors; k++) { + rkf_print_tcst(dump, dumplen, sector + k, cu, rkf_log_slot(tcas, sector + k)); + } + break; + case RKF_ID_TCEL_RECORD: + rkf_print_tcel(dump, dumplen, sector, nsectors, tcas->event_log_record, cu); + break; + default: + rkf_print_chain(dump, dumplen, sector, nsectors, aid, pix, cu); + break; + } +} + +// A card is free to leave the directory empty, so when it names no application +// object, fall back to the identifiers of RKF-0022 section 8.1. +static uint8_t rkf_scan_applications(const uint8_t *dump, size_t dumplen, + const rkf_tcas_t *tcas, uint16_t cu, + uint8_t tcas_sector) { + + uint8_t nsectors = rkf_sector_count(dumplen); + uint8_t found = 0; + + for (uint8_t s = RKF_TCDI_SECTOR + 1; s < nsectors; s++) { + + if (s == tcas_sector) { + continue; + } + + const uint8_t *blk = rkf_block(dump, dumplen, s, 0); + if (blk == NULL) { + continue; + } + + uint8_t id = blk[0]; + if (id != RKF_ID_TCPU_STATIC && id != RKF_ID_TCDB && id != RKF_ID_TCCP && + id != RKF_ID_TCST && id != RKF_ID_TCEL_RECORD && + id != RKF_ID_TCTI_HEADER && id != RKF_ID_TCCO_HEADER) { + continue; + } + + // an object runs on while the following sectors open with the same id + uint8_t n = 1; + while ((s + n) < nsectors && (s + n) != tcas_sector) { + const uint8_t *nxt = rkf_block(dump, dumplen, s + n, 0); + if (nxt == NULL || nxt[0] != id) { + break; + } + n++; + } + + rkf_print_application(dump, dumplen, s, n, 0, 0, tcas, cu); + found++; + s += (n - 1); + } + return found; +} + +int rkf_parser_parse(const uint8_t *dump, size_t dumplen) { + + if (is_valid_rkf_card(dump, dumplen) == false) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("RKF travel card") " ------------------------"); + PrintAndLogEx(INFO, "Resekortsforeningen i Norden, type CL-1"); + + const uint8_t *cmi = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_CMI_BLOCK); + if (cmi) { + rkf_print_cmi(cmi); + } + + rkf_tcci_t tcci = {0}; + const uint8_t *p = rkf_block(dump, dumplen, RKF_CMI_SECTOR, RKF_TCCI_BLOCK); + if (p) { + rkf_read_tcci(p, &tcci); + rkf_print_tcci(&tcci); + } + + uint16_t aid[RKF_SECTORS] = {0}; + uint16_t pix[RKF_SECTORS] = {0}; + rkf_read_tcdi(dump, dumplen, aid, pix); + + rkf_tcas_t tcas1 = {0}; + rkf_tcas_t tcas2 = {0}; + bool have_tcas2 = false; + + // The specification fixes TCAS (1) at S0:B2 and puts TCAS (2) in the first + // block of the sector the directory marks with AID 05 H, but a card is free + // to carry the support layer elsewhere, so both are located by scan. + uint8_t s1 = 0, b1 = 0; + if (rkf_find_tcas(dump, dumplen, 0xFF, 0xFF, &s1, &b1)) { + p = rkf_block(dump, dumplen, s1, b1); + rkf_read_tcas(p, &tcas1); + rkf_print_tcas(&tcas1, 1, s1, b1); + + uint8_t s2 = 0, b2 = 0; + if (rkf_find_tcas(dump, dumplen, s1, b1, &s2, &b2)) { + p = rkf_block(dump, dumplen, s2, b2); + rkf_read_tcas(p, &tcas2); + rkf_print_tcas(&tcas2, 2, s2, b2); + have_tcas2 = true; + } + } + + if (have_tcas2) { + bool same = (memcmp(&tcas1, &tcas2, sizeof(rkf_tcas_t)) == 0); + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, RKF_LABEL " %s", "TCAS instances", + same ? _GREEN_("identical") + : _YELLOW_("differ")); + if (same == false) { + PrintAndLogEx(INFO, RKF_LABEL " RKF-0022 4.3.4.2 reads a difference as an interrupted write,", ""); + PrintAndLogEx(INFO, RKF_LABEL " and takes the first consistent instance", ""); + } + } + + rkf_print_tcdi(dump, dumplen, aid, pix); + + uint8_t decoded = 0; + + // Walk the directory. A sector with PIX 01 H continues the preceding + // application object, RKF-0022 section 7.5 rule 10. + for (uint8_t s = 1; s < RKF_SECTORS; s++) { + + if (aid[s] <= RKF_AID_RESERVED || aid[s] == RKF_AID_TCDI || aid[s] == RKF_AID_TCAS2) { + continue; + } + if (pix[s] == RKF_PIX_CONT) { + continue; + } + + uint8_t n = 1; + while ((s + n) < RKF_SECTORS && aid[s + n] == aid[s] && pix[s + n] == RKF_PIX_CONT) { + n++; + } + + decoded++; + + switch (aid[s]) { + case RKF_AID_TCEL: + rkf_print_tcel(dump, dumplen, s, n, tcas1.event_log_record, tcci.currency_unit); + break; + + case RKF_AID_TCPU: + rkf_print_tcpu(dump, dumplen, s, tcas1.sector_status[s], tcci.currency_unit); + break; + + case RKF_AID_TCPU_DATA: + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("PTA area bound to the purse") " --- sector %u, " + _YELLOW_("PTA specific"), s); + for (uint8_t b = 0; b < 3; b++) { + const uint8_t *blk = rkf_block(dump, dumplen, s, b); + if (blk) { + PrintAndLogEx(INFO, " block %u %s", b, sprint_hex_inrow(blk, MFBLOCK_SIZE)); + } + } + break; + + default: + rkf_print_application(dump, dumplen, s, n, aid[s], pix[s], &tcas1, tcci.currency_unit); + break; + } + + s += (n - 1); + } + + if (tcci.card_version != 2) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(WARNING, "Card reports version %u. The application layouts below are the", + tcci.card_version); + PrintAndLogEx(WARNING, "version 2 layouts of RKF-0023, so field positions may not hold."); + } + + if (decoded == 0) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Directory names no application object, scanning for identifiers"); + decoded = rkf_scan_applications(dump, dumplen, &tcas1, tcci.currency_unit, s1); + if (decoded == 0) { + PrintAndLogEx(INFO, "none found"); + } + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "MAC values are not checked. RKF-0019 holds the MAC key in its edition A,"); + PrintAndLogEx(INFO, "which was only distributed to transport authorities and their suppliers"); + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// Self test +//----------------------------------------------------------------------------- + +#define RKF_T_CSN 0x11223344 +#define RKF_T_PROVIDER 0x0E0 +#define RKF_T_VALID_END 10956 // 2026-12-31 +#define RKF_T_CURRENCY 0x0752 // SEK, main unit +#define RKF_T_TXN 0x5A +#define RKF_T_PURSE_SERIAL 0xDEADBEEF +#define RKF_T_PURSE_VALUE (-12345) +#define RKF_T_DEPOSIT 6000 +#define RKF_T_CUSTOMER 1234567890ULL +#define RKF_T_TICKET_SERIAL 0xCAFEBABE + +#define RKF_T_SEC_PURSE 2 +#define RKF_T_SEC_TCEL 3 +#define RKF_T_SEC_TCAS2 5 +#define RKF_T_SEC_TICKET 6 + +static uint8_t *rkf_test_block(uint8_t *dump, uint8_t sector, uint8_t block) { + return dump + ((size_t)(mfFirstBlockOfSector(sector) + block) * MFBLOCK_SIZE); +} + +static void rkf_set_checksum(uint8_t *blk) { + uint8_t d[MFBLOCK_SIZE - 1]; + memcpy(d, blk, sizeof(d)); + blk[MFBLOCK_SIZE - 1] = (uint8_t)CRC8Mad(d, sizeof(d)); +} + +static void rkf_set_dir(uint8_t *dump, uint8_t sector, uint16_t aid, uint16_t pix) { + uint8_t b = (sector - 1) / 5; + uint8_t i = (sector - 1) % 5; + uint8_t *blk = rkf_test_block(dump, RKF_TCDI_SECTOR, b); + rkf_set_bits(blk, 24 * i, 12, aid); + rkf_set_bits(blk, (24 * i) + 12, 12, pix); +} + +static void rkf_build_selftest_card(uint8_t *dump) { + + memset(dump, 0, MIFARE_1K_MAX_BYTES); + + // CMI, the manufacturer block, check byte over the serial + uint8_t *blk = rkf_test_block(dump, 0, RKF_CMI_BLOCK); + rkf_set_bits(blk, 0, 32, RKF_T_CSN); + rkf_set_bits(blk, 32, 8, blk[0] ^ blk[1] ^ blk[2] ^ blk[3]); + memset(blk + 5, 0xA5, 11); + + // TCCI + blk = rkf_test_block(dump, 0, RKF_TCCI_BLOCK); + rkf_set_bits(blk, 0, 16, 0); + rkf_set_bits(blk, 16, 6, 2); + rkf_set_bits(blk, 22, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 34, 14, RKF_T_VALID_END); + rkf_set_bits(blk, 48, 8, 0x01); + rkf_set_bits(blk, 56, 16, RKF_T_CURRENCY); + rkf_set_bits(blk, 72, 6, 1); + rkf_set_bits(blk, 78, 2, 0); + rkf_set_bits(blk, 80, 6, 3); + rkf_set_bits(blk, 112, 16, 0x1234); + + // TCDI + rkf_set_dir(dump, 1, RKF_AID_TCDI, 0x000); + rkf_set_dir(dump, RKF_T_SEC_PURSE, RKF_AID_TCPU, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TCEL, RKF_AID_TCEL, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TCEL + 1, RKF_AID_TCEL, RKF_PIX_CONT); + rkf_set_dir(dump, RKF_T_SEC_TCAS2, RKF_AID_TCAS2, 0x000); + rkf_set_dir(dump, RKF_T_SEC_TICKET, RKF_T_PROVIDER, 0x064); + rkf_set_dir(dump, RKF_T_SEC_TICKET + 1, RKF_T_PROVIDER, RKF_PIX_CONT); + + for (uint8_t b = 0; b < 3; b++) { + rkf_set_checksum(rkf_test_block(dump, RKF_TCDI_SECTOR, b)); + } + + // TCAS, both instances identical + uint8_t tcas[MFBLOCK_SIZE] = {0}; + rkf_set_bits(tcas, 0, 8, RKF_TCAS_IDENTIFIER); + rkf_set_bits(tcas, 8, 6, 2); + rkf_set_bits(tcas, 14 + (2 * RKF_T_SEC_PURSE), 2, 2); + rkf_set_bits(tcas, 14 + (2 * RKF_T_SEC_TICKET), 2, 1); + rkf_set_bits(tcas, 46, 8, RKF_T_TXN); + rkf_set_bits(tcas, 54, 4, 4); + rkf_set_bits(tcas, 58, 4, 0); + rkf_set_bits(tcas, 94, 2, 0); + rkf_set_bits(tcas, 96, 6, 3); + rkf_set_bits(tcas, 112, 16, 0xBEEF); + memcpy(rkf_test_block(dump, 0, RKF_TCAS_BLOCK), tcas, MFBLOCK_SIZE); + memcpy(rkf_test_block(dump, RKF_T_SEC_TCAS2, 0), tcas, MFBLOCK_SIZE); + + // TCPU static and both dynamic blocks + blk = rkf_test_block(dump, RKF_T_SEC_PURSE, 0); + rkf_set_bits(blk, 0, 8, RKF_ID_TCPU_STATIC); + rkf_set_bits(blk, 8, 6, 2); + rkf_set_bits(blk, 14, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 26, 32, RKF_T_PURSE_SERIAL); + rkf_set_bits(blk, 58, 14, 8000); + rkf_set_bits(blk, 72, 4, 0); + rkf_set_bits(blk, 76, 24, 1000); + rkf_set_bits(blk, 100, 24, 20000); + + for (uint8_t b = 1; b <= 2; b++) { + blk = rkf_test_block(dump, RKF_T_SEC_PURSE, b); + rkf_set_bits(blk, 0, 16, 0x0100 + b); + rkf_set_bits(blk, 16, 14, RKF_T_VALID_END); + rkf_set_bits(blk, 30, 24, (uint32_t)(RKF_T_PURSE_VALUE) & 0xFFFFFF); + rkf_set_bits(blk, 54, 8, 0x01); + rkf_set_bits(blk, 62, 20, RKF_T_DEPOSIT); + rkf_set_bits(blk, 82, 2, 1); + rkf_set_bits(blk, 112, 16, 0xABCD); + } + + // TCEL, one charge record in slot 4 + blk = rkf_test_block(dump, RKF_T_SEC_TCEL + 1, 1); + rkf_set_bits(blk, 0, 8, RKF_ID_TCEL_RECORD); + rkf_set_bits(blk, 8, 14, 10000); + rkf_set_bits(blk, 22, 16, (13u << 11) | (45u << 5) | 15u); + rkf_set_bits(blk, 38, 12, RKF_T_PROVIDER); + rkf_set_bits(blk, 50, 16, 0x0042); + rkf_set_bits(blk, 66, 24, 987654); + rkf_set_bits(blk, 90, 6, 0x08); + rkf_set_bits(blk, 96, 24, 5000); + rkf_set_checksum(blk); + + // A ticket. The static element spans blocks 0 and 1 because its customer + // number crosses the checksum byte of block 0; the dynamic element then has + // to start at the next block boundary and is closed by the MAC group. + blk = rkf_test_block(dump, RKF_T_SEC_TICKET, 0); + rkf_run_set_bits(blk, 0, 8, RKF_ID_TCTI_HEADER); + rkf_run_set_bits(blk, 8, 6, 2); + rkf_run_set_bits(blk, 14, 8, RKF_ID_MANDATORY); + rkf_run_set_bits(blk, 22, 12, RKF_T_PROVIDER); + rkf_run_set_bits(blk, 34, 12, 0x064); + rkf_run_set_bits(blk, 46, 16, 0x0042); + rkf_run_set_bits(blk, 62, 32, RKF_T_TICKET_SERIAL); + rkf_run_set_bits(blk, 94, 8, 0x01); + rkf_run_set_bits(blk, 102, 8, RKF_ID_CUSTOMER); + rkf_run_set_bits(blk, 110, 34, RKF_T_CUSTOMER); + + rkf_run_set_bits(blk, 240, 8, RKF_ID_DYN_SINGLE); + rkf_run_set_bits(blk, 248, 8, RKF_ID_TCTI_PERIOD); + rkf_run_set_bits(blk, 256, 14, 10000); + rkf_run_set_bits(blk, 270, 16, (6u << 11) | (30u << 5)); + rkf_run_set_bits(blk, 286, 14, 10001); + rkf_run_set_bits(blk, 300, 16, (23u << 11) | (59u << 5) | 29u); + rkf_run_set_bits(blk, 316, 8, RKF_ID_MAC); + rkf_run_set_bits(blk, 324, 2, 0); + rkf_run_set_bits(blk, 326, 6, 3); + rkf_set_bits(rkf_test_block(dump, RKF_T_SEC_TICKET, 2), 112, 16, 0x5AA5); +} + +static bool rkf_check(const char *what, uint64_t got, uint64_t want) { + bool ok = (got == want); + PrintAndLogEx(INFO, " %-24s %12llu ( %s )", what, (unsigned long long)got, + ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +static bool rkf_check_str(const char *what, const char *got, const char *want) { + bool ok = (strcmp(got, want) == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", what, got, ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +int rkf_selftest(void) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Testing RKF travel card decode"); + + uint8_t dump[MIFARE_1K_MAX_BYTES]; + rkf_build_selftest_card(dump); + + if (is_valid_rkf_card(dump, sizeof(dump)) == false) { + PrintAndLogEx(FAILED, " card not recognised ( " _RED_("fail") " )"); + return PM3_ESOFT; + } + + bool ok = true; + char buf[40]; + + const uint8_t *cmi = rkf_block(dump, sizeof(dump), 0, RKF_CMI_BLOCK); + ok &= rkf_check("card serial", rkf_bits(cmi, 0, 32), RKF_T_CSN); + ok &= rkf_check("check byte", rkf_bits(cmi, 32, 8), + (uint64_t)(cmi[0] ^ cmi[1] ^ cmi[2] ^ cmi[3])); + + rkf_tcci_t tcci; + rkf_read_tcci(rkf_block(dump, sizeof(dump), 0, RKF_TCCI_BLOCK), &tcci); + ok &= rkf_check("card provider", tcci.card_provider, RKF_T_PROVIDER); + ok &= rkf_check("currency unit", tcci.currency_unit, RKF_T_CURRENCY); + + rkf_date_str(tcci.validity_end, buf, sizeof(buf)); + ok &= rkf_check_str("valid until", buf, "2026-12-31"); + + rkf_currency_str(tcci.currency_unit, buf, sizeof(buf)); + ok &= rkf_check_str("currency", buf, "SEK, main unit"); + + rkf_tcas_t tcas1, tcas2; + rkf_read_tcas(rkf_block(dump, sizeof(dump), 0, RKF_TCAS_BLOCK), &tcas1); + rkf_read_tcas(rkf_block(dump, sizeof(dump), RKF_T_SEC_TCAS2, 0), &tcas2); + ok &= rkf_check("tcas identifier", tcas1.identifier, RKF_TCAS_IDENTIFIER); + ok &= rkf_check("tcas transaction no", tcas1.transaction_no, RKF_T_TXN); + ok &= rkf_check("tcas event record", tcas1.event_log_record, 4); + ok &= rkf_check("tcas purse status", tcas1.sector_status[RKF_T_SEC_PURSE], 2); + ok &= rkf_check("tcas instances equal", (memcmp(&tcas1, &tcas2, sizeof(tcas1)) == 0), 1); + + uint16_t aid[RKF_SECTORS], pix[RKF_SECTORS]; + rkf_read_tcdi(dump, sizeof(dump), aid, pix); + ok &= rkf_check("dir sector 1 aid", aid[1], RKF_AID_TCDI); + ok &= rkf_check("dir purse aid", aid[RKF_T_SEC_PURSE], RKF_AID_TCPU); + ok &= rkf_check("dir event log aid", aid[RKF_T_SEC_TCEL], RKF_AID_TCEL); + ok &= rkf_check("dir continuation pix", pix[RKF_T_SEC_TCEL + 1], RKF_PIX_CONT); + ok &= rkf_check("dir ticket aid", aid[RKF_T_SEC_TICKET], RKF_T_PROVIDER); + + const uint8_t *purse = rkf_block(dump, sizeof(dump), RKF_T_SEC_PURSE, 0); + ok &= rkf_check("purse serial", rkf_bits(purse, 26, 32), RKF_T_PURSE_SERIAL); + + const uint8_t *dyn = rkf_block(dump, sizeof(dump), RKF_T_SEC_PURSE, 2); + int32_t value = rkf_signed(rkf_bits(dyn, 30, 24), 24); + ok &= rkf_check("purse value negative", (value == RKF_T_PURSE_VALUE), 1); + rkf_money_str(value, tcci.currency_unit, buf, sizeof(buf)); + ok &= rkf_check_str("purse value", buf, "-12345 SEK"); + ok &= rkf_check("purse deposit", rkf_bits(dyn, 62, 20), RKF_T_DEPOSIT); + + const uint8_t *ev = rkf_block(dump, sizeof(dump), RKF_T_SEC_TCEL + 1, 1); + ok &= rkf_check("event identifier", rkf_bits(ev, 0, 8), RKF_ID_TCEL_RECORD); + ok &= rkf_check("event code", rkf_bits(ev, 90, 6), 0x08); + ok &= rkf_check("event device txn", rkf_bits(ev, 66, 24), 987654); + ok &= rkf_check("event checksum", rkf_checksum_ok(ev), 1); + ok &= rkf_check("directory checksum", rkf_checksum_ok(rkf_block(dump, sizeof(dump), RKF_TCDI_SECTOR, 0)), 1); + + // RKF-0022 7.7.1 "standard CRC-8" is CRC-8/MIFARE-MAD: a block of 15 zero + // bytes checksums to 0B, as seen on real cards + uint8_t zeros[MFBLOCK_SIZE] = {0}; + zeros[MFBLOCK_SIZE - 1] = 0x0B; + ok &= rkf_check("crc8 of 15 zero bytes", rkf_checksum_ok(zeros), 1); + rkf_time_str((uint16_t)rkf_bits(ev, 22, 16), buf, sizeof(buf)); + ok &= rkf_check_str("event time", buf, "13:45:30"); + + // The customer number of the ticket crosses the block boundary, stepping + // over the checksum byte of block 0 + rkf_run_t run = { .dump = dump, .dumplen = sizeof(dump), .sector = RKF_T_SEC_TICKET, .nblocks = 6 }; + ok &= rkf_check("ticket header id", rkf_run_bits(&run, 0, 8), RKF_ID_TCTI_HEADER); + ok &= rkf_check("ticket serial", rkf_run_bits(&run, 62, 32), RKF_T_TICKET_SERIAL); + ok &= rkf_check("ticket customer no", rkf_run_bits(&run, 110, 34), RKF_T_CUSTOMER); + ok &= rkf_check("dynamic element id", rkf_run_bits(&run, 240, 8), RKF_ID_DYN_SINGLE); + ok &= rkf_check("ticket validity id", rkf_run_bits(&run, 248, 8), RKF_ID_TCTI_PERIOD); + ok &= rkf_check("ticket mac id", rkf_run_bits(&run, 316, 8), RKF_ID_MAC); + + rkf_date_str((uint16_t)rkf_run_bits(&run, 256, 14), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid from", buf, "2024-05-19"); + rkf_time_str((uint16_t)rkf_run_bits(&run, 270, 16), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid from", buf, "06:30:00"); + rkf_date_str((uint16_t)rkf_run_bits(&run, 286, 14), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid to", buf, "2024-05-20"); + rkf_time_str((uint16_t)rkf_run_bits(&run, 300, 16), buf, sizeof(buf)); + ok &= rkf_check_str("ticket valid to", buf, "23:59:58"); + ok &= rkf_check("ticket mac value", + rkf_bits(rkf_block(dump, sizeof(dump), RKF_T_SEC_TICKET, 2), 112, 16), 0x5AA5); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Decoding the self test card"); + rkf_parser_parse(dump, sizeof(dump)); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "RKF self test ( %s )", ok ? _GREEN_("ok") : _RED_("fail")); + return ok ? PM3_SUCCESS : PM3_ESOFT; +} diff --git a/client/src/parsers/parserkf.h b/client/src/parsers/parserkf.h new file mode 100644 index 000000000..deb352d52 --- /dev/null +++ b/client/src/parsers/parserkf.h @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// RKF travel card parser for MIFARE Classic dumps +// +// Resekortsforeningen i Norden, "RKF Type CL-1", the Nordic public transport +// travel card on MIFARE Classic 1K. Layout per RKF-0022 1.0 and RKF-0023 2.00. +//----------------------------------------------------------------------------- + +#ifndef PARSERKF_H__ +#define PARSERKF_H__ + +#include "common.h" + +// TCAS: Travel Card Applications Status, identifier of the first instance, +// always in block 2 of sector 0 +#define RKF_TCAS_IDENTIFIER 0xA0 + +// True when sector 0 carries a travel card applications status block and either +// the card information block or the directory corroborates it +bool is_valid_rkf_card(const uint8_t *dump, size_t dumplen); + +// Decode the support layer and walk the directory, printing every application +// object the specification pins down +int rkf_parser_parse(const uint8_t *dump, size_t dumplen); + +// Build a card from the encoder and check the decoder reads it back +int rkf_selftest(void); + +#endif From 54e004e252ade1ee39b7dfc9975197f67b6d4ef9 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 22 Sep 2026 11:19:24 +0200 Subject: [PATCH 10/11] hf mfdes: add NORTIC travel card parser NORTIC (Norwegian Ticketing Interoperable Concept) is the Norwegian national public transport card, on DESFire since 2008 and specified by Statens vegvesen, now Jernbanedirektoratet, in Handbok V821. Decodes the card issuer header, file 0C of AID 578000. That file is free to read, so the parser produces output on any Norwegian card without key material: country code, format, choice bitmap, card serial number, validity end date, application owner company, retailer organisation and card key version. The transport application, AID 578001, is listed by file with its role and the key it needs, and any file that was read is dumped as hex. Its field layouts are in Handbok V821 Del 18, which has no download link, and every file needs read key 7, which is not public. Nothing there is guessed at. NORTIC is EN 1545 and packs fields most significant bit first, which is the opposite of the RKF Type CL-1 layout in parserkf.c where RKF-0022 7.4.1 numbers bits from the least significant end. Reading a NORTIC header the RKF way gives country code 144 instead of 578, so the self test asserts that as a negative control. Verified field by field against the published card issuer header, every field matching its documented value, including the validity date 6938 decoding to 2015-12-31. 'hf mfdes view --selftest' runs the checks, including a round trip through an encoder. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + client/CMakeLists.txt | 1 + client/Makefile | 1 + client/experimental_lib/CMakeLists.txt | 1 + client/src/cmdhfmfdes.c | 24 +- client/src/parsers/parsenortic.c | 422 +++++++++++++++++++++++++ client/src/parsers/parsenortic.h | 48 +++ 7 files changed, 494 insertions(+), 4 deletions(-) create mode 100644 client/src/parsers/parsenortic.c create mode 100644 client/src/parsers/parsenortic.h diff --git a/CHANGELOG.md b/CHANGELOG.md index efb62414c..10939019e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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 view` - decodes the card issuer header of NORTIC travel cards, the Norwegian national public transport card (@iceman1001) - Added `hf mf view` - decodes RKF travel cards, the Nordic public transport card (Resekortsföreningen i Norden) on MIFARE Classic (@iceman1001) - Fixed `hf 14a info` now correctly handles NAK when receiving RATS (@iceman1001) - Fixed `hf mfu restore` to support Ultralight AES (@iceman1001) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 4d8808073..6ccb4d98a 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -515,6 +515,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/parsers/parsemykey.c ${PM3_ROOT}/client/src/parsers/parseproac.c ${PM3_ROOT}/client/src/parsers/parserkf.c + ${PM3_ROOT}/client/src/parsers/parsenortic.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c diff --git a/client/Makefile b/client/Makefile index 24a471d61..d1be39d84 100644 --- a/client/Makefile +++ b/client/Makefile @@ -913,6 +913,7 @@ SRCS = mifare/aiddesfire.c \ parsers/parsemykey.c \ parsers/parseproac.c \ parsers/parserkf.c \ + parsers/parsenortic.c \ parsers/hrtparser/hrtparser.c \ pm3.c \ pm3_binlib.c \ diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index a7a6d0001..d90053bef 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -442,6 +442,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/parsers/parsemykey.c ${PM3_ROOT}/client/src/parsers/parseproac.c ${PM3_ROOT}/client/src/parsers/parserkf.c + ${PM3_ROOT}/client/src/parsers/parsenortic.c ${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c ${PM3_ROOT}/client/src/pla.c ${PM3_ROOT}/client/src/preferences.c diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index da872445b..71b094573 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -35,6 +35,7 @@ #include "crypto/duoxcrypto.h" #include "protocols.h" #include "parsers/parsehrt.h" +#include "parsers/parsenortic.h" #include "cmdtrace.h" #include "cliparser.h" #include "iso7816/apduinfo.h" // APDU manipulation / errorcodes @@ -9691,12 +9692,14 @@ 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"); + "hf mfdes view -f hf-mfdes-01020304050607-dump.json\n" + "hf mfdes view --selftest"); void *argtable[] = { arg_param_begin, - arg_str1("f", "file", "", "Filename of dump"), + arg_str0("f", "file", "", "Filename of dump"), arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "selftest", "Run the dump parsers self tests and exit"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -9705,8 +9708,18 @@ static int CmdHF14ADesView(const char *Cmd) { char filename[FILE_PATH_SIZE] = {0}; CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); bool verbose = arg_get_lit(ctx, 2); + bool selftest = arg_get_lit(ctx, 3); CLIParserFree(ctx); + if (selftest) { + return nortic_selftest(); + } + + if (fnlen == 0) { + PrintAndLogEx(ERR, "Specify a filename with `-f` or run `--selftest`"); + return PM3_EINVARG; + } + desfire_dump_t *dump = calloc(1, sizeof(desfire_dump_t)); if (dump == NULL) { PrintAndLogEx(ERR, "Failed to allocate memory"); @@ -9776,6 +9789,10 @@ static int CmdHF14ADesView(const char *Cmd) { DesfireViewPrintApp(&dump->app[i]); } + if (is_valid_nortic_card(dump)) { + (void)nortic_parser_parse(dump); + } + if (verbose) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "Loaded `" _YELLOW_("%s") "`", filename); @@ -11053,8 +11070,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_str0(NULL, "dfname", "", "Certificate application DF name (1-16 bytes)"), // 14 arg_str0(NULL, "fid", "", "Certificate file ID (1 byte)"), // 15 arg_lit0(NULL, "no-auth", "Read certificate file without authentication"), // 16 - arg_strn(NULL, "ca", "", 0, MFDES_VERIFYCERT_MAX_CAS, - "CA input, or `skip` to skip certificate signature validation. Repeat --ca for multiple entries"), // 17 + arg_strn(NULL, "ca", "", 0, MFDES_VERIFYCERT_MAX_CAS, "CA input, or `skip` to skip validation"), // 17 arg_str0(NULL, "keyaid", "", "Key application ID (default: cert app)"), // 18 arg_str0(NULL, "keyisoid", "", "Key application ISO DF ID (2 bytes)"), // 19 arg_str0(NULL, "keydfname", "", "Key application DF name (default: cert app)"), // 20 diff --git a/client/src/parsers/parsenortic.c b/client/src/parsers/parsenortic.c new file mode 100644 index 000000000..fed9c16e2 --- /dev/null +++ b/client/src/parsers/parsenortic.c @@ -0,0 +1,422 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// NORTIC travel card parser for MIFARE DESFire dumps +//----------------------------------------------------------------------------- + +#include "parsenortic.h" + +#include // snprintf +#include + +#include "commonutil.h" // ARRAYLEN +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow + +#define NORTIC_CI_HEADER_SIZE 16 + +// Days from 1970-01-01 to the EN 1545 date epoch of 1997-01-01 +#define NORTIC_DAYS_TO_1997 9862 + +#define NORTIC_LABEL "%-22s" + +//----------------------------------------------------------------------------- +// Bit access +// +// EN 1545 packs fields most significant bit first, so bit 0 is the top bit of +// byte 0. This is the opposite of the RKF Type CL-1 layout in parserkf.c, where +// RKF-0022 section 7.4.1 numbers bits from the least significant end. +//----------------------------------------------------------------------------- + +static uint64_t nortic_bits(const uint8_t *buf, uint16_t off, uint8_t len) { + uint64_t v = 0; + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + v = (v << 1) | ((buf[b >> 3] >> (7 - (b & 7))) & 1); + } + return v; +} + +static void nortic_set_bits(uint8_t *buf, uint16_t off, uint8_t len, uint64_t v) { + for (uint8_t k = 0; k < len; k++) { + uint16_t b = off + k; + uint8_t bit = (v >> (len - 1 - k)) & 1; + if (bit) { + buf[b >> 3] |= (uint8_t)(1 << (7 - (b & 7))); + } else { + buf[b >> 3] &= (uint8_t)~(1 << (7 - (b & 7))); + } + } +} + +//----------------------------------------------------------------------------- +// Card issuer header, file 0C of AID 578000, 16 bytes +//----------------------------------------------------------------------------- + +#define NORTIC_OFF_COUNTRY 0 +#define NORTIC_OFF_FORMAT 10 +#define NORTIC_OFF_CHOICE 30 +#define NORTIC_OFF_SERIAL 32 +#define NORTIC_OFF_VALIDITY 64 +#define NORTIC_OFF_OWNER 78 +#define NORTIC_OFF_RETAILER 98 +#define NORTIC_OFF_KEYVERSION 118 +#define NORTIC_OFF_UNUSED 122 + +typedef struct { + uint16_t country; + uint32_t format; + uint8_t choice; + uint32_t serial; + uint16_t validity_end; + uint32_t owner; + uint32_t retailer; + uint8_t key_version; + uint8_t unused; +} nortic_ci_t; + +static void nortic_read_ci(const uint8_t *d, nortic_ci_t *c) { + c->country = (uint16_t)nortic_bits(d, NORTIC_OFF_COUNTRY, 10); + c->format = (uint32_t)nortic_bits(d, NORTIC_OFF_FORMAT, 20); + c->choice = (uint8_t)nortic_bits(d, NORTIC_OFF_CHOICE, 2); + c->serial = (uint32_t)nortic_bits(d, NORTIC_OFF_SERIAL, 32); + c->validity_end = (uint16_t)nortic_bits(d, NORTIC_OFF_VALIDITY, 14); + c->owner = (uint32_t)nortic_bits(d, NORTIC_OFF_OWNER, 20); + c->retailer = (uint32_t)nortic_bits(d, NORTIC_OFF_RETAILER, 20); + c->key_version = (uint8_t)nortic_bits(d, NORTIC_OFF_KEYVERSION, 4); + c->unused = (uint8_t)nortic_bits(d, NORTIC_OFF_UNUSED, 6); +} + +//----------------------------------------------------------------------------- +// Value decoding +//----------------------------------------------------------------------------- + +static void nortic_civil_from_days(int32_t z, int *year, unsigned *month, unsigned *day) { + z += 719468; + int32_t era = ((z >= 0) ? z : (z - 146096)) / 146097; + uint32_t doe = (uint32_t)(z - (era * 146097)); + uint32_t yoe = (doe - (doe / 1460) + (doe / 36524) - (doe / 146096)) / 365; + int32_t y = (int32_t)yoe + (era * 400); + uint32_t doy = doe - ((365 * yoe) + (yoe / 4) - (yoe / 100)); + uint32_t mp = ((5 * doy) + 2) / 153; + *day = doy - (((153 * mp) + 2) / 5) + 1; + *month = (mp < 10) ? (mp + 3) : (mp - 9); + *year = y + ((*month <= 2) ? 1 : 0); +} + +// EN 1545 date, day 0 is 1 January 1997 +static void nortic_date_str(uint16_t v, char *out, size_t outlen) { + int y; + unsigned m, d; + nortic_civil_from_days((int32_t)v + NORTIC_DAYS_TO_1997, &y, &m, &d); + snprintf(out, outlen, "%04d-%02u-%02u", y, m, d); +} + +static const char *nortic_country_name(uint16_t code) { + switch (code) { + case 208: + return "Denmark"; + case 246: + return "Finland"; + case 578: + return "Norway"; + case 752: + return "Sweden"; + default: + return NULL; + } +} + +// The choice bitmap says which optional card identifier is present +static const char *nortic_choice_name(uint8_t choice) { + switch (choice) { + case 0: + return "none"; + case 1: + return "RFU"; + case 2: + return "cardIDNumber32bits"; + default: + return "RFU"; + } +} + +//----------------------------------------------------------------------------- +// Transport application file map +//----------------------------------------------------------------------------- + +static const struct { + uint8_t fid; + const char *name; + const char *note; +} nortic_transport_files[] = { + {0x01, "Product Retailer", "384 bytes, written with key 4"}, + {0x02, "Service Provider", "128 bytes, written with key 6"}, + {0x03, "Special Event", "288 bytes, written with key 6"}, + {0x04, "Stored Value", "value file, written with key 5"}, + {0x05, "General Event Log", "cyclic, 36 bytes per record"}, + {0x06, "SV Reload Log", "cyclic, 32 bytes per record"}, + {0x0A, "Environment", "32 bytes, written with key 2"}, + {0x0C, "Card Holder", "32 bytes, written with key 3"}, +}; + +static const char *nortic_transport_file_name(uint8_t fid) { + for (size_t i = 0; i < ARRAYLEN(nortic_transport_files); i++) { + if (nortic_transport_files[i].fid == fid) { + return nortic_transport_files[i].name; + } + } + return NULL; +} + +//----------------------------------------------------------------------------- +// Lookup helpers +//----------------------------------------------------------------------------- + +static const desfire_dump_app_t *nortic_find_app(const desfire_dump_t *dump, uint32_t aid) { + if (dump == NULL) { + return NULL; + } + for (uint8_t i = 0; i < dump->appcount && i < DESFIRE_MAX_APP_COUNT; i++) { + if (dump->app[i].aid == aid) { + return &dump->app[i]; + } + } + return NULL; +} + +static const desfire_dump_file_t *nortic_find_file(const desfire_dump_app_t *app, uint8_t fid) { + if (app == NULL) { + return NULL; + } + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + if (app->files[i].num == fid) { + return &app->files[i]; + } + } + return NULL; +} + +//----------------------------------------------------------------------------- +// Detection +//----------------------------------------------------------------------------- + +bool is_valid_nortic_card(const desfire_dump_t *dump) { + return (nortic_find_app(dump, NORTIC_AID_CARD_ISSUER) != NULL); +} + +//----------------------------------------------------------------------------- +// Printing +//----------------------------------------------------------------------------- + +static void nortic_print_ci(const nortic_ci_t *c) { + + char buf[32]; + const char *country = nortic_country_name(c->country); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Card issuer header") " --- AID %06X file %02X", + NORTIC_AID_CARD_ISSUER, NORTIC_FID_CI_HEADER); + + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( %s )", "Country code", c->country, + country ? country : "unknown"); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Format", c->format); + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( %s )", "Choice bitmap", c->choice, + nortic_choice_name(c->choice)); + PrintAndLogEx(INFO, NORTIC_LABEL " " _YELLOW_("%u") " ( %08X )", "Card serial number", + c->serial, c->serial); + + nortic_date_str(c->validity_end, buf, sizeof(buf)); + PrintAndLogEx(INFO, NORTIC_LABEL " " _YELLOW_("%s") " ( day %u )", "Valid until", buf, + c->validity_end); + + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "App owner company", c->owner); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Retailer organisation", c->retailer); + PrintAndLogEx(INFO, NORTIC_LABEL " %u", "Card key version", c->key_version); + + if (c->unused != 0) { + PrintAndLogEx(INFO, NORTIC_LABEL " %u ( " _YELLOW_("expected 0") " )", "Unused bits", c->unused); + } +} + +static void nortic_print_transport(const desfire_dump_app_t *app) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Transport application") " --- AID %06X", NORTIC_AID_TRANSPORT); + + if (app == NULL) { + PrintAndLogEx(INFO, "Not present on this card"); + return; + } + + PrintAndLogEx(INFO, " fid | file | read"); + PrintAndLogEx(INFO, "-----+---------------------+---------------------------------------"); + + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + const desfire_dump_file_t *f = &app->files[i]; + const char *name = nortic_transport_file_name(f->num); + + PrintAndLogEx(INFO, " %02X | %-19s | %s", f->num, name ? name : "unknown", + f->read_ok ? _GREEN_("read") : _YELLOW_("not read, needs key 7")); + } + + PrintAndLogEx(INFO, "-----+---------------------+---------------------------------------"); + + // Contents are only printed as hex. The field layouts of these files are in + // Handbok V821 Del 18, which is not published. + for (uint8_t i = 0; i < app->filecount && i < DESFIRE_MAX_FILE_COUNT; i++) { + + const desfire_dump_file_t *f = &app->files[i]; + if (f->read_ok == false || f->data == NULL || f->datalen == 0) { + continue; + } + + const char *name = nortic_transport_file_name(f->num); + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "file %02X %s %u bytes " _YELLOW_("not decoded"), f->num, + name ? name : "unknown", f->datalen); + + for (uint32_t off = 0; off < f->datalen; off += 16) { + uint32_t n = (f->datalen - off < 16) ? (f->datalen - off) : 16; + PrintAndLogEx(INFO, " %04X %s", off, sprint_hex_inrow(f->data + off, n)); + } + } +} + +//----------------------------------------------------------------------------- +// Top level +//----------------------------------------------------------------------------- + +int nortic_parser_parse(const desfire_dump_t *dump) { + + const desfire_dump_app_t *ci = nortic_find_app(dump, NORTIC_AID_CARD_ISSUER); + if (ci == NULL) { + return PM3_EINVARG; + } + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("NORTIC travel card") " ------------------------"); + PrintAndLogEx(INFO, "Norwegian Ticketing Interoperable Concept"); + + const desfire_dump_file_t *f = nortic_find_file(ci, NORTIC_FID_CI_HEADER); + + if (f == NULL) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header (file %02X) is not in this dump", + NORTIC_FID_CI_HEADER); + } else if (f->read_ok == false || f->data == NULL) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header was not read. It needs no key, so retry the dump"); + } else if (f->datalen < NORTIC_CI_HEADER_SIZE) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Card issuer header is %u bytes, expected %u", f->datalen, + NORTIC_CI_HEADER_SIZE); + } else { + nortic_ci_t c; + nortic_read_ci(f->data, &c); + nortic_print_ci(&c); + + if (c.country != NORTIC_COUNTRY_NORWAY) { + PrintAndLogEx(INFO, ""); + PrintAndLogEx(WARNING, "Country code is %u, not %u. The layout below is the", + c.country, NORTIC_COUNTRY_NORWAY); + PrintAndLogEx(WARNING, "Norwegian one and may not hold."); + } + } + + nortic_print_transport(nortic_find_app(dump, NORTIC_AID_TRANSPORT)); + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Transport application layouts are in Handbok V821 Del 18, which is"); + PrintAndLogEx(INFO, "not published. Its files also need read key 7, which is not public"); + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// Self test +//----------------------------------------------------------------------------- + +static bool nortic_check(const char *what, uint64_t got, uint64_t want) { + bool ok = (got == want); + PrintAndLogEx(INFO, " %-24s %12llu ( %s )", what, (unsigned long long)got, + ok ? _GREEN_("ok") : _RED_("fail")); + return ok; +} + +int nortic_selftest(void) { + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "Testing NORTIC card issuer header decode"); + + // The published card issuer header, with the serial number filled in where + // the capture redacted it + const uint8_t ci[NORTIC_CI_HEADER_SIZE] = { + 0x90, 0x80, 0x00, 0x02, 0xAA, 0xBB, 0xCC, 0xDD, + 0x6C, 0x68, 0x00, 0x28, 0x00, 0x02, 0x80, 0x40 + }; + + nortic_ci_t c; + nortic_read_ci(ci, &c); + + bool ok = true; + ok &= nortic_check("country code", c.country, NORTIC_COUNTRY_NORWAY); + ok &= nortic_check("format", c.format, 0); + ok &= nortic_check("choice bitmap", c.choice, 2); + ok &= nortic_check("card serial number", c.serial, 0xAABBCCDD); + ok &= nortic_check("validity end day", c.validity_end, 6938); + ok &= nortic_check("app owner company", c.owner, 160); + ok &= nortic_check("retailer organisation", c.retailer, 160); + ok &= nortic_check("card key version", c.key_version, 1); + ok &= nortic_check("unused bits", c.unused, 0); + + char buf[32]; + nortic_date_str(c.validity_end, buf, sizeof(buf)); + bool dok = (strcmp(buf, "2015-12-31") == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", "validity end date", buf, + dok ? _GREEN_("ok") : _RED_("fail")); + ok &= dok; + + // EN 1545 is most significant bit first. Reading it the RKF way gives 144, + // so a wrong bit order cannot pass unnoticed. + uint64_t lsb = 0; + for (uint8_t k = 0; k < 10; k++) { + if ((ci[k >> 3] >> (k & 7)) & 1) { + lsb |= (uint64_t)1 << k; + } + } + ok &= nortic_check("lsb first would give", lsb, 144); + + // round trip through the encoder + uint8_t enc[NORTIC_CI_HEADER_SIZE] = {0}; + nortic_set_bits(enc, NORTIC_OFF_COUNTRY, 10, c.country); + nortic_set_bits(enc, NORTIC_OFF_FORMAT, 20, c.format); + nortic_set_bits(enc, NORTIC_OFF_CHOICE, 2, c.choice); + nortic_set_bits(enc, NORTIC_OFF_SERIAL, 32, c.serial); + nortic_set_bits(enc, NORTIC_OFF_VALIDITY, 14, c.validity_end); + nortic_set_bits(enc, NORTIC_OFF_OWNER, 20, c.owner); + nortic_set_bits(enc, NORTIC_OFF_RETAILER, 20, c.retailer); + nortic_set_bits(enc, NORTIC_OFF_KEYVERSION, 4, c.key_version); + nortic_set_bits(enc, NORTIC_OFF_UNUSED, 6, c.unused); + + bool rok = (memcmp(enc, ci, NORTIC_CI_HEADER_SIZE) == 0); + PrintAndLogEx(INFO, " %-24s %12s ( %s )", "re-encodes to the same 16 B", + sprint_hex_inrow(enc, 4), rok ? _GREEN_("ok") : _RED_("fail")); + ok &= rok; + + PrintAndLogEx(INFO, ""); + PrintAndLogEx(INFO, "NORTIC self test ( %s )", ok ? _GREEN_("ok") : _RED_("fail")); + return ok ? PM3_SUCCESS : PM3_ESOFT; +} diff --git a/client/src/parsers/parsenortic.h b/client/src/parsers/parsenortic.h new file mode 100644 index 000000000..a321d1511 --- /dev/null +++ b/client/src/parsers/parsenortic.h @@ -0,0 +1,48 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// NORTIC travel card parser for MIFARE DESFire dumps +// +// Norwegian Ticketing Interoperable Concept, the national public transport card +// specified by Statens vegvesen and now Jernbanedirektoratet, Handbok V821. +// Fields are EN 1545 coded. +//----------------------------------------------------------------------------- + +#ifndef PARSENORTIC_H__ +#define PARSENORTIC_H__ + +#include "common.h" +#include "fileutils.h" // desfire_dump_t + +// Card Issuer application. Its header file is free to read, no key needed. +#define NORTIC_AID_CARD_ISSUER 0x578000 +#define NORTIC_FID_CI_HEADER 0x0C + +// Transport application. Every file needs the read key, number 7. +#define NORTIC_AID_TRANSPORT 0x578001 + +// ISO 3166 numeric code carried in the first field of the card issuer header +#define NORTIC_COUNTRY_NORWAY 578 + +// True when the dump carries the NORTIC card issuer application +bool is_valid_nortic_card(const desfire_dump_t *dump); + +// Decode the card issuer header and name what the transport application holds +int nortic_parser_parse(const desfire_dump_t *dump); + +// Check the decoder against the published card issuer header +int nortic_selftest(void); + +#endif From 0aa6c96c22124d313066499f2ae11ea385bdcf51 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 22 Sep 2026 11:20:15 +0200 Subject: [PATCH 11/11] hook in parser --- client/src/cmdhfmf.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 21203793b..80972625b 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -898,6 +898,10 @@ static int mf_view_dump(uint8_t *dump, size_t bytes_read, uint16_t block_cnt, bo (void)proac_parser_parse(dump, bytes_read); } + if (is_valid_rkf_card(dump, bytes_read)) { + (void)rkf_parser_parse(dump, bytes_read); + } + return PM3_SUCCESS; } @@ -8557,7 +8561,11 @@ static int CmdHF14AMfView(const char *Cmd) { if (res != PM3_SUCCESS) { return res; } - return hexact_selftest(); + res = hexact_selftest(); + if (res != PM3_SUCCESS) { + return res; + } + return rkf_selftest(); } if (fnlen == 0) {