transit parsers: shared helpers and per technology dispatch

Adds parsers/parsetransit.{c,h}: MSB/LSB bit readers and writers, date,
datetime and money formatting, one print style for every card system,
and a dispatcher per technology that runs each registered parser whose
detection matches. The tables start empty, card systems follow.

Hook points, each run on data the command already has:
  hf mf view / hf mf dump / hf mf autopwn   -> transit_mfc_parse
  hf mfdes view / hf mfdes dump             -> transit_mfdes_parse
  hf mfu view / hf mfu dump                 -> transit_mfu_parse
  hf 14b view / dump (SRx)                  -> transit_st25tb_parse
  hf felica dump                            -> transit_felica_parse
  hf calypso info                           -> transit_calypso_parse

hf calypso info now also reads the contract list, counters, contracts
and events by SFI for the Calypso parsers. Self tests hang off the same
commands via --selftest; hf mfu view gains that flag, hf felica dump and
hf calypso info gain it and become always available so it runs offline,
with an explicit device check for the real path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
iceman1001andClaude Opus 5.5 committed 2026-11-10 10:05:13 +07:00
1 parent a9a5b1ac51
commit ea599c4a71
11 files changed
+804 -9

No files matched your search

+1
View File
@@ -517,6 +517,7 @@ set (TARGET_SOURCES
${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/parsetransit.c
${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c
${PM3_ROOT}/client/src/pla.c
${PM3_ROOT}/client/src/preferences.c
+1
View File
@@ -924,6 +924,7 @@ SRCS = mifare/aiddesfire.c \
parsers/parseproac.c \
parsers/parserkf.c \
parsers/parsenortic.c \
parsers/parsetransit.c \
parsers/hrtparser/hrtparser.c \
pm3.c \
pm3_binlib.c \
+1
View File
@@ -444,6 +444,7 @@ set (TARGET_SOURCES
${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/parsetransit.c
${PM3_ROOT}/client/src/parsers/hrtparser/hrtparser.c
${PM3_ROOT}/client/src/pla.c
${PM3_ROOT}/client/src/preferences.c
+8 -1
View File
@@ -41,6 +41,7 @@
#include "atrs.h" // atqbToEmulatedAtr
#include "pla.h" // ECP parsing
#include "parsers/parsemykey.h" // MyKey / COGES
#include "parsers/parsetransit.h" // transit card parsers
#define MAX_14B_TIMEOUT_MS (4949U)
@@ -937,6 +938,8 @@ static void sr_view_dump(uint8_t *data, size_t len, const uint8_t *uid, bool den
if (is_valid_mykey_card(data, len)) {
(void)mykey_parser_parse(data, len, uid);
}
(void)transit_st25tb_parse(data, len, uid);
}
static void print_std_blocks(uint8_t *data, size_t len, const uint8_t *uid, uint8_t uidlen, bool dense_output) {
@@ -3362,7 +3365,11 @@ static int CmdHF14BView(const char *Cmd) {
CLIParserFree(ctx);
if (selftest) {
return mykey_selftest();
int res = mykey_selftest();
if (res != PM3_SUCCESS) {
return res;
}
return transit_st25tb_selftest();
}
if (fnlen == 0) {
+62 -2
View File
@@ -35,6 +35,7 @@
#include "fileutils.h"
#include "iso7816/apduinfo.h"
#include "iso7816/iso7816core.h"
#include "parsers/parsetransit.h" // transit card parsers
#include "protocols.h"
#include "ui.h"
#include "util.h"
@@ -2052,6 +2053,51 @@ static int calypso_read_ticketing_environment(uint8_t *env, size_t env_len, size
return calypso_read_ticketing_environment_file(env, env_len, read_len, sw);
}
static bool calypso_read_transit_record(uint8_t sfi, uint8_t record, transit_calypso_record_t *rec) {
size_t len = 0;
uint16_t sw = 0;
int res = calypso_read_sfi_record(sfi, record, 0, rec->data, sizeof(rec->data), &len, &sw);
if (res != PM3_SUCCESS || sw != ISO7816_OK || len == 0) {
rec->len = 0;
return false;
}
rec->len = (uint8_t)len;
return true;
}
// Contracts, events and counters for the transit parsers, by SFI in the selected application
static void calypso_run_transit_parsers(const calypso_select_result_t *selected, const uint8_t *env, size_t env_len) {
transit_calypso_card_t card;
memset(&card, 0, sizeof(card));
if (selected->parsed.has_serial) {
memcpy(card.serial, selected->parsed.serial, sizeof(card.serial));
card.has_serial = true;
}
card.env.len = (uint8_t)MIN(env_len, sizeof(card.env.data));
memcpy(card.env.data, env, card.env.len);
(void)calypso_read_transit_record(0x1E, 1, &card.contract_list);
(void)calypso_read_transit_record(0x19, 1, &card.counters);
// records are numbered from 1, a missing one ends the file
for (uint8_t i = 0; i < 4; i++) {
if (calypso_read_transit_record(0x09, i + 1, &card.contracts[i]) == false) {
break;
}
card.contract_count++;
}
for (uint8_t i = 0; i < TRANSIT_CALYPSO_MAX_EVENTS; i++) {
if (calypso_read_transit_record(0x08, i + 1, &card.events[i]) == false) {
break;
}
card.event_count++;
}
(void)transit_calypso_parse(&card);
}
static void calypso_dump_filename_add_serial(calypso_dump_filename_context_t *ctx, const calypso_select_result_t *selected) {
uint8_t serial[CALYPSO_SERIAL_LEN] = {0};
if (ctx == NULL || calypso_selection_profile_serial(selected, serial) == false) {
@@ -4774,12 +4820,14 @@ static int CmdHFCalypsoInfo(const char *Cmd) {
"Tag information for Calypso cards",
"hf calypso info\n"
"hf calypso info -v\n"
"hf calypso info --aid 315449432E494341");
"hf calypso info --aid 315449432E494341\n"
"hf calypso info --selftest");
void *argtable[] = {
arg_param_begin,
arg_str0(NULL, "aid", "<hex>", "Calypso application AID or AID prefix (5..16 bytes)"),
arg_lit0("v", "verbose", "verbose output"),
arg_lit0(NULL, "selftest", "Run the transit parsers self tests and exit"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
@@ -4788,11 +4836,22 @@ static int CmdHFCalypsoInfo(const char *Cmd) {
int user_aid_len = 0;
int parse_res = CLIParamHexToBuf(arg_get_str(ctx, 1), user_aid, sizeof(user_aid), &user_aid_len);
bool verbose = arg_get_lit(ctx, 2);
bool selftest = arg_get_lit(ctx, 3);
CLIParserFree(ctx);
if (parse_res != PM3_SUCCESS) {
return PM3_EINVARG;
}
if (selftest) {
return transit_calypso_selftest();
}
// listed as always available so the self test runs offline
if (IfPm3Iso14443() == false) {
PrintAndLogEx(WARNING, "Only offline mode is available, use `" _YELLOW_("--selftest") "`");
return PM3_ENOTTY;
}
if (user_aid_len > 0 && (user_aid_len < 5 || user_aid_len > CALYPSO_MAX_AID_LEN)) {
PrintAndLogEx(ERR, "AID length must be 5..16 bytes, got %d", user_aid_len);
return PM3_EINVARG;
@@ -4851,6 +4910,7 @@ static int CmdHFCalypsoInfo(const char *Cmd) {
res = calypso_read_ticketing_environment(ticket_env, sizeof(ticket_env), &ticket_env_len, &ticket_env_sw);
if (res == PM3_SUCCESS && ticket_env_sw == ISO7816_OK) {
calypso_print_ticketing_environment(ticket_env, ticket_env_len, verbose);
calypso_run_transit_parsers(&selected, ticket_env, ticket_env_len);
} else if (verbose) {
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, "Ticketing environment unavailable (%04X - %s)", ticket_env_sw, GetAPDUCodeDescription(ticket_env_sw >> 8, ticket_env_sw & 0xFF));
@@ -4863,7 +4923,7 @@ static int CmdHFCalypsoInfo(const char *Cmd) {
static command_t CommandTable[] = {
{"help", CmdHelp, AlwaysAvailable, "This help"},
{"info", CmdHFCalypsoInfo, IfPm3Iso14443, "Tag information"},
{"info", CmdHFCalypsoInfo, AlwaysAvailable, "Tag information"},
{"dump", CmdHFCalypsoDump, IfPm3Iso14443, "Dump nodes after application profile scan"},
{"probecmdcompat", CmdHFCalypsoProbe, IfPm3Iso14443, "Probe SELECT command compatibility"},
{"list", CmdHFCalypsoList, AlwaysAvailable, "List Calypso history"},
+72 -2
View File
@@ -39,6 +39,7 @@
#include "util_posix.h" // msleep, msclock
#include "jansson.h"
#include "jsonutils.h"
#include "parsers/parsetransit.h" // transit card parsers
#define FELICA_BLK_SIZE 16
@@ -5437,6 +5438,60 @@ static void felica_dump_systems_free(felica_dump_system_t *systems, size_t syste
}
}
// Hand the public service blocks to the transit parsers, blocks laid out by number
static void felica_dump_run_transit_parsers(const felica_dump_system_t *systems, size_t system_count) {
transit_felica_system_t tsys[FELICA_DISCOVERED_SYSTEM_MAX_COUNT];
memset(tsys, 0, sizeof(tsys));
size_t tcount = 0;
for (size_t i = 0; i < system_count && tcount < ARRAYLEN(tsys); i++) {
const felica_dump_system_t *sys = &systems[i];
transit_felica_service_t *svc = calloc(sys->node_count + 1, sizeof(transit_felica_service_t));
if (svc == NULL) {
break;
}
size_t n = 0;
for (size_t j = 0; j < sys->node_count; j++) {
const felica_dump_node_t *node = &sys->nodes[j];
if (node->type != FELICA_NODE_TYPE_SERVICE || node->block_count == 0) {
continue;
}
uint16_t blocks = 0;
for (size_t k = 0; k < node->block_count; k++) {
if (node->blocks[k].block_number >= blocks) {
blocks = node->blocks[k].block_number + 1;
}
}
uint8_t *buf = calloc(blocks, FELICA_BLK_SIZE);
if (buf == NULL) {
continue;
}
for (size_t k = 0; k < node->block_count; k++) {
memcpy(buf + (node->blocks[k].block_number * FELICA_BLK_SIZE), node->blocks[k].data, FELICA_BLK_SIZE);
}
svc[n].code = node->node_code_le;
svc[n].block_count = blocks;
svc[n].blocks = buf;
n++;
}
tsys[tcount].system_code = sys->system_code;
memcpy(tsys[tcount].idm, sys->idm, sizeof(tsys[tcount].idm));
tsys[tcount].service_count = n;
tsys[tcount].services = svc;
tcount++;
}
transit_felica_card_t card = { .system_count = tcount, .systems = tsys };
(void)transit_felica_parse(&card);
for (size_t i = 0; i < tcount; i++) {
for (size_t j = 0; j < tsys[i].service_count; j++) {
free((void *)tsys[i].services[j].blocks);
}
free((void *)tsys[i].services);
}
}
static felica_dump_node_t *felica_dump_system_add_node(felica_dump_system_t *system,
const felica_discovered_node_t *node) {
if (system == NULL || node == NULL) {
@@ -7196,7 +7251,8 @@ static int CmdHFFelicaDump(const char *Cmd) {
"hf felica dump\n"
"hf felica dump --retry 5\n"
"hf felica dump --idm 11100910C11BC407\n"
"hf felica dump -f my-felica-dump");
"hf felica dump -f my-felica-dump\n"
"hf felica dump --selftest");
void *argtable[] = {
arg_param_begin,
arg_lit0(NULL, "no-auth", "read public services"),
@@ -7204,6 +7260,7 @@ static int CmdHFFelicaDump(const char *Cmd) {
arg_str0(NULL, "idm", "<hex>", "use custom IDm"),
arg_str0("f", "file", "<fn>", "Specify a filename for JSON dump file"),
arg_lit0(NULL, "no-ic-optimizations", "attempt all commands even if the IC is known not to support them"),
arg_lit0(NULL, "selftest", "Run the transit parsers self tests and exit"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
@@ -7215,11 +7272,22 @@ static int CmdHFFelicaDump(const char *Cmd) {
int fnlen = 0;
CLIParamStrToBuf(arg_get_str(ctx, 4), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
bool no_ic_optimizations = arg_get_lit(ctx, 5);
bool selftest = arg_get_lit(ctx, 6);
CLIParserFree(ctx);
if (res) {
return PM3_EINVARG;
}
if (selftest) {
return transit_felica_selftest();
}
// listed as always available so the self test runs offline
if (IfPm3Felica() == false) {
PrintAndLogEx(WARNING, "Only offline mode is available, use `" _YELLOW_("--selftest") "`");
return PM3_ENOTTY;
}
// bool no_auth = arg_get_lit(ctx, 1);
const uint64_t dump_started_ms = msclock();
@@ -7298,6 +7366,8 @@ static int CmdHFFelicaDump(const char *Cmd) {
snprintf(filename, sizeof(filename), "hf-felica-%s-dump", sprint_hex_inrow(idm, sizeof(idm)));
}
felica_dump_run_transit_parsers(dump_systems, dump_system_count);
json_t *root = felica_dump_systems_json(dump_systems, dump_system_count, &dump_metadata);
if (root == NULL) {
felica_dump_systems_free(dump_systems, dump_system_count);
@@ -9565,7 +9635,7 @@ static command_t CommandTable[] = {
{"-----------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("FeliCa SEAC") " -----------------------"},
{"seacauth1", CmdHFFelicaSeacAuth1, IfPm3Felica, "FeliCa SEAC Authentication1"},
{"-----------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("FeliCa Standard") " -----------------------"},
{"dump", CmdHFFelicaDump, IfPm3Felica, "Wait for and try dumping FeliCa"},
{"dump", CmdHFFelicaDump, AlwaysAvailable, "Wait for and try dumping FeliCa"},
{"discnodes", CmdHFFelicaDiscoverNodes, IfPm3Felica, "discover Area Code and Service Code nodes."},
{"sim", CmdHFFelicaSim, IfPm3Felica, "Emulate FeliCa Standard from dump file"},
{"rqservice", CmdHFFelicaRequestService, IfPm3Felica, "verify the existence of Area and Service, and to acquire Key Version."},
+10 -1
View File
@@ -48,6 +48,7 @@
#include "parsers/parsehexact.h"
#include "parsers/parseproac.h"
#include "parsers/parserkf.h"
#include "parsers/parsetransit.h" // transit card parsers
#include "generator.h" // keygens.
#include "fpga.h"
#include "mifare/mifarehost.h"
@@ -914,6 +915,8 @@ static int mf_view_dump(uint8_t *dump, size_t bytes_read, uint16_t block_cnt, bo
(void)rkf_parser_parse(dump, bytes_read);
}
(void)transit_mfc_parse(dump, bytes_read);
return PM3_SUCCESS;
}
@@ -4046,6 +4049,8 @@ all_found:
free(fptr);
pm3_save_mf_dump(outfilename, dump, bytes, jsfCardMemory);
(void)transit_mfc_parse(dump, bytes);
free(dump);
out:
@@ -8770,7 +8775,11 @@ static int CmdHF14AMfView(const char *Cmd) {
if (res != PM3_SUCCESS) {
return res;
}
return rkf_selftest();
res = rkf_selftest();
if (res != PM3_SUCCESS) {
return res;
}
return transit_mfc_selftest();
}
if (fnlen == 0) {
+10 -1
View File
@@ -36,6 +36,7 @@
#include "protocols.h"
#include "parsers/parsehrt.h"
#include "parsers/parsenortic.h"
#include "parsers/parsetransit.h" // transit card parsers
#include "cmdtrace.h"
#include "cliparser.h"
#include "iso7816/apduinfo.h" // APDU manipulation / errorcodes
@@ -9058,6 +9059,8 @@ static int CmdHF14ADesDump(const char *Cmd) {
DropField();
(void)transit_mfdes_parse(dump);
if (nosave) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "Called with no save option");
@@ -9863,7 +9866,11 @@ static int CmdHF14ADesView(const char *Cmd) {
CLIParserFree(ctx);
if (selftest) {
return nortic_selftest();
int res = nortic_selftest();
if (res != PM3_SUCCESS) {
return res;
}
return transit_mfdes_selftest();
}
if (fnlen == 0) {
@@ -9944,6 +9951,8 @@ static int CmdHF14ADesView(const char *Cmd) {
(void)nortic_parser_parse(dump);
}
(void)transit_mfdes_parse(dump);
if (verbose) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "Loaded `" _YELLOW_("%s") "`", filename);
+21 -2
View File
@@ -41,6 +41,7 @@
#include "crc16.h"
#include "crypto/originality.h"
#include "util.h"
#include "parsers/parsetransit.h" // transit card parsers
#include <pthread.h>
#include <vec/vec.h>
@@ -3934,6 +3935,10 @@ static int CmdHF14AMfUDump(const char *Cmd) {
PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread")"`");
}
if (start_page == 0) {
(void)transit_mfu_parse(dump_file_data.data, pages * MFU_BLOCK_SIZE);
}
if (nosave) {
PrintAndLogEx(INFO, "Called with no save option");
PrintAndLogEx(NORMAL, "");
@@ -8574,13 +8579,15 @@ static int CmdHF14AMfuView(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "hf mfu view",
"Print a MIFARE Ultralight/NTAG dump file (bin/eml/json)",
"hf mfu view -f hf-mfu-01020304-dump.bin"
"hf mfu view -f hf-mfu-01020304-dump.bin\n"
"hf mfu view --selftest"
);
void *argtable[] = {
arg_param_begin,
arg_str1("f", "file", "<fn>", "Specify a filename for dump file"),
arg_str0("f", "file", "<fn>", "Specify a filename for dump file"),
arg_lit0("v", "verbose", "Verbose output"),
arg_lit0("z", "dense", "dense dump output style"),
arg_lit0(NULL, "selftest", "Run the dump parsers self tests and exit"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, false);
@@ -8589,8 +8596,18 @@ static int CmdHF14AMfuView(const char *Cmd) {
CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
bool verbose = arg_get_lit(ctx, 2);
bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3));
bool selftest = arg_get_lit(ctx, 4);
CLIParserFree(ctx);
if (selftest) {
return transit_mfu_selftest();
}
if (fnlen == 0) {
PrintAndLogEx(ERR, "Specify a filename with `-f` or run `--selftest`");
return PM3_EINVARG;
}
// read dump file
uint8_t *dump = NULL;
size_t bytes_read = 0;
@@ -8631,6 +8648,8 @@ static int CmdHF14AMfuView(const char *Cmd) {
PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread")"`");
}
(void)transit_mfu_parse(p->data, block_cnt * MFU_BLOCK_SIZE);
free(dump);
return PM3_SUCCESS;
}
+449
View File
@@ -0,0 +1,449 @@
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// Transit card parsers, shared helpers and per technology dispatch
//-----------------------------------------------------------------------------
#include "parsetransit.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "ui.h" // PrintAndLogEx
#define TRANSIT_LABEL_WIDTH 17
//-----------------------------------------------------------------------------
// Bit and byte access
//-----------------------------------------------------------------------------
uint64_t transit_bits_be(const uint8_t *buf, size_t buflen, size_t off, uint8_t n) {
uint64_t v = 0;
for (uint8_t k = 0; k < n && k < 64; k++) {
size_t b = off + k;
uint8_t bit = 0;
if (buf != NULL && (b >> 3) < buflen) {
bit = (buf[b >> 3] >> (7 - (b & 7))) & 1;
}
v = (v << 1) | bit;
}
return v;
}
uint64_t transit_bits_le(const uint8_t *buf, size_t buflen, size_t off, uint8_t n) {
uint64_t v = 0;
for (uint8_t k = 0; k < n && k < 64; k++) {
size_t b = off + k;
if (buf != NULL && (b >> 3) < buflen && ((buf[b >> 3] >> (b & 7)) & 1)) {
v |= (uint64_t)1 << k;
}
}
return v;
}
void transit_set_bits_be(uint8_t *buf, size_t buflen, size_t off, uint8_t n, uint64_t v) {
for (uint8_t k = 0; k < n && k < 64; k++) {
size_t b = off + k;
if ((b >> 3) >= buflen) {
return;
}
uint8_t mask = (uint8_t)(1 << (7 - (b & 7)));
if ((v >> (n - 1 - k)) & 1) {
buf[b >> 3] |= mask;
} else {
buf[b >> 3] &= (uint8_t)~mask;
}
}
}
void transit_set_bits_le(uint8_t *buf, size_t buflen, size_t off, uint8_t n, uint64_t v) {
for (uint8_t k = 0; k < n && k < 64; k++) {
size_t b = off + k;
if ((b >> 3) >= buflen) {
return;
}
uint8_t mask = (uint8_t)(1 << (b & 7));
if ((v >> k) & 1) {
buf[b >> 3] |= mask;
} else {
buf[b >> 3] &= (uint8_t)~mask;
}
}
}
int64_t transit_sign_extend(uint64_t v, uint8_t n) {
if (n == 0 || n >= 64) {
return (int64_t)v;
}
uint64_t m = (uint64_t)1 << (n - 1);
v &= ((uint64_t)1 << n) - 1;
return (int64_t)((v ^ m) - m);
}
bool transit_is_zero(const uint8_t *buf, size_t len) {
for (size_t i = 0; i < len; i++) {
if (buf[i]) {
return false;
}
}
return true;
}
int transit_bcd(uint8_t b) {
if ((b >> 4) > 9 || (b & 0x0F) > 9) {
return -1;
}
return ((b >> 4) * 10) + (b & 0x0F);
}
//-----------------------------------------------------------------------------
// Formatting
//-----------------------------------------------------------------------------
// Howard Hinnant's days_from_civil and its inverse
void transit_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);
}
int32_t transit_days_from_civil(int year, unsigned month, unsigned day) {
int32_t y = year - ((month <= 2) ? 1 : 0);
int32_t era = ((y >= 0) ? y : (y - 399)) / 400;
uint32_t yoe = (uint32_t)(y - (era * 400));
uint32_t doy = ((153 * ((month > 2) ? (month - 3) : (month + 9))) + 2) / 5 + day - 1;
uint32_t doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy;
return (era * 146097) + (int32_t)doe - 719468;
}
void transit_date_str(char *out, size_t outlen, int32_t days) {
int y;
unsigned m, d;
transit_civil_from_days(days, &y, &m, &d);
snprintf(out, outlen, "%04d-%02u-%02u", y, m, d);
}
void transit_datetime_str(char *out, size_t outlen, int64_t secs) {
int64_t days = secs / 86400;
int64_t rem = secs % 86400;
if (rem < 0) {
rem += 86400;
days--;
}
int y;
unsigned m, d;
transit_civil_from_days((int32_t)days, &y, &m, &d);
snprintf(out, outlen, "%04d-%02u-%02u %02u:%02u:%02u", y, m, d,
(unsigned)(rem / 3600), (unsigned)((rem / 60) % 60), (unsigned)(rem % 60));
}
void transit_money_str(char *out, size_t outlen, int64_t minor, uint8_t decimals, const char *currency) {
const char *sign = (minor < 0) ? "-" : "";
uint64_t a = (minor < 0) ? (uint64_t)(-(minor + 1)) + 1 : (uint64_t)minor;
const char *cur = (currency != NULL) ? currency : "";
const char *sep = (cur[0] != '\0') ? " " : "";
if (decimals == 0) {
snprintf(out, outlen, "%s%" PRIu64 "%s%s", sign, a, sep, cur);
return;
}
uint64_t div = 1;
for (uint8_t i = 0; i < decimals; i++) {
div *= 10;
}
snprintf(out, outlen, "%s%" PRIu64 ".%0*" PRIu64 "%s%s", sign, a / div, (int)decimals, a % div, sep, cur);
}
//-----------------------------------------------------------------------------
// Printing
//-----------------------------------------------------------------------------
void transit_print_header(const char *title) {
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "--- " _CYAN_("%s") " ---------------------------", title);
}
void transit_print_kv(const char *label, const char *fmt, ...) {
char lbl[TRANSIT_LABEL_WIDTH + 1];
size_t n = strlen(label);
if (n > TRANSIT_LABEL_WIDTH) {
n = TRANSIT_LABEL_WIDTH;
}
memcpy(lbl, label, n);
memset(lbl + n, '.', TRANSIT_LABEL_WIDTH - n);
lbl[TRANSIT_LABEL_WIDTH] = '\0';
char val[256];
va_list args;
va_start(args, fmt);
vsnprintf(val, sizeof(val), fmt, args);
va_end(args);
PrintAndLogEx(SUCCESS, "%s %s", lbl, val);
}
bool transit_check(const char *what, uint64_t got, uint64_t want) {
bool ok = (got == want);
PrintAndLogEx(INFO, " %-28s %14" PRIu64 " ( %s )", what, got, ok ? _GREEN_("ok") : _RED_("fail"));
return ok;
}
bool transit_check_str(const char *what, const char *got, const char *want) {
bool ok = (got != NULL && want != NULL && strcmp(got, want) == 0);
PrintAndLogEx(INFO, " %-28s %14s ( %s )", what, got ? got : "(null)", ok ? _GREEN_("ok") : _RED_("fail"));
return ok;
}
int transit_selftest_result(const char *name, bool ok) {
PrintAndLogEx(INFO, "%s selftest ( %s )", name, ok ? _GREEN_("ok") : _RED_("fail"));
return ok ? PM3_SUCCESS : PM3_ESOFT;
}
//-----------------------------------------------------------------------------
// FeliCa and Calypso lookups
//-----------------------------------------------------------------------------
const transit_felica_system_t *transit_felica_find_system(const transit_felica_card_t *card, uint16_t system_code) {
if (card == NULL || card->systems == NULL) {
return NULL;
}
for (size_t i = 0; i < card->system_count; i++) {
if (card->systems[i].system_code == system_code) {
return &card->systems[i];
}
}
return NULL;
}
const transit_felica_service_t *transit_felica_find_service(const transit_felica_system_t *sys, uint16_t code) {
if (sys == NULL || sys->services == NULL) {
return NULL;
}
for (size_t i = 0; i < sys->service_count; i++) {
if (sys->services[i].code == code && sys->services[i].blocks != NULL) {
return &sys->services[i];
}
}
return NULL;
}
static int transit_helpers_selftest(void) {
PrintAndLogEx(INFO, "");
PrintAndLogEx(INFO, "Testing transit helpers");
const uint8_t b[] = { 0xA5, 0x3C };
bool ok = true;
ok &= transit_check("bits be 4..11", transit_bits_be(b, sizeof(b), 4, 8), 0x53);
ok &= transit_check("bits le 4..11", transit_bits_le(b, sizeof(b), 4, 8), 0xCA);
ok &= transit_check("bits be past end", transit_bits_be(b, sizeof(b), 12, 8), 0xC0);
ok &= transit_check("sign extend 0xFFF/12", (uint64_t)transit_sign_extend(0xFFF, 12), (uint64_t) -1);
uint8_t w[2] = {0};
transit_set_bits_be(w, sizeof(w), 4, 8, 0x53);
transit_set_bits_le(w, sizeof(w), 4, 4, 0xA);
transit_set_bits_be(w, sizeof(w), 12, 4, 0xC);
ok &= transit_check("set bits round trip", ((uint64_t)w[0] << 8) | w[1], 0xA53C);
char s[40];
transit_date_str(s, sizeof(s), TRANSIT_DAYS_TO_1997);
ok &= transit_check_str("EN 1545 epoch", s, "1997-01-01");
ok &= transit_check("days from civil 2000-03-01", (uint64_t)transit_days_from_civil(2000, 3, 1), 11017);
transit_datetime_str(s, sizeof(s), 951782400 + 3723);
ok &= transit_check_str("datetime", s, "2000-02-29 01:02:03");
transit_money_str(s, sizeof(s), -1234, 2, "AUD");
ok &= transit_check_str("money -12.34", s, "-12.34 AUD");
transit_money_str(s, sizeof(s), 5, 2, NULL);
ok &= transit_check_str("money 0.05", s, "0.05");
transit_money_str(s, sizeof(s), 210, 0, "JPY");
ok &= transit_check_str("money JPY", s, "210 JPY");
return transit_selftest_result("Transit helpers", ok);
}
//-----------------------------------------------------------------------------
// Dispatch tables, one row per card system, NULL name ends a table
//-----------------------------------------------------------------------------
typedef struct {
const char *name;
bool (*detect)(const uint8_t *dump, size_t dumplen);
int (*parse)(const uint8_t *dump, size_t dumplen);
int (*selftest)(void);
} transit_buf_parser_t;
typedef struct {
const char *name;
bool (*detect)(const desfire_dump_t *dump);
int (*parse)(const desfire_dump_t *dump);
int (*selftest)(void);
} transit_mfdes_parser_t;
typedef struct {
const char *name;
bool (*detect)(const uint8_t *data, size_t datalen, const uint8_t *uid);
int (*parse)(const uint8_t *data, size_t datalen, const uint8_t *uid);
int (*selftest)(void);
} transit_st25tb_parser_t;
typedef struct {
const char *name;
bool (*detect)(const transit_felica_card_t *card);
int (*parse)(const transit_felica_card_t *card);
int (*selftest)(void);
} transit_felica_parser_t;
typedef struct {
const char *name;
bool (*detect)(const transit_calypso_card_t *card);
int (*parse)(const transit_calypso_card_t *card);
int (*selftest)(void);
} transit_calypso_parser_t;
static const transit_buf_parser_t mfc_parsers[] = {
{NULL, NULL, NULL, NULL}
};
static const transit_mfdes_parser_t mfdes_parsers[] = {
{NULL, NULL, NULL, NULL}
};
static const transit_buf_parser_t mfu_parsers[] = {
{NULL, NULL, NULL, NULL}
};
static const transit_st25tb_parser_t st25tb_parsers[] = {
{NULL, NULL, NULL, NULL}
};
static const transit_felica_parser_t felica_parsers[] = {
{NULL, NULL, NULL, NULL}
};
static const transit_calypso_parser_t calypso_parsers[] = {
{NULL, NULL, NULL, NULL}
};
// Runs every self test of a table, all of them even after a failure
#define TRANSIT_RUN_SELFTESTS(table) do { \
bool ok = (transit_helpers_selftest() == PM3_SUCCESS); \
int cnt = 0; \
for (size_t i = 0; table[i].name != NULL; i++) { \
if (table[i].selftest != NULL) { \
ok &= (table[i].selftest() == PM3_SUCCESS); \
cnt++; \
} \
} \
PrintAndLogEx(INFO, ""); \
PrintAndLogEx(INFO, "%d transit parser selftest(s)", cnt); \
return transit_selftest_result("Transit", ok); \
} while (0)
int transit_mfc_parse(const uint8_t *dump, size_t dumplen) {
int hits = 0;
for (size_t i = 0; dump != NULL && mfc_parsers[i].name != NULL; i++) {
if (mfc_parsers[i].detect(dump, dumplen)) {
(void)mfc_parsers[i].parse(dump, dumplen);
hits++;
}
}
return hits;
}
int transit_mfc_selftest(void) {
TRANSIT_RUN_SELFTESTS(mfc_parsers);
}
int transit_mfdes_parse(const desfire_dump_t *dump) {
int hits = 0;
for (size_t i = 0; dump != NULL && mfdes_parsers[i].name != NULL; i++) {
if (mfdes_parsers[i].detect(dump)) {
(void)mfdes_parsers[i].parse(dump);
hits++;
}
}
return hits;
}
int transit_mfdes_selftest(void) {
TRANSIT_RUN_SELFTESTS(mfdes_parsers);
}
int transit_mfu_parse(const uint8_t *data, size_t datalen) {
int hits = 0;
for (size_t i = 0; data != NULL && mfu_parsers[i].name != NULL; i++) {
if (mfu_parsers[i].detect(data, datalen)) {
(void)mfu_parsers[i].parse(data, datalen);
hits++;
}
}
return hits;
}
int transit_mfu_selftest(void) {
TRANSIT_RUN_SELFTESTS(mfu_parsers);
}
int transit_st25tb_parse(const uint8_t *data, size_t datalen, const uint8_t *uid) {
int hits = 0;
for (size_t i = 0; data != NULL && st25tb_parsers[i].name != NULL; i++) {
if (st25tb_parsers[i].detect(data, datalen, uid)) {
(void)st25tb_parsers[i].parse(data, datalen, uid);
hits++;
}
}
return hits;
}
int transit_st25tb_selftest(void) {
TRANSIT_RUN_SELFTESTS(st25tb_parsers);
}
int transit_felica_parse(const transit_felica_card_t *card) {
int hits = 0;
for (size_t i = 0; card != NULL && felica_parsers[i].name != NULL; i++) {
if (felica_parsers[i].detect(card)) {
(void)felica_parsers[i].parse(card);
hits++;
}
}
return hits;
}
int transit_felica_selftest(void) {
TRANSIT_RUN_SELFTESTS(felica_parsers);
}
int transit_calypso_parse(const transit_calypso_card_t *card) {
int hits = 0;
for (size_t i = 0; card != NULL && calypso_parsers[i].name != NULL; i++) {
if (calypso_parsers[i].detect(card)) {
(void)calypso_parsers[i].parse(card);
hits++;
}
}
return hits;
}
int transit_calypso_selftest(void) {
TRANSIT_RUN_SELFTESTS(calypso_parsers);
}
+169
View File
@@ -0,0 +1,169 @@
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// Transit card parsers, shared helpers and per technology dispatch
//
// Each card system lives in its own parsers/parse<name>.c and exposes
// is_valid_<name>_card(), <name>_parser_parse() and <name>_selftest() over
// plain byte buffers. The dispatchers below run every parser of a technology
// whose detection matches.
//-----------------------------------------------------------------------------
#ifndef PARSETRANSIT_H__
#define PARSETRANSIT_H__
#include "common.h"
#include "fileutils.h" // desfire_dump_t
#include "ui.h" // PM3_PRINTF_FORMAT
// Days from 1970-01-01 to common transit epochs
#define TRANSIT_DAYS_TO_1980 3652
#define TRANSIT_DAYS_TO_1990 7305
#define TRANSIT_DAYS_TO_1997 9862 // EN 1545
#define TRANSIT_DAYS_TO_2000 10957
//-----------------------------------------------------------------------------
// Bit and byte access, out of range bits read as zero
//-----------------------------------------------------------------------------
// Most significant bit first, bit 0 is the top bit of byte 0 (EN 1545)
uint64_t transit_bits_be(const uint8_t *buf, size_t buflen, size_t off, uint8_t n);
// Least significant bit first, bit 0 is the low bit of byte 0
uint64_t transit_bits_le(const uint8_t *buf, size_t buflen, size_t off, uint8_t n);
// Writers for building self test vectors
void transit_set_bits_be(uint8_t *buf, size_t buflen, size_t off, uint8_t n, uint64_t v);
void transit_set_bits_le(uint8_t *buf, size_t buflen, size_t off, uint8_t n, uint64_t v);
// Sign extend the low n bits of v
int64_t transit_sign_extend(uint64_t v, uint8_t n);
bool transit_is_zero(const uint8_t *buf, size_t len);
// Two digit BCD byte, -1 when a nibble is not a digit
int transit_bcd(uint8_t b);
//-----------------------------------------------------------------------------
// Formatting, all write a NUL terminated string into out
//-----------------------------------------------------------------------------
void transit_civil_from_days(int32_t days, int *year, unsigned *month, unsigned *day);
int32_t transit_days_from_civil(int year, unsigned month, unsigned day);
// days since 1970-01-01 -> YYYY-MM-DD
void transit_date_str(char *out, size_t outlen, int32_t days);
// seconds since 1970-01-01 -> YYYY-MM-DD HH:MM:SS, no time zone applied
void transit_datetime_str(char *out, size_t outlen, int64_t secs);
// minor units -> "-12.34 AUD", decimals is the currency exponent
void transit_money_str(char *out, size_t outlen, int64_t minor, uint8_t decimals, const char *currency);
//-----------------------------------------------------------------------------
// Printing in one style for every card system
//-----------------------------------------------------------------------------
// Blank line and a cyan section banner
void transit_print_header(const char *title);
// "Label........... value", value formatted printf style
void transit_print_kv(const char *label, const char *fmt, ...) __attribute__((format(PM3_PRINTF_FORMAT, 2, 3)));
// Self test helper, prints and returns got == want
bool transit_check(const char *what, uint64_t got, uint64_t want);
bool transit_check_str(const char *what, const char *got, const char *want);
// Final self test line, returns PM3_SUCCESS or PM3_ESOFT
int transit_selftest_result(const char *name, bool ok);
//-----------------------------------------------------------------------------
// FeliCa view handed to the parsers. Service codes are as the specs write
// them, e.g. 0x090F for the Suica history.
//-----------------------------------------------------------------------------
typedef struct {
uint16_t code;
uint16_t block_count;
const uint8_t *blocks; // block_count * 16 bytes, block 0 first
} transit_felica_service_t;
typedef struct {
uint16_t system_code;
uint8_t idm[8];
size_t service_count;
const transit_felica_service_t *services;
} transit_felica_system_t;
typedef struct {
size_t system_count;
const transit_felica_system_t *systems;
} transit_felica_card_t;
const transit_felica_system_t *transit_felica_find_system(const transit_felica_card_t *card, uint16_t system_code);
const transit_felica_service_t *transit_felica_find_service(const transit_felica_system_t *sys, uint16_t code);
//-----------------------------------------------------------------------------
// Calypso view handed to the parsers, records as read from the card
//-----------------------------------------------------------------------------
#define TRANSIT_CALYPSO_REC_LEN 29
#define TRANSIT_CALYPSO_MAX_CONTRACTS 8
#define TRANSIT_CALYPSO_MAX_EVENTS 3
typedef struct {
uint8_t len; // 0 when not read
uint8_t data[TRANSIT_CALYPSO_REC_LEN];
} transit_calypso_record_t;
typedef struct {
uint8_t serial[8];
bool has_serial;
transit_calypso_record_t env; // SFI 07, 2001
transit_calypso_record_t contract_list; // SFI 1E, 2050
transit_calypso_record_t counters; // SFI 19, 2069
uint8_t contract_count;
transit_calypso_record_t contracts[TRANSIT_CALYPSO_MAX_CONTRACTS]; // SFI 09, 2020
uint8_t event_count;
transit_calypso_record_t events[TRANSIT_CALYPSO_MAX_EVENTS]; // SFI 08, 2010
} transit_calypso_card_t;
//-----------------------------------------------------------------------------
// Dispatch per technology, return how many parsers matched
//-----------------------------------------------------------------------------
// MIFARE Classic, dump starts at block 0
int transit_mfc_parse(const uint8_t *dump, size_t dumplen);
int transit_mfc_selftest(void);
// MIFARE DESFire, as written by `hf mfdes dump`
int transit_mfdes_parse(const desfire_dump_t *dump);
int transit_mfdes_selftest(void);
// MIFARE Ultralight / NTAG, page 0 first, no dump prefix
int transit_mfu_parse(const uint8_t *data, size_t datalen);
int transit_mfu_selftest(void);
// ST25TB / SRx, block 0 first, uid as printed by `hf 14b view`
int transit_st25tb_parse(const uint8_t *data, size_t datalen, const uint8_t *uid);
int transit_st25tb_selftest(void);
int transit_felica_parse(const transit_felica_card_t *card);
int transit_felica_selftest(void);
int transit_calypso_parse(const transit_calypso_card_t *card);
int transit_calypso_selftest(void);
#endif