From ef23d014eb59a791903acced47cd660b138fd52c Mon Sep 17 00:00:00 2001 From: ry4000 <154689120+ry4000@users.noreply.github.com> Date: Wed, 9 Sep 2026 16:15:03 +1000 Subject: [PATCH 01/26] R&Y: Updated `MEGACASH` AID in `aid_desfire.json` # Updates 1. Updated `MEGACASH` vendor name from `Bank Mega` to `PT Bank Mega Tbk` *which is the vendor's full name*. -r&y. Signed-off-by: ry4000 <154689120+ry4000@users.noreply.github.com> --- client/resources/aid_desfire.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index a166e32ca..3b4f180c0 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -873,9 +873,9 @@ }, { "AID": "008800", - "Vendor": "Bank Mega", + "Vendor": "PT Bank Mega Tbk", "Country": "ID", - "Name": "MegaCash", + "Name": "MEGACASH", "Description": "Indonesian stored-value card // FIDs 01: Card Identification; 02: Stored Value; 03: Transaction Records", "Type": "payment system" }, From 186c72eefd079f07e84c51883adef357ed1f2d39 Mon Sep 17 00:00:00 2001 From: "Young, Nathen C" Date: Wed, 9 Sep 2026 08:57:09 -0700 Subject: [PATCH 02/26] fix(usb): terminate packet-aligned CDC transfers with ZLP Send a synchronous zero-length packet after CDC responses whose length is an exact multiple of the endpoint packet size, preventing oversized host reads from remaining pending. --- common_arm/usb/usb_cdc_at32.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/common_arm/usb/usb_cdc_at32.c b/common_arm/usb/usb_cdc_at32.c index f4a6087c2..2c6b7d4b8 100644 --- a/common_arm/usb/usb_cdc_at32.c +++ b/common_arm/usb/usb_cdc_at32.c @@ -508,6 +508,21 @@ int usb_write(const uint8_t *data, const size_t len) { // Have a cup of tea? } + // End a packet-aligned CDC transfer with a zero-length packet. Without + // this short packet, a host read larger than this reply can remain pending. + // Use the low-level sender: usb_write() intentionally rejects len == 0. + // Keep this in the synchronous path, not the asynchronous sample stream. + if ((len % USBD_CDC_IN_MAXPACKET_SIZE) == 0) { + if (usb_vcp_send_data(udev, (uint8_t *) data, 0) != SUCCESS) { + return PM3_EIO; + } + while (pcdc->g_tx_completed != 1) { + if (usb_check() == false) { + return PM3_EIO; + } + } + } + return PM3_SUCCESS; } From 253e0d148a1c4ab0b8ff45cb4640318654861bc2 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 02:55:16 +0200 Subject: [PATCH 03/26] hf emrtd info - did not identify and mapped OID for algorithms in PACE. Now we keep a list and pretty print it --- CHANGELOG.md | 1 + client/src/cmdhfemrtd.c | 51 ++++++- client/src/emrtd/emrtd_pace.c | 237 ++++++++++++++++++++++++++---- client/src/emrtd/emrtd_pace.h | 32 +++- client/src/emrtd/emrtd_pacetest.c | 62 ++++++++ 5 files changed, 343 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b655b3876..f36f364a6 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 emrtd info` - now correctly pretty print algos (@iceman1001) - Fixed `trace list -t topaz` - now parses topaz reader frames up to 16 bytes (@iceman1001) - Fixed `hw bwm` - doc and comment references still named the flat `hw bwmsetcap`/`bwmcharge`/`bwmautooff` commands from before the subgroup move (@xilni) - Added TA1=96 support via pwm to sim module `sim024.bin` - v4.66 (@antiklesys) diff --git a/client/src/cmdhfemrtd.c b/client/src/cmdhfemrtd.c index 04d0748b0..cfde4c9df 100644 --- a/client/src/cmdhfemrtd.c +++ b/client/src/cmdhfemrtd.c @@ -2468,15 +2468,28 @@ static void emrtd_print_cardaccess(const emrtd_cardaccess_t *ca) { PrintAndLogEx(SUCCESS, ""); } - if (info->alg != NULL) { - PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("%s"), info->alg->name); - } else { - PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("unknown") " ( OID %s )", - sprint_hex_inrow((uint8_t *)info->oid, info->oidlen)); + char oidstr[64] = { 0x00 }; + emrtd_oid_to_str(info->oid, info->oidlen, oidstr, sizeof(oidstr)); + if (oidstr[0] == 0x00) { + snprintf(oidstr, sizeof(oidstr), "%s", sprint_hex_inrow((uint8_t *)info->oid, info->oidlen)); } + bool is_pace = ((info->kind == EMRTD_SI_PACE) || (info->kind == EMRTD_SI_PACE_DP)); + + if (info->protocol != NULL) { + PrintAndLogEx(SUCCESS, "%s " _YELLOW_("%s"), + is_pace ? "PACE algorithm..........." : "Protocol.................", + info->protocol); + } else { + PrintAndLogEx(SUCCESS, "Protocol................. " _YELLOW_("unknown")); + } + + PrintAndLogEx(SUCCESS, "OID...................... %s", oidstr); + if (info->version != 0) { - PrintAndLogEx(SUCCESS, "PACE version............. " _YELLOW_("%u"), info->version); + PrintAndLogEx(SUCCESS, "%s " _YELLOW_("%u"), + is_pace ? "PACE version............." : "Version..................", + info->version); } if (info->has_param) { @@ -2488,18 +2501,40 @@ static void emrtd_print_cardaccess(const emrtd_cardaccess_t *ca) { } } + if (info->has_key_id) { + PrintAndLogEx(SUCCESS, "Key id................... " _YELLOW_("%u"), info->key_id); + } + if (info->supported) { PrintAndLogEx(SUCCESS, "Supported by this client. " _GREEN_("yes") "%s", ((int)i == ca->best) ? _GREEN_(" (selected)") : ""); - } else { + } else if (is_pace) { PrintAndLogEx(SUCCESS, "Supported by this client. " _YELLOW_("no") " ( %s )", (info->reason != NULL) ? info->reason : "unsupported"); + } else { + // not a PACE protocol at all, "unsupported PACE algorithm" would be + // the wrong thing to tell the user + PrintAndLogEx(SUCCESS, "Note..................... %s", + (info->reason != NULL) ? info->reason : "not a PACE protocol"); } } if (ca->best < 0) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(WARNING, "None of the offered PACE algorithms is supported by this client"); + + bool pace_offered = false; + for (size_t i = 0; i < ca->count; i++) { + if (ca->infos[i].kind == EMRTD_SI_PACE) { + pace_offered = true; + break; + } + } + + if (pace_offered) { + PrintAndLogEx(WARNING, "None of the offered PACE algorithms is supported by this client"); + } else { + PrintAndLogEx(WARNING, "EF_CardAccess does not offer any PACE algorithm"); + } } } diff --git a/client/src/emrtd/emrtd_pace.c b/client/src/emrtd/emrtd_pace.c index 1af3a8674..b8aa44047 100644 --- a/client/src/emrtd/emrtd_pace.c +++ b/client/src/emrtd/emrtd_pace.c @@ -26,6 +26,8 @@ #include #include #include +#include +#include #include "crypto/libpcrypto.h" // sha1hash, sha256hash, des_encrypt/decrypt, pcrypto_rng_* #include "ui.h" // PrintAndLogEx @@ -86,6 +88,140 @@ static const emrtd_pacesdp_t pacesdp_table[] = { {32, NULL, 0, false, MBEDTLS_ECP_DP_NONE} }; +// Every SecurityInfo protocol that can share EF_CardAccess / EF_DG14 with the +// PACE entries. EF_CardAccess is a SET OF SecurityInfo, so a document lists +// everything it supports in there, not just PACE. TR-03110 part 3, A.1.1.1 +// covers the 0.4.0.127.0.7.2.2.x arcs, ICAO 9303-11 section 9 the ICAO ones. +// We do not run these protocols, but naming them beats printing a hex blob. +typedef struct { + size_t oidlen; + uint8_t oid[EMRTD_PACE_OID_MAXLEN]; + emrtd_si_t kind; + const char *name; +} emrtd_secinfo_t; + +// 0.4.0.127.0.7.2.2, bsi-de protocols(2) smartcard(2) +#define BSI_SC 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02 +// 2.23.136.1.1, id-icao-mrtd-security +#define ICAO_SEC 0x67, 0x81, 0x08, 0x01, 0x01 + +static const emrtd_secinfo_t secinfo_table[] = { +// len oid kind name + // id-PK, ChipAuthenticationPublicKeyInfo + {8, {BSI_SC, 0x01}, EMRTD_SI_PK, "Chip Authentication Public Key"}, + {9, {BSI_SC, 0x01, 0x01}, EMRTD_SI_PK, "Chip Authentication Public Key, DH"}, + {9, {BSI_SC, 0x01, 0x02}, EMRTD_SI_PK, "Chip Authentication Public Key, ECDH"}, + + // id-TA, TerminalAuthenticationInfo. The signature arcs below it show up in + // CV certificates rather than in EF_CardAccess, they are here for lookups. + {8, {BSI_SC, 0x02}, EMRTD_SI_TA, "Terminal Authentication"}, + {9, {BSI_SC, 0x02, 0x01}, EMRTD_SI_TA, "Terminal Authentication, RSA"}, + {10, {BSI_SC, 0x02, 0x01, 0x01}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-1"}, + {10, {BSI_SC, 0x02, 0x01, 0x02}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-256"}, + {10, {BSI_SC, 0x02, 0x01, 0x03}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-1"}, + {10, {BSI_SC, 0x02, 0x01, 0x04}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-256"}, + {10, {BSI_SC, 0x02, 0x01, 0x05}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-512"}, + {10, {BSI_SC, 0x02, 0x01, 0x06}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-512"}, + {9, {BSI_SC, 0x02, 0x02}, EMRTD_SI_TA, "Terminal Authentication, ECDSA"}, + {10, {BSI_SC, 0x02, 0x02, 0x01}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-1"}, + {10, {BSI_SC, 0x02, 0x02, 0x02}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-224"}, + {10, {BSI_SC, 0x02, 0x02, 0x03}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-256"}, + {10, {BSI_SC, 0x02, 0x02, 0x04}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-384"}, + {10, {BSI_SC, 0x02, 0x02, 0x05}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-512"}, + + // id-CA. The 9 byte arcs are ChipAuthenticationDomainParameterInfo, the + // 10 byte ones ChipAuthenticationInfo. + {8, {BSI_SC, 0x03}, EMRTD_SI_CA, "Chip Authentication"}, + {9, {BSI_SC, 0x03, 0x01}, EMRTD_SI_CA_DP, "Chip Authentication, DH"}, + {10, {BSI_SC, 0x03, 0x01, 0x01}, EMRTD_SI_CA, "Chip Authentication, DH, 3DES-CBC-CBC"}, + {10, {BSI_SC, 0x03, 0x01, 0x02}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-128"}, + {10, {BSI_SC, 0x03, 0x01, 0x03}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-192"}, + {10, {BSI_SC, 0x03, 0x01, 0x04}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-256"}, + {9, {BSI_SC, 0x03, 0x02}, EMRTD_SI_CA_DP, "Chip Authentication, ECDH"}, + {10, {BSI_SC, 0x03, 0x02, 0x01}, EMRTD_SI_CA, "Chip Authentication, ECDH, 3DES-CBC-CBC"}, + {10, {BSI_SC, 0x03, 0x02, 0x02}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-128"}, + {10, {BSI_SC, 0x03, 0x02, 0x03}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-192"}, + {10, {BSI_SC, 0x03, 0x02, 0x04}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-256"}, + + // id-PACE. The leaves live in pacealg_table, these two are the + // PACEDomainParameterInfo arcs. + {8, {BSI_SC, 0x04}, EMRTD_SI_PACE, "PACE"}, + {9, {BSI_SC, 0x04, 0x01}, EMRTD_SI_PACE_DP, "PACE, DH domain parameters"}, + {9, {BSI_SC, 0x04, 0x02}, EMRTD_SI_PACE_DP, "PACE, ECDH domain parameters"}, + + // id-RI. 9 byte arcs are RestrictedIdentificationDomainParameterInfo. + {8, {BSI_SC, 0x05}, EMRTD_SI_RI, "Restricted Identification"}, + {9, {BSI_SC, 0x05, 0x01}, EMRTD_SI_RI_DP, "Restricted Identification, DH"}, + {10, {BSI_SC, 0x05, 0x01, 0x01}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-1"}, + {10, {BSI_SC, 0x05, 0x01, 0x02}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-224"}, + {10, {BSI_SC, 0x05, 0x01, 0x03}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-256"}, + {10, {BSI_SC, 0x05, 0x01, 0x04}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-384"}, + {10, {BSI_SC, 0x05, 0x01, 0x05}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-512"}, + {9, {BSI_SC, 0x05, 0x02}, EMRTD_SI_RI_DP, "Restricted Identification, ECDH"}, + {10, {BSI_SC, 0x05, 0x02, 0x01}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-1"}, + {10, {BSI_SC, 0x05, 0x02, 0x02}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-224"}, + {10, {BSI_SC, 0x05, 0x02, 0x03}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-256"}, + {10, {BSI_SC, 0x05, 0x02, 0x04}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-384"}, + {10, {BSI_SC, 0x05, 0x02, 0x05}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-512"}, + + {8, {BSI_SC, 0x06}, EMRTD_SI_CI, "Card Info Locator"}, + {8, {BSI_SC, 0x07}, EMRTD_SI_EIDSECURITY, "eID Security"}, + {8, {BSI_SC, 0x08}, EMRTD_SI_PT, "Privileged Terminal"}, + + {5, {ICAO_SEC}, EMRTD_SI_UNKNOWN, "ICAO MRTD security"}, + {6, {ICAO_SEC, 0x05}, EMRTD_SI_AA, "Active Authentication"}, + {6, {ICAO_SEC, 0x0D}, EMRTD_SI_EFDIR, "EF.DIR"}, + + {0, {0}, EMRTD_SI_UNKNOWN, NULL} +}; + +#undef BSI_SC +#undef ICAO_SEC + +const char *emrtd_secinfo_name(const uint8_t *oid, size_t oidlen, emrtd_si_t *kind) { + const emrtd_secinfo_t *best = NULL; + + // longest prefix wins, so an arc we did not enumerate still resolves to its + // family instead of falling through to "unknown" + for (int i = 0; secinfo_table[i].name != NULL; i++) { + const emrtd_secinfo_t *e = &secinfo_table[i]; + if ((e->oidlen > oidlen) || (memcmp(e->oid, oid, e->oidlen) != 0)) { + continue; + } + if ((best == NULL) || (e->oidlen > best->oidlen)) { + best = e; + } + } + + if (best == NULL) { + if (kind != NULL) { + *kind = EMRTD_SI_UNKNOWN; + } + return NULL; + } + + if (kind != NULL) { + *kind = best->kind; + } + return best->name; +} + +void emrtd_oid_to_str(const uint8_t *oid, size_t oidlen, char *out, size_t outlen) { + if ((out == NULL) || (outlen == 0)) { + return; + } + out[0] = 0x00; + + mbedtls_asn1_buf buf; + buf.tag = MBEDTLS_ASN1_OID; + buf.len = oidlen; + buf.p = (uint8_t *)oid; + + if (mbedtls_oid_get_numeric_string(out, outlen, &buf) < 0) { + out[0] = 0x00; + } +} + const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen) { for (int i = 0; pacealg_table[i].name != NULL; i++) { if (pacealg_table[i].oidlen == oidlen && memcmp(pacealg_table[i].oid, oid, oidlen) == 0) { @@ -492,14 +628,51 @@ static bool emrtd_asn1_uint(const uint8_t *value, size_t valuelen, uint32_t *out // The PACEDomainParameterInfo protocol OIDs, TR-03110 part 3, A.1.1. // 0.4.0.127.0.7.2.2.4.1 (DH) and .2 (ECDH) +// 0.4.0.127.0.7.2.2.4, id-PACE itself +static const uint8_t oid_pace[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04}; static const uint8_t oid_pace_dh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01}; static const uint8_t oid_pace_ecdh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02}; static void emrtd_pace_classify(emrtd_paceinfo_t *info) { info->supported = false; + // Only PACEInfo entries are candidates for the session. The rest of + // EF_CardAccess describes protocols this client does not run, say so + // instead of calling them unsupported PACE algorithms. + switch (info->kind) { + case EMRTD_SI_PACE: + break; + case EMRTD_SI_PACE_DP: + info->reason = "domain parameter definition, informational"; + return; + case EMRTD_SI_CA: + case EMRTD_SI_CA_DP: + case EMRTD_SI_PK: + info->reason = "not a PACE protocol, EAC Chip Authentication is not implemented"; + return; + case EMRTD_SI_TA: + info->reason = "not a PACE protocol, needs an EAC inspection system certificate"; + return; + case EMRTD_SI_RI: + case EMRTD_SI_RI_DP: + info->reason = "not a PACE protocol, needs an EAC sector key"; + return; + case EMRTD_SI_AA: + info->reason = "not a PACE protocol, uses the public key in EF_DG15"; + return; + case EMRTD_SI_CI: + case EMRTD_SI_EIDSECURITY: + case EMRTD_SI_PT: + case EMRTD_SI_EFDIR: + info->reason = "informational, not a PACE protocol"; + return; + case EMRTD_SI_UNKNOWN: + info->reason = "unknown protocol OID"; + return; + } + if (info->alg == NULL) { - info->reason = "unknown protocol OID"; + info->reason = "unknown PACE algorithm OID"; return; } @@ -601,43 +774,45 @@ static void emrtd_pace_parse_securityinfo(const uint8_t *seq, size_t seqlen, emr memcpy(info->oid, val, vlen); info->oidlen = vlen; info->alg = emrtd_pace_alg_by_oid(val, vlen); + info->protocol = emrtd_secinfo_name(val, vlen, &info->kind); - if (is_domain_param) { - // SEQUENCE { OID, AlgorithmIdentifier, INTEGER parameterId OPTIONAL } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { - return; - } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { - uint32_t v = 0; - if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { - info->has_param = true; - info->param_id = (uint8_t)v; - info->sdp = emrtd_pace_sdp_by_id(info->param_id); - } - } - info->supported = false; - info->reason = "domain parameter definition, informational"; - out->count++; - return; + if (info->alg != NULL) { + // a PACEInfo we can act on, pacealg_table has the better name + info->kind = EMRTD_SI_PACE; + info->protocol = info->alg->name; + } else if (is_domain_param) { + info->kind = EMRTD_SI_PACE_DP; + } else if ((vlen > sizeof(oid_pace)) && (memcmp(val, oid_pace, sizeof(oid_pace)) == 0)) { + // an id-PACE arc we do not implement, still a PACEInfo and not a + // domain parameter definition + info->kind = EMRTD_SI_PACE; } - // PACEInfo ::= SEQUENCE { protocol OID, version INTEGER, parameterId INTEGER OPTIONAL } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { - return; - } - if (tag != ASN1_TAG_INTEGER) { - return; - } - if (emrtd_asn1_uint(val, vlen, &info->version) == false) { - return; + // Second element: + // PACEInfo / ChipAuthenticationInfo / TerminalAuthenticationInfo version INTEGER + // PACEDomainParameterInfo / ChipAuthenticationPublicKeyInfo an AlgorithmIdentifier + // or SubjectPublicKeyInfo + // Take it as the version only when it really is an INTEGER. + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { + emrtd_asn1_uint(val, vlen, &info->version); } + // Third element, an optional INTEGER. For the PACE entries that is the + // standardized domain parameter id of table A.2, for the Chip + // Authentication ones it is a keyId and must not be read as a curve. if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { uint32_t v = 0; - if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { - info->has_param = true; - info->param_id = (uint8_t)v; - info->sdp = emrtd_pace_sdp_by_id(info->param_id); + if (emrtd_asn1_uint(val, vlen, &v)) { + if ((info->kind == EMRTD_SI_PACE) || (info->kind == EMRTD_SI_PACE_DP)) { + if (v <= 0xFF) { + info->has_param = true; + info->param_id = (uint8_t)v; + info->sdp = emrtd_pace_sdp_by_id(info->param_id); + } + } else { + info->has_key_id = true; + info->key_id = v; + } } } diff --git a/client/src/emrtd/emrtd_pace.h b/client/src/emrtd/emrtd_pace.h index e42f8189d..5e76ec7be 100644 --- a/client/src/emrtd/emrtd_pace.h +++ b/client/src/emrtd/emrtd_pace.h @@ -57,6 +57,27 @@ typedef enum { EMRTD_PACE_CIPHER_AES256, } emrtd_pace_cipher_t; +// EF_CardAccess is a SET OF SecurityInfo, not a list of PACE algorithms. A +// document announces everything it can do in there, so Chip Authentication and +// Terminal Authentication share the file with the PACE entries. Only +// EMRTD_SI_PACE entries are candidates for the session we are about to open. +typedef enum { + EMRTD_SI_UNKNOWN = 0, + EMRTD_SI_PACE, // PACEInfo + EMRTD_SI_PACE_DP, // PACEDomainParameterInfo + EMRTD_SI_CA, // ChipAuthenticationInfo + EMRTD_SI_CA_DP, // ChipAuthenticationDomainParameterInfo + EMRTD_SI_PK, // ChipAuthenticationPublicKeyInfo + EMRTD_SI_TA, // TerminalAuthenticationInfo + EMRTD_SI_RI, // RestrictedIdentificationInfo + EMRTD_SI_RI_DP, // RestrictedIdentificationDomainParameterInfo + EMRTD_SI_CI, // CardInfoLocator + EMRTD_SI_EIDSECURITY, // eIDSecurityInfo + EMRTD_SI_PT, // PrivilegedTerminalInfo + EMRTD_SI_AA, // ActiveAuthenticationInfo + EMRTD_SI_EFDIR, // EFDIRInfo +} emrtd_si_t; + typedef struct emrtd_pacealg_s { const char *name; emrtd_pace_ka_t ka; @@ -79,12 +100,16 @@ typedef struct emrtd_pacesdp_s { // One parsed SecurityInfo out of EF_CardAccess typedef struct { - const emrtd_pacealg_t *alg; // NULL when the OID is unknown to us + const emrtd_pacealg_t *alg; // NULL unless this is a PACEInfo we know + emrtd_si_t kind; // which SecurityInfo this is + const char *protocol; // pretty name, NULL when the OID is unknown uint8_t oid[EMRTD_PACE_OID_MAXLEN]; size_t oidlen; uint32_t version; bool has_param; uint8_t param_id; + bool has_key_id; // ChipAuthentication* keyId, not a PACE thing + uint32_t key_id; const emrtd_pacesdp_t *sdp; // NULL when param_id is unknown/absent bool supported; const char *reason; // why not supported, NULL when it is @@ -151,6 +176,11 @@ int emrtd_retail_mac(const uint8_t *key, const uint8_t *input, size_t inputlen, // Table lookups //----------------------------------------------------------------------------- const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen); +// Names any SecurityInfo protocol OID, PACE or not. Longest prefix wins, so an +// arc we did not enumerate still resolves to its family. NULL when unknown. +const char *emrtd_secinfo_name(const uint8_t *oid, size_t oidlen, emrtd_si_t *kind); +// Dotted decimal form of a BER encoded OID body, for reporting +void emrtd_oid_to_str(const uint8_t *oid, size_t oidlen, char *out, size_t outlen); const emrtd_pacesdp_t *emrtd_pace_sdp_by_id(uint8_t id); const char *emrtd_pace_cipher_name(emrtd_pace_cipher_t cipher); diff --git a/client/src/emrtd/emrtd_pacetest.c b/client/src/emrtd/emrtd_pacetest.c index 463a790b9..d0646601d 100644 --- a/client/src/emrtd/emrtd_pacetest.c +++ b/client/src/emrtd/emrtd_pacetest.c @@ -547,6 +547,67 @@ static bool test_cardaccess(void) { return res; } +static bool test_cardaccess_secinfo(void) { + // EF_CardAccess is a SET OF SecurityInfo, not a list of PACE algorithms. + // This is the shape a document with EAC has: + // PACEInfo ECDH-GM-AES-CMAC-128, v2, BrainpoolP256r1 + // TerminalAuthenticationInfo id-TA, v1 + // ChipAuthenticationInfo id-CA-ECDH-AES-CBC-CMAC-128, v1, keyId 16 + const char *blob = + "3137" + "3012" "060A04007F0007020204020202010202010D" + "300D" "060804007F0007020202" "020101" + "3012" "060A04007F00070202030202" "020101" "020110"; + + uint8_t data[128] = { 0x00 }; + size_t datalen = unhex(blob, data, sizeof(data)); + + emrtd_cardaccess_t ca; + bool res = (datalen > 0); + res = res && (emrtd_pace_parse_cardaccess(data, datalen, &ca) == PM3_SUCCESS); + // the non-PACE entries must survive parsing, they used to be dropped or + // reported as unknown PACE algorithms + res = res && (ca.count == 3); + res = res && (ca.best == 0); + + res = res && (ca.infos[0].kind == EMRTD_SI_PACE) && (ca.infos[0].supported); + res = res && (ca.infos[0].has_param) && (ca.infos[0].param_id == 13); + + res = res && (ca.infos[1].kind == EMRTD_SI_TA); + res = res && (ca.infos[1].alg == NULL) && (ca.infos[1].supported == false); + res = res && (ca.infos[1].version == 1); + res = res && (ca.infos[1].protocol != NULL) && + (strcmp(ca.infos[1].protocol, "Terminal Authentication") == 0); + + res = res && (ca.infos[2].kind == EMRTD_SI_CA); + res = res && (ca.infos[2].alg == NULL) && (ca.infos[2].supported == false); + res = res && (ca.infos[2].version == 1); + res = res && (ca.infos[2].protocol != NULL) && + (strcmp(ca.infos[2].protocol, "Chip Authentication, ECDH, AES-CMAC-128") == 0); + // a ChipAuthenticationInfo keyId is not a standardized domain parameter id + res = res && (ca.infos[2].has_param == false); + res = res && (ca.infos[2].has_key_id) && (ca.infos[2].key_id == 16); + res = res && (ca.infos[2].sdp == NULL); + + // an id-TA arc we did not enumerate still resolves to its family + const uint8_t ta_odd[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x02, 0x7F}; + emrtd_si_t kind = EMRTD_SI_UNKNOWN; + const char *name = emrtd_secinfo_name(ta_odd, sizeof(ta_odd), &kind); + res = res && (kind == EMRTD_SI_TA) && (name != NULL); + + // and something outside both roots must stay unknown + const uint8_t bogus[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D}; + res = res && (emrtd_secinfo_name(bogus, sizeof(bogus), &kind) == NULL); + res = res && (kind == EMRTD_SI_UNKNOWN); + + char oidstr[64] = { 0x00 }; + emrtd_oid_to_str(ca.infos[1].oid, ca.infos[1].oidlen, oidstr, sizeof(oidstr)); + res = res && (strcmp(oidstr, "0.4.0.127.0.7.2.2.2") == 0); + + PrintAndLogEx(SUCCESS, "SecurityInfos.... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + // Chip Authentication Mapping. // // The chip sends t = SK.Map.IC * SK.CA.IC^-1 mod n encrypted with KSenc, so @@ -667,6 +728,7 @@ bool emrtd_test(bool verbose) { res = test_kdf() && res; res = test_nonce() && res; res = test_cardaccess() && res; + res = test_cardaccess_secinfo() && res; res = test_gm() && res; res = test_ec_keygen() && res; res = test_token() && res; From b3123d153fc30c4632c8e8c14db3d1cc2a02ef22 Mon Sep 17 00:00:00 2001 From: Innocent Bystander Date: Wed, 9 Sep 2026 21:14:26 -0400 Subject: [PATCH 04/26] Adding BWM Flashing instructions to PM5 Documentation --- .../PM5_Start_Here/Getting_Started_With_PM5.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md index 42012b894..3013039a1 100644 --- a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md +++ b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md @@ -104,7 +104,23 @@ hf 14a read --drop ## Do this exactly once. * The very first time for a new battery: ```hw bwm setcap --cap 500``` -* Do a full charge/discharge cycle for it to learn the real capacity. +* Your PM5 will learn about the battery through usage. + +## Flash the BWM +* Make sure your BWM has enough charge in the battery `hw status` 50%+ should work. +* Get the latest firmware: + * Go [here](https://github.com/RfidResearchGroup/Proxmark5_BWM_esp32/actions/workflows/esp-idf-build.yml): + * Click on the latest workflow run (As of this writing that's "Merge pull request #3 from nieldk/master") + * Scroll all the way to the bottom, you'll see **Artifacts** + * Click on "proxmark5_bwm_master" which will start a download for `proxmark5_bwm_master.zip` + * Unzip this file somehwere, remember that location + * The upgrade command is: `hw bwm upgrade -f \proxmark5_ble_wifi_module.bin` + * This will take some time, you'll see the Progress in % displayed on the screen until the process is done. + * Once you see "BWM Rebooting into the new image" you know the upgrade finished. + * Wait a few seconds (under 10) and unplug and replug the Proxmark5 back into the usb port. + * Once reconnected, you can run `hw status` and you'll see: + * `BWM fw version......XX` where XX is the fw version. + * You have finished flashing the BWM. ### Operation From ea2909702fb6a989fe7e85a0c275c6bf0336a096 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 03:58:14 +0200 Subject: [PATCH 05/26] lf t55xx: anchor the block read offset in samples, not demod bits GetT55xxBlockData extracted every block at config.offset, a bit index into a demod buffer cached by the last detect - a different capture. Demodulators do not all start on the same bit, so a later read could return a rotation of the block with nothing marking it as wrong: psk1 by four or five bits, fsk2a and nrz by one, manchester and biphase never. Record the boundary where it is stable instead. Every demodulator reports the graph sample its first bit sits on, and turn_read_lf_on(137 * 8) makes the firmware open each read acquisition at the same point, so the word boundary lands on the same sample every time. Convert back per demodulation. Block 0 re-anchors from its known value, and a write is now verified by the value being anywhere in the repeating stream rather than at one cached offset - which also fixes correct writes reporting as validation failures. A block 0 verify re-detects on a mismatch, not only on a decode failure: the pre-write config can decode the post-write signal into garbage rather than failing. Also fixes a -1 password sentinel truncated to 32 bits by a ternary, which made that detect report a password that was never supplied. Measured on a T5577 across psk1, fsk2a and direct/nrz: three consecutive dumps agree field for field, against a baseline where psk1 corrupted 22 of 24. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 3 + client/src/cmdlft55xx.c | 244 +++++++++++++++++++++++++++++++--------- client/src/cmdlft55xx.h | 12 +- 3 files changed, 203 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f36f364a6..1693377e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) +- Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) +- Fixed `lf t55xx detect` - the automatic detect after a block 0 write reported a password that was never supplied (@iceman1001) - Fixed `hf emrtd info` - now correctly pretty print algos (@iceman1001) - Fixed `trace list -t topaz` - now parses topaz reader frames up to 16 bytes (@iceman1001) - Fixed `hw bwm` - doc and comment references still named the flat `hw bwmsetcap`/`bwmcharge`/`bwmautooff` commands from before the subgroup move (@xilni) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index fc9fbd648..a4131c407 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -76,6 +76,110 @@ static t55xx_conf_block_t config = { static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; +// A block read repeats one 32 bit word for as long as the field is on, so a +// demodulation that starts one bit late yields a rotation of the block with +// nothing in the data to mark it as wrong. `offset` is a bit index into a +// demod buffer that no longer exists once the next acquisition lands, and the +// demodulators do not all start on the same bit: manchester anchors on the +// sequence terminator, psk starts at whatever phase transition it finds first. +static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { + c->offset = offset; + c->anchor_valid = (g_DemodClock > 0); + c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock); + c->anchor_tracelen = (int32_t)g_GraphTraceLen; +} + +// records a detect candidate against the demodulation that is loaded right now +static void t55xx_record_hit(t55xx_conf_block_t *t) { + t->block0 = PackBits(t->offset, 32, g_DemodBuffer); + t->anchor_valid = (g_DemodClock > 0); + t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock); + t->anchor_tracelen = (int32_t)g_GraphTraceLen; +} + +// the bit offset to read a block at in the demod buffer loaded right now +static bool t55xx_demod_offset(uint8_t *idx) { + + if (g_DemodBufferLen < 32) { + PrintAndLogEx(DEBUG, "DEBUG: (t55xx) demod buffer holds %zu bits, need 32", g_DemodBufferLen); + return false; + } + + int32_t bit = config.offset; + + // a different graph length is a different signal, not another read of the + // same one - fall back to the plain offset rather than resolve against it + if (config.anchor_valid && + g_DemodClock > 0 && + (config.anchor_tracelen == (int32_t)g_GraphTraceLen)) { + + // negative when this demodulation started later than the anchored one + const int32_t delta = config.anchor_sample - g_DemodStartIdx; + const int32_t half = g_DemodClock / 2; + + bit = (delta >= 0) ? ((delta + half) / g_DemodClock) : -((-delta + half) / g_DemodClock); + + // landing outside the buffer means this demodulation started a long way + // from the anchored one. an addressed block read repeats every 32 bits, + // so whole periods can be added or dropped to bring the window back in. + // that is a rescue, not a normalisation - a regular read mode capture + // cycles several blocks and would answer with a different one + while (bit < 0) { + bit += 32; + } + while (bit + 32 > (int32_t)g_DemodBufferLen) { + bit -= 32; + } + } + + if (bit < 0 || bit + 32 > (int32_t)g_DemodBufferLen) { + PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %zu)", bit, g_DemodBufferLen - 32); + return false; + } + + *idx = (uint8_t)bit; + return true; +} + +// a word that is its own rotation cannot say where the boundary is +static bool t55xx_rotation_unique(uint32_t v) { + for (uint8_t r = 1; r < 32; r++) { + if ((((v << r) | (v >> (32 - r))) & 0xFFFFFFFF) == v) { + return false; + } + } + return true; +} + +// true when the demodulated stream carries `data` at some offset. a block read +// repeats the addressed word, so a hit anywhere proves the tag holds it, no +// matter which bit the demodulator started on. a false hit needs a 32 bit +// coincidence in a few hundred positions. re-anchors on the hit, which is the +// one place a data block can say where its own boundary is +static bool t55xx_stream_holds(uint32_t data) { + + if (g_DemodBufferLen < 32) { + return false; + } + + for (size_t i = 0; i + 32 <= g_DemodBufferLen; i++) { + + if (PackBits(0, 32, g_DemodBuffer + i) != data) { + continue; + } + + if (i <= 255 && t55xx_rotation_unique(data)) { + const uint8_t before = config.offset; + t55xx_anchor(&config, (uint8_t)i); + if (before != config.offset) { + PrintAndLogEx(DEBUG, "DEBUG: (t55xx) re-anchored offset %u -> %u", before, config.offset); + } + } + return true; + } + return false; +} + t55xx_conf_block_t Get_t55xx_Config(void) { return config; } @@ -333,7 +437,7 @@ bool t55xxAcquireAndCompareBlock0(bool usepwd, uint32_t password, uint32_t known for (size_t i = 0; i < g_DemodBufferLen - 32; i++) { uint32_t tmp = PackBits(i, 32, g_DemodBuffer); if (tmp == known_block0) { - config.offset = i; + t55xx_anchor(&config, (uint8_t)i); config.downlink_mode = m; return true; } @@ -351,7 +455,10 @@ bool t55xxAcquireAndDetect(bool usepwd, uint32_t password, uint32_t known_block0 if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password, m) == false) continue; - if (t55xxTryDetectModulationEx(m, verbose, known_block0, (usepwd) ? password : -1) == false) + // password is uint32_t here, so an untyped -1 would be truncated to + // 0xFFFFFFFF by the ternary before it widens, and the `pwd != -1` + // sentinel check inside would read it as a known password + if (t55xxTryDetectModulationEx(m, verbose, known_block0, (usepwd) ? (uint64_t)password : (uint64_t) - 1) == false) continue; config.downlink_mode = m; @@ -362,9 +469,10 @@ bool t55xxAcquireAndDetect(bool usepwd, uint32_t password, uint32_t known_block0 return false; } -bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data) { +static bool t55xx_verify_write_ex(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data, bool redetect) { uint32_t read_data = 0; + bool ok = false; if (downlink_mode == 0xFF) downlink_mode = config.downlink_mode; @@ -372,23 +480,37 @@ bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, int res = T55xxReadBlockEx(block, page1, usepwd, override, password, downlink_mode, false); if (res == PM3_SUCCESS) { - if (GetT55xxBlockData(&read_data) == false) - return false; + // the value being anywhere in the stream is the proof, not the value at + // one cached offset. a correct write read back on a different bit + // boundary used to report as a validation failure + ok = t55xx_stream_holds(data); - } else if (res == PM3_EWRONGANSWER) { - - // couldn't decode. Lets see if this was a block 0 write and try read/detect it auto. - // this messes up with ppl config.. - if (block == 0 && page1 == false) { - - if (t55xxAcquireAndDetect(usepwd, password, data, true) == false) - return false; - - return t55xxVerifyWrite(block, page1, usepwd, 2, password, config.downlink_mode, data); + if (ok == false && GetT55xxBlockData(&read_data)) { + ok = (read_data == data); } } - return (read_data == data); + if (ok) { + return true; + } + + // A block 0 write changes how the tag talks, so the configuration held from before the write is stale. + // A: he demodulator fails outright, or + // B:_it succeeds on the wrong modulation and answers with garbage + if (block == 0 && page1 == false && redetect) { + + if (t55xxAcquireAndDetect(usepwd, password, data, true) == false) { + return false; + } + + return t55xx_verify_write_ex(block, page1, usepwd, 2, password, config.downlink_mode, data, false); + } + + return false; +} + +bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data) { + return t55xx_verify_write_ex(block, page1, usepwd, override, password, downlink_mode, data, true); } int t55xxWrite(uint8_t block, bool page1, bool usepwd, bool testMode, uint32_t password, uint8_t downlink_mode, uint32_t data) { @@ -461,6 +583,9 @@ void SetConfigWithBlock0Ex(uint32_t block0, uint8_t offset, bool Q5) { config.Q5 = Q5; config.ST = sst; config.usepwd = pwd; + if (config.offset != offset) { + config.anchor_valid = false; + } config.offset = offset; config.block0 = block0; } @@ -580,6 +705,7 @@ static int CmdT55xxSetConfig(const char *Cmd) { // validate user specified offset if (offset > -1 && offset < 0x100) { config.offset = offset; + config.anchor_valid = false; } // validate user specific T5555 / Q5 - use the flag to toggle between T5577 and Q5 @@ -688,8 +814,19 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u if (DecodeT55xxBlock() == false) return PM3_EWRONGANSWER; - if (verbose) + // block 0 is the one block whose content is known before it is read, so use + // it to re-anchor this capture rather than trusting the one detect left + if (block == T55x7_CONFIGURATION_BLOCK && + page1 == false && + config.block0Status == AUTODETECT && + config.block0 != 0) { + + t55xx_stream_holds(config.block0); + } + + if (verbose) { printT55xxBlock(block, page1); + } return PM3_SUCCESS; } @@ -1230,7 +1367,7 @@ static void t55xx_psk_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test tests[*hits].psk_carrier = t55xx_observed_psk_carrier(); tests[*hits].bitrate = bitRate; tests[*hits].inverted = inverted; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1314,7 +1451,7 @@ static void t55xx_ask_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test tests[*hits].modulation = mode; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (invert != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1374,7 +1511,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = m; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1402,7 +1539,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_PSK1; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1417,7 +1554,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].psk_carrier = t55xx_observed_psk_carrier(); tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1449,7 +1586,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_NRZ; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1465,7 +1602,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_ASK; tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].downlink_mode = downlink_mode; (*hits)++; return true; @@ -1478,7 +1615,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_ASK; tests[*hits].bitrate = bitRate; tests[*hits].inverted = true; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].downlink_mode = downlink_mode; (*hits)++; return true; @@ -1490,7 +1627,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_BI; tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1503,7 +1640,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_BIa; tests[*hits].bitrate = bitRate; tests[*hits].inverted = true; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1647,7 +1784,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_FSK2; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1660,7 +1797,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_FSK2a; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1678,7 +1815,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].downlink_mode = downlink_mode; ++hits; } @@ -1692,7 +1829,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].downlink_mode = downlink_mode; ++hits; } @@ -1700,7 +1837,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_BI; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1709,7 +1846,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_BIa; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1721,7 +1858,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1731,7 +1868,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1749,7 +1886,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1758,7 +1895,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1772,7 +1909,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].psk_carrier = t55xx_observed_psk_carrier(); tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1802,6 +1939,9 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 config.bitrate = tests[0].bitrate; config.inverted = tests[0].inverted; config.offset = tests[0].offset; + config.anchor_sample = tests[0].anchor_sample; + config.anchor_tracelen = tests[0].anchor_tracelen; + config.anchor_valid = tests[0].anchor_valid; config.block0 = tests[0].block0; config.Q5 = tests[0].Q5; config.ST = tests[0].ST; @@ -1835,6 +1975,9 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 config.bitrate = tests[i].bitrate; config.inverted = tests[i].inverted; config.offset = tests[i].offset; + config.anchor_sample = tests[i].anchor_sample; + config.anchor_tracelen = tests[i].anchor_tracelen; + config.anchor_valid = tests[i].anchor_valid; config.block0 = tests[i].block0; config.Q5 = tests[i].Q5; config.ST = tests[i].ST; @@ -1892,13 +2035,8 @@ bool testKnownConfigBlock(uint32_t block0) { bool GetT55xxBlockData(uint32_t *blockdata) { - if (g_DemodBufferLen == 0) - return false; - - uint8_t idx = config.offset; - - if (idx + 32 > g_DemodBufferLen) { - PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %zu)", idx, g_DemodBufferLen - 32); + uint8_t idx = 0; + if (t55xx_demod_offset(&idx) == false) { return false; } @@ -2142,9 +2280,12 @@ static size_t t55xx_psk3_resolve(uint8_t nblk, uint32_t *only) { void printT55xxBlock(uint8_t blockNum, bool page1) { - uint32_t val = 0; - if (GetT55xxBlockData(&val) == false) + uint8_t idx = 0; + if (t55xx_demod_offset(&idx) == false) { return; + } + + uint32_t val = PackBits(0, 32, g_DemodBuffer + idx); uint8_t bytes[4] = {0}; num_to_bytes(val, 4, bytes); @@ -2153,7 +2294,7 @@ void printT55xxBlock(uint8_t blockNum, bool page1) { const char *note = t55xx_config_psk3_ambiguous() ? _YELLOW_(" <- psk2/psk3 ambiguous") : ""; - PrintAndLogEx(SUCCESS, " %02d | %08X | %s | %s%s", blockNum, val, sprint_bytebits_bin(g_DemodBuffer + config.offset, 32), sprint_ascii(bytes, 4), note); + PrintAndLogEx(SUCCESS, " %02d | %08X | %s | %s%s", blockNum, val, sprint_bytebits_bin(g_DemodBuffer + idx, 32), sprint_ascii(bytes, 4), note); } static bool testModulation(uint8_t mode, uint8_t modread) { @@ -3302,13 +3443,12 @@ static int CmdT55xxInfo(const char *Cmd) { return PM3_ESOFT; } - // too little space to start with - if (g_DemodBufferLen < 32 + config.offset) { + uint8_t boff = 0; + if (t55xx_demod_offset(&boff) == false) { return PM3_ESOFT; } - //PrintAndLogEx(NORMAL, "Offset+32 ==%d\n DemodLen == %d", config.offset + 32, g_DemodBufferLen); - block0 = PackBits(config.offset, 32, g_DemodBuffer); + block0 = PackBits(0, 32, g_DemodBuffer + boff); } PrintAndLogEx(NORMAL, ""); diff --git a/client/src/cmdlft55xx.h b/client/src/cmdlft55xx.h index a0ded1fa7..750e51d17 100644 --- a/client/src/cmdlft55xx.h +++ b/client/src/cmdlft55xx.h @@ -20,6 +20,7 @@ #define CMDLFT55XX_H__ #include "common.h" +#include #define T55x7_CONFIGURATION_BLOCK 0x00 #define T55x7_PWD_BLOCK 0x07 @@ -158,10 +159,13 @@ typedef struct { } bitrate; bool Q5; bool ST; - uint8_t psk_carrier; // observed psk subcarrier in field clocks, 2/4/8. 0 = not measured - uint8_t broadcast_blocks; // measured blocks per regular-read cycle. 0 = not measured - bool psk3_favoured; // data blocks lean psk3, but do not settle it - bool pwd_known; // usepwd below reflects a live detect, not a default + int32_t anchor_sample; + int32_t anchor_tracelen; // graph length it was taken on, so a loaded file + bool anchor_valid; // anchor_sample came from a live demodulation + uint8_t psk_carrier; // observed psk subcarrier in field clocks, 2/4/8. 0 = not measured + uint8_t broadcast_blocks; // measured blocks per regular-read cycle. 0 = not measured + bool psk3_favoured; // data blocks lean psk3, but do not settle it + bool pwd_known; // usepwd below reflects a live detect, not a default bool usepwd; uint32_t pwd; enum { From bef7f3752ac37e174155b722ab6f8e3fb3392865 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 04:03:57 +0200 Subject: [PATCH 06/26] another entry --- client/resources/aid_desfire.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index 3b4f180c0..705baa24f 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -311,6 +311,14 @@ "Description": "SMARTair Credential", "Type": "pacs" }, + { + "AID": "F70090", + "Vendor": "ASSA ABLOY (Timelox / VingCard Elsafe)", + "Country": "SE", + "Name": "Visionline", + "Description": "Hotel access credential", + "Type": "pacs" + }, { "AID": "F51BC0", "Vendor": "STid Group", From d54ae662cec526586caa1697d1e59d49ce582841 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 04:31:47 +0200 Subject: [PATCH 07/26] fix lua scripts grabbing return text. mimics the python binding way now --- client/src/scripting.c | 43 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/client/src/scripting.c b/client/src/scripting.c index 8901de663..efe75ec44 100644 --- a/client/src/scripting.c +++ b/client/src/scripting.c @@ -416,12 +416,51 @@ static int l_kbd_enter_pressed(lua_State *L) { /** * @brief Calls the command line parser to deal with the command. This enables * lua-scripts to do stuff like "core.console('hf mf mifare')" + * core.console(cmd [, capture [, quiet]]) + * + * Same idea as the python binding + * `capture` hands the command's output back as a string, + * `quiet` keeps it off the// terminal * @param L * @return */ static int l_CmdConsole(lua_State *L) { - CommandReceived((char *)luaL_checkstring(L, 1)); - return 0; + + const char *cmd = luaL_checkstring(L, 1); + + const bool capture = (lua_isnoneornil(L, 2) == 0) && lua_toboolean(L, 2); + const bool quiet = (lua_isnoneornil(L, 3) == 0) && lua_toboolean(L, 3); + + const uint8_t prev_printAndLog = g_printAndLog; + + if (capture) { + g_printAndLog |= PRINTANDLOG_GRAB; + // anything left in the grabber belongs to an earlier call + g_grabbed_output.idx = 0; + } + + if (quiet) { + g_printAndLog &= ~PRINTANDLOG_PRINT; + } + + CommandReceived((char *)cmd); + + g_printAndLog = prev_printAndLog; + + if (capture == false) { + return 0; + } + + if (g_grabbed_output.ptr == NULL) { + lua_pushstring(L, ""); + return 1; + } + + g_grabbed_output.ptr[g_grabbed_output.idx] = 0; + lua_pushstring(L, g_grabbed_output.ptr); + + g_grabbed_output.idx = 0; + return 1; } static int l_iso15693_crc(lua_State *L) { From e121e3f0a84a48c22cc927867fbe3e9a6f8ad0b8 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 05:28:06 +0200 Subject: [PATCH 08/26] fixing FSK / t5577 --- CHANGELOG.md | 1 + client/src/cmdlft55xx.c | 125 ++++++++++++++++++++++++++++++++-------- 2 files changed, 103 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1693377e6..62a8bc90b 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 `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) - Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) - Fixed `lf t55xx detect` - the automatic detect after a block 0 write reported a password that was never supplied (@iceman1001) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index a4131c407..7e8cfcc46 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -76,12 +76,15 @@ static t55xx_conf_block_t config = { static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; -// A block read repeats one 32 bit word for as long as the field is on, so a -// demodulation that starts one bit late yields a rotation of the block with -// nothing in the data to mark it as wrong. `offset` is a bit index into a -// demod buffer that no longer exists once the next acquisition lands, and the -// demodulators do not all start on the same bit: manchester anchors on the -// sequence terminator, psk starts at whatever phase transition it finds first. +// true when the graph buffer holds an addressed block read, where the tag repeats one word every 32 bits. +// Regular read mode cycles several blocks and a buffer loaded from a file could be either +static bool s_block_read_capture = false; + +// A block read repeats one 32 bit word for as long as the field is on. +// `offset` is a bit index into a demod buffer that no longer exists once the next acquisition lands, +// and the demodulators do not all start on the same bit: +// manchester anchors on the sequence terminator, +// psk starts at whatever phase transition it finds first. static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { c->offset = offset; c->anchor_valid = (g_DemodClock > 0); @@ -109,9 +112,9 @@ static bool t55xx_demod_offset(uint8_t *idx) { // a different graph length is a different signal, not another read of the // same one - fall back to the plain offset rather than resolve against it - if (config.anchor_valid && - g_DemodClock > 0 && - (config.anchor_tracelen == (int32_t)g_GraphTraceLen)) { + if (config.anchor_valid && + g_DemodClock > 0 && + (config.anchor_tracelen == (int32_t)g_GraphTraceLen)) { // negative when this demodulation started later than the anchored one const int32_t delta = config.anchor_sample - g_DemodStartIdx; @@ -816,11 +819,11 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u // block 0 is the one block whose content is known before it is read, so use // it to re-anchor this capture rather than trusting the one detect left - if (block == T55x7_CONFIGURATION_BLOCK && + if (block == T55x7_CONFIGURATION_BLOCK && page1 == false && - config.block0Status == AUTODETECT && + config.block0Status == AUTODETECT && config.block0 != 0) { - + t55xx_stream_holds(config.block0); } @@ -1130,6 +1133,11 @@ static int CmdT55xxDetect(const char *Cmd) { if (SanityOfflineCheck(use_gb) != PM3_SUCCESS) return PM3_ESOFT; + // a replayed buffer carries no promise about how it was captured + if (use_gb) { + s_block_read_capture = false; + } + if (use_gb == false) { char wakecmd[20] = { 0x00 }; @@ -1270,6 +1278,40 @@ bool t55xxTryDetectModulation(uint8_t downlink_mode, bool print_config) { #define PM3_T55_FALLBACK_MAXERR 100 +// A demodulation that recovers far fewer bits than its clock implies never locked onto the tag, +// Measured on a T5577 over 56 configurations: +// every correct detection recovered at least 98.8% of g_GraphTraceLen / clk bits +// while the fsk aliasing that invents a configuration out of an RF/8 signal recovered 59 to 64%. +#define T55XX_MIN_DEMOD_YIELD_PCT 80 + +static bool t55xx_demod_yield_ok(uint8_t clk) { + + // what actually produced the bits, which is not always what was asked for + const uint32_t used = (g_DemodClock > 0) ? (uint32_t)g_DemodClock : clk; + + if (used == 0 || g_GraphTraceLen == 0) { + return true; + } + + const size_t expected = g_GraphTraceLen / used; + + // too short to say anything either way + if (expected < 32) { + return true; + } + + if (g_DemodBufferLen * 100 >= expected * T55XX_MIN_DEMOD_YIELD_PCT) { + return true; + } + + PrintAndLogEx(DEBUG, "DEBUG: (t55xx test) clk %u recovered %zu bits of %zu, too few to trust" + , used + , g_DemodBufferLen + , expected + ); + return false; +} + static bool block0_repeats_at_stride(uint8_t offset) { if ((size_t)offset + 64 > g_DemodBufferLen || offset > 255 - 32) { @@ -1278,8 +1320,16 @@ static bool block0_repeats_at_stride(uint8_t offset) { return (PackBits(offset, 32, g_DemodBuffer) == PackBits((uint8_t)(offset + 32), 32, g_DemodBuffer)); } -// psk subcarrier in field clocks, or 0 when it could not be measured, so -// callers can skip the constraint rather than filter on a bad reading +// psk subcarrier in field clocks, or 0 when it could not be measured +// At RF/128 a capture is 93 bits, so a word sitting past bit 29 has no second copy to compare against +static bool block0_stride_not_disproved(uint8_t offset) { + + if ((size_t)offset + 64 > g_DemodBufferLen) { + return true; + } + return block0_repeats_at_stride(offset); +} + static uint8_t t55xx_observed_psk_carrier(void) { const int fc = GetPskCarrier(false); return (fc == 2 || fc == 4 || fc == 8) ? (uint8_t)fc : 0; @@ -1474,13 +1524,21 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l if (mod == PM3_MOD_FSK) { - static const uint8_t rates[] = { 32, 40, 50, 64, 100, 128 }; + // RF/8 is left out on purpose. A bit period of 8 field clocks cannot + // hold a whole cycle of both tones of either legal pair, and measured + // on a T5577 no fsk variant reads back at RF/8 even with the config + // forced and both inversions tried. + static const uint8_t rates[] = { 16, 32, 40, 50, 64, 100, 128 }; const uint8_t pairs[3][2] = { { (uint8_t)fc_hi, (uint8_t)fc_lo }, { 8, 5 }, { 10, 8 } }; - for (int strict = 1; strict >= 0; strict--) { + // An addressed block read repeats the word every 32 bits, + // a candidate that does not is not a configuration + const int last_pass = s_block_read_capture ? 1 : 0; + + for (int strict = 1; strict >= last_pass; strict--) { for (size_t p = 0; p < ARRAYLEN(pairs); p++) { if (pairs[p][0] == 0 || pairs[p][1] == 0) { @@ -1497,7 +1555,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l continue; } - if (strict && block0_repeats_at_stride(tests[*hits].offset) == false) { + if (strict && block0_stride_not_disproved(tests[*hits].offset) == false) { continue; } @@ -1916,12 +1974,6 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 } } // inverse waves does not affect this demod - // no psk3 candidate here on purpose: it would demodulate the same - // as psk2 and only differ in the test() constant, which wants two - // adjacent ones - and this demod recovers rising edges, which are - // never adjacent. psk3 is reached by ruling psk2 out instead, see - // t55xx_psk3_resolve() - //undo trim samples restore_bufferS32(saveState, g_GraphBuffer); g_GridOffset = saveState.offset; @@ -1930,6 +1982,12 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 } } + // The tag only has two legal fsk pair + // An fsk1 tag at RF/32 counts field clocks as 5 and 6 here + if (hits == 0) { + t55xx_fallback_try(PM3_MOD_FSK, 0, 0, 0, 0, tests, &hits, downlink_mode, false); + } + if (hits == 0) { t55xx_detect_fallback(tests, &hits, downlink_mode); } @@ -2496,6 +2554,12 @@ static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t cl //uint8_t nml01 = PackBits(si, 1, g_DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode //uint8_t nml02 = PackBits(si, 2, g_DemodBuffer); si += 2; + // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. + // Set with any other key the word is not a valid configuration + if (extend && safer != 0x6 && safer != 0x9) { + continue; + } + //if extended mode bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; @@ -2522,6 +2586,15 @@ static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t cl *fndBitRate = bitRate; *offset = (uint8_t)idx; + + PrintAndLogEx(DEBUG, "DEBUG: (t55xx test) accepted mode %u clk %u rate %d offset %u bits %zu of %zu" + , mode + , clk + , bitRate + , idx + , g_DemodBufferLen + , (clk > 0) ? (g_GraphTraceLen / clk) : 0 + ); return true; } @@ -2543,6 +2616,10 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) return false; } + if (t55xx_demod_yield_ok(clk) == false) { + return false; + } + // Scan as far as the buffer allows rather than stopping at bit 64. // // The tag repeats its configuration every 32 bits, so a window of 36 @@ -3851,6 +3928,8 @@ bool AcquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password, u payload.pwdmode = pwdmode; payload.downlink_mode = downlink_mode; + s_block_read_capture = (block != REGULAR_READ_MODE_BLOCK); + clearCommandBuffer(); SendCommandNG(CMD_LF_T55XX_READBL, (uint8_t *)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_LF_T55XX_READBL, NULL, 2500) == false) { From 78b4d4ef00b07bed316ebef795af7fa62c0a1162 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 05:45:13 +0200 Subject: [PATCH 09/26] fix psk1 detection. now scores 24/24 tests --- CHANGELOG.md | 1 + client/src/cmdlft55xx.c | 68 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62a8bc90b..ceef461b4 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 `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) - Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 7e8cfcc46..278035352 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -82,7 +82,7 @@ static bool s_block_read_capture = false; // A block read repeats one 32 bit word for as long as the field is on. // `offset` is a bit index into a demod buffer that no longer exists once the next acquisition lands, -// and the demodulators do not all start on the same bit: +// and the demodulators do not all start on the same bit: // manchester anchors on the sequence terminator, // psk starts at whatever phase transition it finds first. static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { @@ -820,9 +820,9 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u // block 0 is the one block whose content is known before it is read, so use // it to re-anchor this capture rather than trusting the one detect left if (block == T55x7_CONFIGURATION_BLOCK && - page1 == false && - config.block0Status == AUTODETECT && - config.block0 != 0) { + page1 == false && + config.block0Status == AUTODETECT && + config.block0 != 0) { t55xx_stream_holds(config.block0); } @@ -1279,9 +1279,8 @@ bool t55xxTryDetectModulation(uint8_t downlink_mode, bool print_config) { #define PM3_T55_FALLBACK_MAXERR 100 // A demodulation that recovers far fewer bits than its clock implies never locked onto the tag, -// Measured on a T5577 over 56 configurations: +// Measured on a T5577 over 56 configurations: // every correct detection recovered at least 98.8% of g_GraphTraceLen / clk bits -// while the fsk aliasing that invents a configuration out of an RF/8 signal recovered 59 to 64%. #define T55XX_MIN_DEMOD_YIELD_PCT 80 static bool t55xx_demod_yield_ok(uint8_t clk) { @@ -1413,6 +1412,11 @@ static void t55xx_psk_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test continue; } + // sweeping the bit rates means a wrong one can fit first where an RF/16 signal answers at RF/8 + if (s_block_read_capture && block0_stride_not_disproved(tests[*hits].offset) == false) { + continue; + } + tests[*hits].modulation = modes[variant]; tests[*hits].psk_carrier = t55xx_observed_psk_carrier(); tests[*hits].bitrate = bitRate; @@ -1498,6 +1502,11 @@ static void t55xx_ask_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test continue; } + // sweeping the bit rates means a wrong one can fit first, so hold a block read to the 32 bit stride + if (s_block_read_capture && block0_stride_not_disproved(tests[*hits].offset) == false) { + continue; + } + tests[*hits].modulation = mode; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (invert != 0); @@ -1527,7 +1536,10 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l // RF/8 is left out on purpose. A bit period of 8 field clocks cannot // hold a whole cycle of both tones of either legal pair, and measured // on a T5577 no fsk variant reads back at RF/8 even with the config - // forced and both inversions tried. + // forced and both inversions tried. + // RF/8 stays out: it gains nothing measured, and on a replayed capture, + // where the 32 bit stride cannot be demanded, it aliases a Q5 fsk2a trace + // into a confident wrong answer static const uint8_t rates[] = { 16, 32, 40, 50, 64, 100, 128 }; const uint8_t pairs[3][2] = { @@ -1825,6 +1837,38 @@ static void t55xx_detect_fallback(t55xx_conf_block_t *tests, uint8_t *hits, uint free(sig); } +// The coherent psk detector is only reached when the fitter ranks psk above ask and nrz, and on a weak psk signal it does not at all. +static void t55xx_psk_sweep(t55xx_conf_block_t *tests, uint8_t *hits, uint8_t downlink_mode) { + + if (s_block_read_capture == false) { + return; + } + + static const uint8_t rates[] = { 8, 16, 32, 40, 50, 64, 100, 128 }; + + const uint8_t before = *hits; + + for (size_t r = 0; r < ARRAYLEN(rates) && *hits == before; r++) { + t55xx_psk_coherent(rates[r], rates[r], tests, hits, downlink_mode); + } +} + +// same argument as t55xx_psk_sweep, for the ask and biphase side +static void t55xx_ask_sweep(t55xx_conf_block_t *tests, uint8_t *hits, uint8_t downlink_mode) { + + if (s_block_read_capture == false) { + return; + } + + static const uint8_t rates[] = { 8, 16, 32, 40, 50, 64, 100, 128 }; + + const uint8_t before = *hits; + + for (size_t r = 0; r < ARRAYLEN(rates) && *hits == before; r++) { + t55xx_ask_coherent(rates[r], rates[r], tests, hits, downlink_mode); + } +} + bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32_t wanted_conf, uint64_t pwd) { t55xx_conf_block_t tests[15] = {0}; @@ -1984,10 +2028,18 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 // The tag only has two legal fsk pair // An fsk1 tag at RF/32 counts field clocks as 5 and 6 here - if (hits == 0) { + if (hits == 0 && s_block_read_capture) { t55xx_fallback_try(PM3_MOD_FSK, 0, 0, 0, 0, tests, &hits, downlink_mode, false); } + if (hits == 0) { + t55xx_psk_sweep(tests, &hits, downlink_mode); + } + + if (hits == 0) { + t55xx_ask_sweep(tests, &hits, downlink_mode); + } + if (hits == 0) { t55xx_detect_fallback(tests, &hits, downlink_mode); } From 1457a5d8279e8ee29a864891a361744de9341585 Mon Sep 17 00:00:00 2001 From: Innocent Bystander Date: Thu, 10 Sep 2026 01:17:06 -0400 Subject: [PATCH 10/26] Add verbage to make flashing the BWM clearer --- doc/md/PM5_Start_Here/Getting_Started_With_PM5.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md index 3013039a1..3dcc7e403 100644 --- a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md +++ b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md @@ -114,12 +114,12 @@ hf 14a read --drop * Scroll all the way to the bottom, you'll see **Artifacts** * Click on "proxmark5_bwm_master" which will start a download for `proxmark5_bwm_master.zip` * Unzip this file somehwere, remember that location - * The upgrade command is: `hw bwm upgrade -f \proxmark5_ble_wifi_module.bin` + * The upgrade command is: `hw bwm upgrade -f proxmark5_ble_wifi_module.bin` * This will take some time, you'll see the Progress in % displayed on the screen until the process is done. * Once you see "BWM Rebooting into the new image" you know the upgrade finished. * Wait a few seconds (under 10) and unplug and replug the Proxmark5 back into the usb port. * Once reconnected, you can run `hw status` and you'll see: - * `BWM fw version......XX` where XX is the fw version. + * `BWM fw version...... 1` where 1 is the current fw version. As of 2026-09-10, the most current version is 1. * You have finished flashing the BWM. From 82c726dd9b6cd78dcfb61844e6fb7f8e8eb43408 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 10 Sep 2026 10:05:10 +0200 Subject: [PATCH 11/26] fix t55xx_config.lua script with scoring of psk2/3 to write a proper text --- client/lualibs/t55xx_config.lua | 41 +++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/client/lualibs/t55xx_config.lua b/client/lualibs/t55xx_config.lua index f3f1e67e1..fbba524d1 100644 --- a/client/lualibs/t55xx_config.lua +++ b/client/lualibs/t55xx_config.lua @@ -131,11 +131,25 @@ function Config.detect(offline) .. 'Rebuild with `make client` and start a new pm3 session', 0) end - local block0 = out:match('Block0%.+%s*(%x%x%x%x%x%x%x%x)') - if block0 == nil then return nil, out end + -- Everything between the Block0 label and the next field. That covers both + -- forms detect prints: one word, or `ambiguous, one of:` followed by a + -- candidate per line. PSK2 and PSK3 are the same waveform under a + -- different reading, so a candidate list is detect being honest, not + -- detect failing, and the suite has to be able to score it + local seg = out:match('Block0%.+(.-)Downlink mode') or out:match('Block0%.+([^\n]*)') + + local cands = {} + if seg ~= nil then + for w in seg:gmatch('(%x%x%x%x%x%x%x%x)') do + table.insert(cands, w) + end + end + + if #cands == 0 then return nil, out end return { - block0 = block0, + block0 = cands[1], + candidates = cands, modulation = out:match('Modulation%.+%s*([^\n]-)%s*\n'), bitrate = out:match('Bit rate%.+%s*([^\n]-)%s*\n'), offset = out:match('Offset%.+%s*(%d+)'), @@ -265,7 +279,26 @@ function Config.check(report, block0, opts) local found = Config.detect(opts.offline) core.clearCommandBuffer() - local res = report:add(block0, found and found.block0 or nil) + local got, extra = nil, {} + + if found ~= nil then + + got = found.block0 + + -- a word the tag could be holding counts as read back. Say how many + -- readings were live, so an ambiguous pass is not mistaken for a clean one + if #found.candidates > 1 then + + for _, c in ipairs(found.candidates) do + if c:upper() == block0:upper() then got = c end + end + + extra.ok = (got:upper() == block0:upper()) + extra.note = extra.ok and ('ambiguous, 1 of ' .. #found.candidates) or 'MISMATCH' + end + end + + local res = report:add(block0, got, extra) if opts.verbose then core.console('lf t55xx info') From 782d28932c27fabc8ab9fa8b827856a581d7e297 Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 10:33:17 -0700 Subject: [PATCH 12/26] lf: restore the graph buffer length along with its contents restore_bufferS32() returns the length it put back and every graph-buffer caller dropped it, so g_GraphTraceLen kept whatever value the code between save and restore had left. In try_detect_modulation() that is the 160 sample psk antenna-settle trim: `data modulation` gave the buffer's samples back but left it 160 short, and a following demod lost round(160 / clk) bits off the end. check_chiptype() loses the same way through the acquisitions its detections make, on the `lf search` path, and for g_DemodBuffer too. demodTI() loses convLen + 16 on its error path. save_graphbuffer() / restore_graphbuffer() pair the length and grid offset with the contents so no call site has to remember them. The visa2000 and zx8211 sites do not change the length, so converting them is a no-op today and keeps the next one from being a bug. Regression test in tools/pm3_tests.sh: `data modulation` on a saved psk1 trace must leave all 20000 samples. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + client/src/cmddata.c | 6 ++---- client/src/cmdlf.c | 9 ++++----- client/src/cmdlfti.c | 6 ++---- client/src/cmdlfvisa2000.c | 15 +++++---------- client/src/cmdlfzx8211.c | 9 +++------ client/src/graph.c | 18 ++++++++++++++++++ client/src/graph.h | 3 +++ tools/pm3_tests.sh | 1 + 9 files changed, 39 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceef461b4..1dcb9a79c 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 `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 411515da9..979ecc31b 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -2778,8 +2778,7 @@ static int try_detect_modulation(void) { clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) CmdLtrim("-i 160"); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS)) { @@ -2791,8 +2790,7 @@ static int try_detect_modulation(void) { tests[hits].carrier = GetPskCarrier(false); } //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); } } diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index bf8186d73..26fb3d83f 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -1609,8 +1609,7 @@ static bool check_chiptype(bool getDeviceData) { } //Save the state of the Graph and Demod Buffers - buffer_savestate_t saveState_gb = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState_gb.offset = g_GridOffset; + buffer_savestate_t saveState_gb = save_graphbuffer(); buffer_savestate_t saveState_db = save_buffer8(g_DemodBuffer, g_DemodBufferLen); saveState_db.clock = g_DemodClock; saveState_db.offset = g_DemodStartIdx; @@ -1683,12 +1682,12 @@ static bool check_chiptype(bool getDeviceData) { PrintAndLogEx(INFO, "Couldn't identify a chipset"); out: - restore_buffer8(saveState_db, g_DemodBuffer); + // the detections above demodulate, so the length comes back with the contents + g_DemodBufferLen = restore_buffer8(saveState_db, g_DemodBuffer); g_DemodClock = saveState_db.clock; g_DemodStartIdx = saveState_db.offset; - restore_bufferS32(saveState_gb, g_GraphBuffer); - g_GridOffset = saveState_gb.offset; + restore_graphbuffer(saveState_gb); return retval; } diff --git a/client/src/cmdlfti.c b/client/src/cmdlfti.c index 17d843a7c..57965d8d2 100644 --- a/client/src/cmdlfti.c +++ b/client/src/cmdlfti.c @@ -89,8 +89,7 @@ int demodTI(bool verbose) { 1, 1, 1, 1, 1, 1, 1, 1 }; - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); int lowLen = ARRAYLEN(LowTone); int highLen = ARRAYLEN(HighTone); @@ -278,8 +277,7 @@ int demodTI(bool verbose) { out: if (retval != PM3_SUCCESS) { - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); } return retval; diff --git a/client/src/cmdlfvisa2000.c b/client/src/cmdlfvisa2000.c index 092f38e30..93e8ff466 100644 --- a/client/src/cmdlfvisa2000.c +++ b/client/src/cmdlfvisa2000.c @@ -84,8 +84,7 @@ static uint8_t visa_parity(uint32_t id) { //see ASKDemod for what args are accepted int demodVisa2k(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); //CmdAskEdgeDetect(""); @@ -93,8 +92,7 @@ int demodVisa2k(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -109,8 +107,7 @@ int demodVisa2k(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); @@ -128,8 +125,7 @@ int demodVisa2k(bool verbose) { // test checksums if (chk != calc) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 checksum (%s) %x - %x\n", _RED_("fail"), chk, calc); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } // parity @@ -137,8 +133,7 @@ int demodVisa2k(bool verbose) { uint8_t chk_par = (raw3 & 0xFF0) >> 4; if (calc_par != chk_par) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 parity (%s) %x - %x\n", _RED_("fail"), chk_par, calc_par); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } PrintAndLogEx(SUCCESS, "Visa2000 - Card " _GREEN_("%u") ", Raw: %08X%08X%08X", raw2, raw1, raw2, raw3); diff --git a/client/src/cmdlfzx8211.c b/client/src/cmdlfzx8211.c index 793cc3d54..00e19d152 100644 --- a/client/src/cmdlfzx8211.c +++ b/client/src/cmdlfzx8211.c @@ -41,8 +41,7 @@ static int CmdHelp(const char *Cmd); // see ASKDemod for what args are accepted int demodzx(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // CmdAskEdgeDetect(""); @@ -50,8 +49,7 @@ int demodzx(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -66,8 +64,7 @@ int demodzx(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); diff --git a/client/src/graph.c b/client/src/graph.c index 80c1e4dc0..8df84d829 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -648,3 +648,21 @@ size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest) { return index; } + +// Save/restore the graph buffer as a unit: contents, length and grid offset. +// A caller that drops restore_bufferS32()'s return leaves g_GraphTraceLen short. +buffer_savestate_t save_graphbuffer(void) { + buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); + saveState.offset = g_GridOffset; + return saveState; +} + +void restore_graphbuffer(buffer_savestate_t saveState) { + size_t len = restore_bufferS32(saveState, g_GraphBuffer); + if (len == 0) { + // nothing was restored, so leave the buffer and its length alone + return; + } + g_GraphTraceLen = len; + g_GridOffset = saveState.offset; +} diff --git a/client/src/graph.h b/client/src/graph.h index 6f0822f96..1a46d6362 100644 --- a/client/src/graph.h +++ b/client/src/graph.h @@ -67,6 +67,9 @@ size_t restore_buffer32(buffer_savestate_t saveState, uint32_t *dest); size_t restore_bufferS32(buffer_savestate_t saveState, int32_t *dest); size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest); +buffer_savestate_t save_graphbuffer(void); +void restore_graphbuffer(buffer_savestate_t saveState); + #define MAX_GRAPH_TRACE_LEN (40000 * 32) #define GRAPH_SAVE 1 #define GRAPH_RESTORE 0 diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index a63279319..b0f257ab6 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -468,6 +468,7 @@ while true; do if ! CheckExecute "data qrcode invalid hex" "$CLIENTBIN -c 'data qrcode -d zz' 2>&1" "QR data must contain only hex characters"; then break; fi if ! CheckExecute "data qrcode odd hex" "$CLIENTBIN -c 'data qrcode -d a' 2>&1" "QR data must contain an even number of hex digits"; then break; fi if ! CheckExecute "data qrcode spaced hex" "$CLIENTBIN -c 'data qrcode -d \"aa bb\"' 2>&1" "Spaces are not supported; encode a space byte as 20"; then break; fi + if ! CheckExecute "data modulation keeps trace" "$CLIENTBIN -c 'data load -f traces/lf_Q5_mod-psk1-32-4.pm3; data modulation; data autocorr -w 99999'" "smaller than trace \\( 20000 samples \\)"; then break; fi if ! CheckExecute "mfu pwdgen test" "$CLIENTBIN -c 'hf mfu pwdgen --test'" "Selftest ok"; then break; fi if ! CheckExecute "mfu keygen test" "$CLIENTBIN -c 'hf mfu keygen --uid 11223344556677'" "80 B1 C2 71 D8 A0"; then break; fi if ! CheckExecute "jooki encode test" "$CLIENTBIN -c 'hf jooki encode --test'" "04 28 F4 DA F0 4A 81 \( ok \)"; then break; fi From bdc4828e0fe6f7c2c48a4edcedb1832006e841f2 Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 02:19:13 -0700 Subject: [PATCH 13/26] lf t55xx writetest: read each block three times and name how it differs One read cannot see the fault this suite is most useful for. A block that comes back silently wrong on some reads and right on others scores the same as one that is simply wrong, and the same as one that is fine. Read each block three times and mark disagreement between them as `unstable`. Where a block is wrong the same way every time, name it: `rol1`, `ror5`, `inverted`, `inv+ror2`, `shr1`. The kind matters. A rotation says the word boundary moved, an inversion says psk picked the opposite phase, and a shift says a demodulation opened a bit early and padded with zero - three different faults that want three different fixes, and all of them previously reported as "block 3,4 bad". Measured on a T5577 over the 21 PSK1 configurations, this turns 56 fields of "bad" into 56 marked unstable, and on a build that has since fixed part of it, into 24 rotations whose size tracks the bit rate - ror5 at RF/32, ror4 at RF/40, ror2 at RF/100 - which is a fixed sample offset rather than noise, and says where to look. Block 1 is 00000000, which equals all of its own rotations, so a rotated read of it cannot be told from a correct one. Noted in the header rather than changed, since the payload is the suite's own choice. Also corrects the header, which described block 2 as ffffffff where the script writes aa5500ff. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + .../luascripts/tests/lf_t55xx_writetest.lua | 96 +++++++++++++++++-- 2 files changed, 87 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceef461b4..ea9d3b1dd 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] +- Changed `tests/lf_t55xx_writetest.lua` - reads each block three times and names how a bad read differs (`rol1`, `ror5`, `inverted`, `shr1`) instead of only pass/fail (@mfcarroll) - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) diff --git a/client/luascripts/tests/lf_t55xx_writetest.lua b/client/luascripts/tests/lf_t55xx_writetest.lua index 436846bc0..05251def2 100644 --- a/client/luascripts/tests/lf_t55xx_writetest.lua +++ b/client/luascripts/tests/lf_t55xx_writetest.lua @@ -16,7 +16,7 @@ A strict T55x7 test suite: lf t55xx wipe lf t55xx write -b 1 -d 00000000 - lf t55xx write -b 2 -d ffffffff + lf t55xx write -b 2 -d aa5500ff lf t55xx write -b 3 -d 80000000 lf t55xx write -b 4 -d 00000001 @@ -24,6 +24,14 @@ Each row names the configuration word, what it means, what `lf t55xx detect` made of it and how many of the four data blocks read back intact. Markers are also written into the session log ( `rem [ERR:...]` and `rem [SUMMARY:...]` ) +Every block is read three times. A block that reads back differently between +those is marked `unstable`, which is the fault a single read cannot see: the +value is silently wrong rather than missing. A block that is wrong the same way +each time is named where it can be - `rol1`, `ror5`, `inverted`, `shr1` - because +a rotation points at the word boundary and an inversion at psk phase, and the two +want different fixes. Block 1 is `00000000`, which is equal to all of its own +rotations, so a rotated read of it cannot be told from a correct one. + Note: that the card is wiped before each modulation. Needs a T5577 in the field. @@ -161,30 +169,98 @@ local function prepare() return true end +-- a block is read this many times, so that a value which is silently wrong on +-- only some reads is not mistaken for one that is right +local READS = 3 + +local function rol32(v, n) + n = n % 32 + if n == 0 then return v end + return ((v << n) | (v >> (32 - n))) & 0xFFFFFFFF +end + --- --- Read blocks 1-4 back. Returns how many matched and a short note naming the --- ones that did not. +-- Name how `got` differs from `want`, when it can be named. A rotation says the +-- word boundary moved, an inversion says psk picked the opposite phase, and a +-- shift says a demodulation opened a bit early and padded with zero - different +-- faults wanting different fixes, so worth telling apart. A word equal to all of +-- its own rotations carries no boundary information and only gets 'differs'. +local function classify(want, got) + + if got == want then return 'ok' end + + if rol32(want, 1) == want then return 'differs' end + + for n = 1, 31 do + if rol32(want, n) == got then + return (n <= 16) and ('rol' .. n) or ('ror' .. (32 - n)) + end + end + + if (want ~ 0xFFFFFFFF) == got then return 'inverted' end + + for n = 1, 31 do + if (rol32(want, n) ~ 0xFFFFFFFF) == got then + return 'inv+' .. ((n <= 16) and ('rol' .. n) or ('ror' .. (32 - n))) + end + end + + for n = 1, 8 do + if ((want >> n) & 0xFFFFFFFF) == got then return 'shr' .. n end + if ((want << n) & 0xFFFFFFFF) == got then return 'shl' .. n end + end + + return 'differs' +end + +--- +-- Read blocks 1-4 back, READS times each. Returns how many matched on every +-- read and a short note naming what went wrong with the ones that did not. local function read_back(config) local good, bad = 0, {} for block, want in ipairs(DATA_BLOCKS) do - local data = core.t55xx_readblock(block, '0', '0', '') - local got = data and ('%08X'):format(data) or '' + local wantv = tonumber(want, 16) + local seen, first, stable = {}, nil, true - if got:lower() == want:lower() then + for _ = 1, READS do + local data = core.t55xx_readblock(block, '0', '0', '') + local v = data and (data & 0xFFFFFFFF) or nil + table.insert(seen, v) + if first == nil then + first = v + elseif v ~= first then + stable = false + end + end + + if stable and first == wantv then good = good + 1 else - table.insert(bad, tostring(block)) - core.console(format('rem [ERR:READ:%s:%d] block %d: read %s instead of %s', - config, block, block, got, want), false, true) + local what + if stable == false then + what = 'unstable' + else + what = classify(wantv, first) + end + + table.insert(bad, format('b%d %s', block, what)) + + local reads = {} + for _, v in ipairs(seen) do + table.insert(reads, v and ('%08X'):format(v) or '----') + end + core.console(format('rem [ERR:READ:%s:%d] block %d: %s, wanted %s, read %s', + config, block, block, what, want, + table.concat(reads, ' ')), false, true) end end local note = '' if #bad > 0 then - note = 'block ' .. table.concat(bad, ',') .. ' bad' + note = table.concat(bad, ' ') end return good, note end From 1ebcf225f12e418cc4d72e07e554ef74f54066cf Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Wed, 9 Sep 2026 21:02:09 -0700 Subject: [PATCH 14/26] lf nrz demod: start the bitstream at the first edge The samples before the first level change were counted as bits, and where no edge arrives inside ten clocks the long-run flush fired first and invented ten of them out of the quiet lead-in. The count sat on a rounding boundary, so one sample of jitter in that edge added or dropped a leading bit and rotated the rest of the word - while startIdx, derived from the same count, held i % clk and could name no sample. A level change can only fall on a bit boundary, so start there and report it. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + common/lfdemod.c | 25 +++++++++++++++++++------ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceef461b4..d79d185ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) - Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) - Fixed `lf t55xx detect` - the automatic detect after a block 0 write reported a password that was never supplied (@iceman1001) diff --git a/common/lfdemod.c b/common/lfdemod.c index 33ee616cc..6c742a0d4 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -1902,18 +1902,31 @@ int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, const int *invert, int *s if (dest[i] <= low) bit = 0; dest[i] = bit; } - //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) + // start on the first level change: it is the earliest sample known to be a + // bit boundary. counting the samples before it as bits rotated the stream + // whenever that edge moved by one, and left startIdx naming no sample size_t lastBit = 0; size_t numBits = 0; + bool anchored = false; for (i = 21; i < *size - 20; i++) { + + bool edge = (dest[i] != dest[i - 1]); + + if (anchored == false) { + if (edge == false) { + continue; + } + *startIdx = (int)i; + if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); + lastBit = i - 1; + anchored = true; + continue; + } + //if transition detected or large number of same bits - store the passed bits - if (dest[i] != dest[i - 1] || (i - lastBit) == (10 * *clk)) { + if (edge || (i - lastBit) == (10 * *clk)) { memset(dest + numBits, dest[i - 1] ^ *invert, (i - lastBit + (*clk / 4)) / *clk); numBits += (i - lastBit + (*clk / 4)) / *clk; - if (lastBit == 0) { - *startIdx = i - (numBits * *clk); - if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); - } lastBit = i - 1; } } From e206d748a2b1bec7c1d1acec1d5a84f9105851b7 Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 01:33:44 -0700 Subject: [PATCH 15/26] lf fsk demod: do not fabricate a bit from a leading run aggregate_bits sized each run of like waves in bits and then forced a zero to one. That is right mid-stream, where a run rounding to nothing would drop a bit the tag did send. On the leading run it is wrong: a single subcarrier wave is about fchigh samples against a bit period of clk, so it rounds to no bits and was made into one anyway - a bit the tag never sent, shifting every bit after it and dragging startIdx back by most of a bit period. Skip a leading run that rounds to nothing and let the next transition be first. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + common/lfdemod.c | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d79d185ba..7d7ab0ebd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) - Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) - Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) diff --git a/common/lfdemod.c b/common/lfdemod.c index 6c742a0d4..57fadc344 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -2051,6 +2051,13 @@ static size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t in // 0->1 crossing n = (n * fchigh + hclk) / clk; + // A leading run that rounds to no bits is lead-in, not data. Forcing it to one fabricates + // a bit and shifts the word; mid-stream a zero would lose a bit the tag did send. + if (n == 0 && numBits == 0) { + lastval = dest[i]; + continue; + } + if (n == 0) n = 1; From 907f21b8cb11e6708b6e64553f5eb01b6263c0f0 Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 01:42:01 -0700 Subject: [PATCH 16/26] lf psk demod: do not accept a phase shift from the lead-in The emitted bit is the running phase, so a shift accepted before the tag answers toggles curPhase once too often and the rest of the word comes back complemented. pskFindFirstPhaseShift judged its first measured length, but waveStart starts as wherever the caller began looking - that length is part of a wave, not a wave, and any gap beating fc was taken as a shift. Baseline on the first peak instead. pskRawDemod_ext separately trusted a shift under one bit period in; the clock is known by then, so look again from a bit period in. Both are needed - dropping either leaves one of the tags measured inverting on most reads. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + common/lfdemod.c | 30 +++++++++++++++++++++--------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d7ab0ebd..49b7e0311 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf psk demod` - lead-in samples were accepted as a phase shift, complementing the rest of the word (@mfcarroll) - Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) - Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) diff --git a/common/lfdemod.c b/common/lfdemod.c index 57fadc344..77c3f6308 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -547,13 +547,16 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP uint16_t avgWaveVal = 0, lastAvgWaveVal; size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave; + // waveStart starts as wherever the caller began looking, so the first length is part of a wave, + // not a wave, and judging it accepts a shift that is not there. Baseline on the first peak. + bool wave_from_peak = false; for (; i < loopCnt; i++) { // find peak // was "samples[i] + fc" but why? must have been used to weed out some wave error... removed.. if (samples[i] < samples[i + 1] && samples[i + 1] >= samples[i + 2]) { waveEnd = i + 1; if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %zu, waveStart: %zu", waveEnd, waveStart); waveLenCnt = waveEnd - waveStart; - if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack + if (wave_from_peak && waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack lastAvgWaveVal = avgWaveVal / (waveLenCnt); firstFullWave = waveStart; *fullWaveLen = waveLenCnt; @@ -562,6 +565,7 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP return firstFullWave; } waveStart = i + 1; + wave_from_peak = true; avgWaveVal = 0; } avgWaveVal += samples[i + 2]; @@ -2161,14 +2165,22 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, const int *invert, i = findModStart(dest, *size, fc); //find first phase shift firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen); - if (firstFullWave == 0) { - // no phase shift detected - could be all 1's or 0's - doesn't matter where we start - // so skip a little to ensure we are past any Start Signal - firstFullWave = 160; - memset(dest, curPhase, firstFullWave / *clock); - } else { - memset(dest, curPhase ^ 1, firstFullWave / *clock); - } + } + + // A first shift less than a bit period in is lead-in, not data. Counting it toggles curPhase + // once too often, and the emitted bit is the running phase, so the rest of the word inverts. + const size_t bit_period = (size_t)(*clock); + if (firstFullWave != 0 && firstFullWave < bit_period) { + curPhase = *invert; + fullWaveLen = 0; + firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, bit_period, fc, &fullWaveLen); + } + + if (firstFullWave == 0) { + // no phase shift detected - could be all 1's or 0's - doesn't matter where we start + // so skip a little to ensure we are past any Start Signal + firstFullWave = 160; + memset(dest, curPhase, firstFullWave / *clock); } else { memset(dest, curPhase ^ 1, firstFullWave / *clock); } From 0586b8a1c31f10e71847f00a0d773edd8ebe913c Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 01:42:01 -0700 Subject: [PATCH 17/26] lf t55xx detect: settle the block 0 rotation with the broadcast period A block read repeats one 32 bit word, so every offset yields a rotation and more than one can pass the structural checks. A T5577 in direct/nrz carried both 00080040, the word on the tag, and 00080001, its ror19 - both master key 0, reserved 0, RF/32, direct. test() answers with the first hit from a fixed floor, so which one detect reported was scan order rather than evidence. No structural check separates them: every bit of block 0 is a real field, and the three the scan skips are otp, fast write and inverse data, all settable. The tag can, though - maxblock has to account for what regular read mode cycles through. So measure the broadcast period and keep the rotation that agrees, reusing the constraint printConfiguration already applies to the psk2/psk3 pre-images. Costs one acquisition, and only when the reading is ambiguous. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + client/src/cmdlft55xx.c | 246 ++++++++++++++++++++++++++++++---------- 2 files changed, 187 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49b7e0311..8f8272e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf t55xx detect` - the block 0 rotation was picked by scan order; the measured broadcast period now settles it (@mfcarroll) - Fixed `lf psk demod` - lead-in samples were accepted as a phase shift, complementing the rest of the word (@mfcarroll) - Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) - Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 278035352..49e7e2433 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -61,6 +61,8 @@ static bool t55xx_psk3_probe(bool usepwd, uint32_t password, uint8_t downlink_mo static uint8_t t55xx_measure_broadcast_blocks(bool usepwd, uint32_t password, uint8_t downlink_mode); static uint8_t t55xx_measure_broadcast_blocks_once(bool usepwd, uint32_t password, uint8_t downlink_mode); static size_t t55xx_psk3_resolve(uint8_t nblk, uint32_t *only); +static bool t55xx_block0_rotation_ambiguous(void); +static bool t55xx_resolve_block0_rotation(uint8_t nblk); // Default configuration static t55xx_conf_block_t config = { @@ -1247,6 +1249,22 @@ static int CmdT55xxDetect(const char *Cmd) { } } + // Several rotations of the word can read as a configuration and detect takes the first the + // scan reaches. The broadcast period is the tag's own answer to which is real + bool rerotated = false; + + if (found && use_gb == false && t55xx_block0_rotation_ambiguous()) { + + if (nblk == 0) { + nblk = t55xx_measure_broadcast_blocks(config.usepwd, config.pwd, config.downlink_mode); + config.broadcast_blocks = nblk; + } + + if (nblk) { + rerotated = t55xx_resolve_block0_rotation(nblk); + } + } + if (found) { printConfiguration(config); @@ -1255,6 +1273,10 @@ static int CmdT55xxDetect(const char *Cmd) { PrintAndLogEx(SUCCESS, "Broadcast repeats every " _GREEN_("%u") " block(s), so maxblock is a multiple of %u", nblk, nblk); } + if (rerotated) { + PrintAndLogEx(SUCCESS, "Block 0 " _GREEN_("re-anchored") " - the first reading was a rotation the broadcast period contradicts"); + } + if (psk2_out) { PrintAndLogEx(SUCCESS, "psk2 " _RED_("ruled out") " - the psk2 reading of block 0 carries a maxblock contradicted by the broadcast"); } else if (favoured) { @@ -2565,6 +2587,167 @@ static void windows_build(t55_windows_t *w) { } } +// the checks a 32 bit word has to pass to be a configuration block for `mode` at +// `clk`, independent of where in a demodulation it was found +static bool t55xx_block0_plausible(uint32_t block0, uint8_t mode, uint8_t clk, int *fndBitRate) { + + uint8_t safer = (block0 >> 28) & 0x0F; //master key + uint8_t resv = (block0 >> 24) & 0x0F; //was 7 // should be only 4 bits if extended mode + // 2nibble must be zeroed. + + if (resv > 0x00) { + return false; + } + + // The master key is 0, or 6 or 9 to select extended mode + if (safer != 0x0 && safer != 0x6 && safer != 0x9) { + return false; + } + + int bitRate = (block0 >> 18) & 0x3F; //bit rate (includes extended mode part of rate) + uint8_t extend = (block0 >> 17) & 0x01; //bit 15 extended mode + uint8_t modread = (block0 >> 12) & 0x1F; + //pskcr = (block0 >> 10) & 0x03; //could check psk cr + //bit 24, 30, 31 are otp, fast write and inverse data - all settable, so no help here + + // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. + // Set with any other key the word is not a valid configuration + if (extend && safer != 0x6 && safer != 0x9) { + return false; + } + + //if extended mode + bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; + + if (extMode == false) { + + if (bitRate > 7) { + return false; + } + + if (testBitRate(bitRate, clk) == false) { + return false; + } + + } else { //extended mode bitrate = same function to calc bitrate as em4x05 + if (EM4x05_GET_BITRATE(bitRate) != clk) { + return false; + } + } + + //test modulation + if (testModulation(mode, modread) == false) { + return false; + } + + if (fndBitRate) { + *fndBitRate = bitRate; + } + return true; +} + +// true when the maxblock and sequence terminator in `block0` could have produced +// an `nblk` block broadcast period +static bool t55xx_block0_fits_period(uint32_t block0, uint8_t nblk) { + + // ST adds four bit periods per cycle, so a whole number of 32 + // bit blocks rules it out. leans on the measurement, not on + // config.ST, which the psk paths hardcode rather than detect + if (((block0 >> 3) & 1) != 0) { + return false; + } + + const uint8_t mb = (block0 >> 5) & 0x07; + return (mb != 0 && (mb % nblk) == 0); +} + +// how many distinct rotations of `block0` read as a configuration for `mode` at `clk`. more than +// one means detect's answer was scan order, not evidence. `nblk` 0 skips the period constraint +static size_t t55xx_block0_rotations(uint32_t block0, uint8_t mode, uint8_t clk, uint8_t nblk, uint32_t *only) { + + uint32_t seen[32] = {0}; + size_t n = 0; + + for (uint8_t r = 0; r < 32; r++) { + + const uint32_t v = (r == 0) ? block0 : ((block0 << r) | (block0 >> (32 - r))); + + if (t55xx_block0_plausible(v, mode, clk, NULL) == false) { + continue; + } + + if (nblk != 0 && t55xx_block0_fits_period(v, nblk) == false) { + continue; + } + + // a word that is its own rotation offers the same value twice + bool dup = false; + for (size_t i = 0; i < n; i++) { + if (seen[i] == v) { + dup = true; + break; + } + } + if (dup) { + continue; + } + + seen[n++] = v; + } + + if (n == 1 && only != NULL) { + *only = seen[0]; + } + return n; +} + +// the clock the detected bit rate names, for the rotation helpers above +static uint8_t t55xx_config_clock(void) { + static const uint8_t basic[] = {8, 16, 32, 40, 50, 64, 100, 128}; + return basic[config.bitrate & 0x07]; +} + +// more than one rotation of the detected block 0 reads as a configuration +static bool t55xx_block0_rotation_ambiguous(void) { + + if (config.Q5 || config.block0 == 0) { + return false; + } + + return (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), 0, NULL) > 1); +} + +// Settle which rotation is real with the tag's own broadcast period and re-anchor on it. Nothing +// surviving means the measurement disagrees with every reading, so leave the detected word alone +static bool t55xx_resolve_block0_rotation(uint8_t nblk) { + + uint32_t only = 0; + if (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), nblk, &only) != 1) { + return false; + } + + if (only == config.block0) { + return false; + } + + // measuring the period left a regular read in the demod buffer + if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, config.usepwd, config.pwd, config.downlink_mode) == false) { + return false; + } + + if (DecodeT55xxBlock() == false) { + return false; + } + + if (t55xx_stream_holds(only) == false) { + return false; + } + + // keep the offset t55xx_stream_holds just anchored + SetConfigWithBlock0Ex(only, config.offset, config.Q5); + return true; +} + static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, uint16_t start, uint16_t end, const t55_windows_t *w, uint16_t need, bool need_stride) { @@ -2581,58 +2764,8 @@ static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t cl continue; } - uint8_t safer = PackBits(si, 4, g_DemodBuffer); - si += 4; //master key - uint8_t resv = PackBits(si, 4, g_DemodBuffer); - si += 4; //was 7 & +=7+3 // should be only 4 bits if extended mode - // 2nibble must be zeroed. - - if (resv > 0x00) { - continue; - } - - // The master key is 0, or 6 or 9 to select extended mode - if (safer != 0x0 && safer != 0x6 && safer != 0x9) { - continue; - } - - int bitRate = PackBits(si, 6, g_DemodBuffer); - si += 6; //bit rate (includes extended mode part of rate) - uint8_t extend = PackBits(si, 1, g_DemodBuffer); - si += 1; //bit 15 extended mode - uint8_t modread = PackBits(si, 5, g_DemodBuffer); - si += 5 + 2 + 1; - //uint8_t pskcr = PackBits(si, 2, g_DemodBuffer); si += 2+1; //could check psk cr - //uint8_t nml01 = PackBits(si, 1, g_DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode - //uint8_t nml02 = PackBits(si, 2, g_DemodBuffer); si += 2; - - // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. - // Set with any other key the word is not a valid configuration - if (extend && safer != 0x6 && safer != 0x9) { - continue; - } - - //if extended mode - bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; - - if (extMode == false) { - - if (bitRate > 7) { - continue; - } - - if (testBitRate(bitRate, clk) == false) { - continue; - } - - } else { //extended mode bitrate = same function to calc bitrate as em4x05 - if (EM4x05_GET_BITRATE(bitRate) != clk) { - continue; - } - } - - //test modulation - if (testModulation(mode, modread) == false) { + int bitRate = 0; + if (t55xx_block0_plausible(PackBits(si, 32, g_DemodBuffer), mode, clk, &bitRate) == false) { continue; } @@ -2910,14 +3043,7 @@ int printConfiguration(t55xx_conf_block_t b) { if (b.broadcast_blocks) { size_t kept = 0; for (size_t i = 0; i < ncand; i++) { - const uint8_t mb = (cand[i] >> 5) & 0x07; - // ST adds four bit periods per cycle, so a whole number of 32 - // bit blocks rules it out. leans on the measurement, not on - // config.ST, which the psk paths hardcode rather than detect - if (((cand[i] >> 3) & 1) != 0) { - continue; - } - if (mb != 0 && (mb % b.broadcast_blocks) == 0) { + if (t55xx_block0_fits_period(cand[i], b.broadcast_blocks)) { cand[kept++] = cand[i]; } } From b0d5178c92673ea1ec5bd6a57a9c8265f4f7b28d Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Thu, 10 Sep 2026 03:05:30 -0700 Subject: [PATCH 18/26] lf t55xx detect: finish undoing the psk antenna-settle trim test_scan and t55xx_fallback_try drop 160 samples off the head of the capture before demodulating psk, then restore it. restore_bufferS32 copies the samples back and returns the length it put back, but no caller assigned that return, so g_GraphTraceLen stayed at the trimmed length for the rest of detect. That left the sample-space anchoring unable to engage. t55xx_demod_offset only resolves when config.anchor_tracelen equals g_GraphTraceLen; detect recorded 11840 while every block read acquires 12000, so the guard never matched and a dump fell back to config.offset - a bit index into a demod buffer that no longer exists, which is the case its own comment warns about. Over six instrumented dumps of a PSK1 RF/128 tag, one resolved and five did not; the one that resolved read block 0 correctly on the first try. A candidate found inside the trim was also measured 160 samples left of where a block read measures, so those anchors were out of frame even when the length happened to match. 160 samples is round(160 / clk) bits - 5 at RF/32, 1 at RF/128 - and a rotation of that size is what read-back was showing. Pair the trim with its undo so a third call site cannot pick up half of it, hold a bias while the capture is trimmed so a recorded anchor still names an untrimmed sample, and give the 160 one home. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 1 + client/src/cmdlft55xx.c | 50 ++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f8272e76..141acff11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) - Fixed `lf t55xx detect` - the block 0 rotation was picked by scan order; the measured broadcast period now settles it (@mfcarroll) +- Fixed `lf t55xx detect` - the psk antenna-settle trim left the graph 160 samples short, so the graph-sample anchor was discarded on most block reads (@mfcarroll) - Fixed `lf psk demod` - lead-in samples were accepted as a phase shift, complementing the rest of the word (@mfcarroll) - Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) - Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 49e7e2433..eb1006e90 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -82,6 +82,13 @@ static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; // Regular read mode cycles several blocks and a buffer loaded from a file could be either static bool s_block_read_capture = false; +// samples dropped from the head of a capture before psk demodulation +#define T55XX_PSK_SETTLE_TRIM 160 + +// non-zero while the capture is trimmed, so an anchor recorded inside the trim +// still names an untrimmed sample +static int32_t s_sample_bias = 0; + // A block read repeats one 32 bit word for as long as the field is on. // `offset` is a bit index into a demod buffer that no longer exists once the next acquisition lands, // and the demodulators do not all start on the same bit: @@ -90,16 +97,36 @@ static bool s_block_read_capture = false; static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { c->offset = offset; c->anchor_valid = (g_DemodClock > 0); - c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock); - c->anchor_tracelen = (int32_t)g_GraphTraceLen; + c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock) + s_sample_bias; + c->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; } // records a detect candidate against the demodulation that is loaded right now static void t55xx_record_hit(t55xx_conf_block_t *t) { t->block0 = PackBits(t->offset, 32, g_DemodBuffer); t->anchor_valid = (g_DemodClock > 0); - t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock); - t->anchor_tracelen = (int32_t)g_GraphTraceLen; + t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock) + s_sample_bias; + t->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; +} + +// skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) +static buffer_savestate_t t55xx_psk_trim_head(void) { + buffer_savestate_t st = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); + st.offset = g_GridOffset; + + char ltrim[16]; + snprintf(ltrim, sizeof(ltrim), "-i %d", T55XX_PSK_SETTLE_TRIM); + CmdLtrim(ltrim); + + s_sample_bias = T55XX_PSK_SETTLE_TRIM; + return st; +} + +static void t55xx_psk_untrim_head(buffer_savestate_t st) { + s_sample_bias = 0; + // restore_bufferS32 returns the length it put back; dropping it leaves the trim in place + g_GraphTraceLen = restore_bufferS32(st, g_GraphBuffer); + g_GridOffset = st.offset; } // the bit offset to read a block at in the demod buffer loaded right now @@ -1617,9 +1644,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l if (mod == PM3_MOD_PSK) { - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); for (int inv = 0; inv < 2; inv++) { if (PSKDemod(fitclk, inv, PM3_T55_FALLBACK_MAXERR, false) != PM3_SUCCESS) { @@ -1653,8 +1678,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l } } - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); if (*hits == before && coherent_ok) { t55xx_psk_coherent(fitclk, clk, tests, hits, downlink_mode); @@ -2002,10 +2026,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; @@ -2041,8 +2062,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 } // inverse waves does not affect this demod //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); // t55xx_search_config_psk(g_GraphBuffer, 1); // t55xx_search_config_psk(g_GraphBuffer, 2); } From 2cd5285cb2e693b1f8c0f19e60fa39cb6c713d7e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 10:38:57 +0200 Subject: [PATCH 19/26] hf mfdes chk: track found keys per application foundKeys was indexed [keytype][keyno] with no AID dimension and was never reset between applications, so a key number recovered on one AID was skipped without a single auth attempt on every later AID. On a card with AES key 00 set on two apps, only the first one was ever reported. Give every application its own desfire_app_keys_t and hand that to the checker. Saving to json now uses a new 'mfdes v2' format keyed by AID, with a loader that round-trips it; v1 is kept for existing files. Also in the same path: - one auth error below 7 broke out of the key number loop, abandoning every remaining key number for the AID. Only an algo mismatch (4, 50, 51) skips the key type now; an invalid key number (3) skips just that key number, and a transmit error retries after a reselect - 3TDEA keys were stored 16 bytes wide and written out as 24 - -k with a 24 byte key was rejected by the parser, making the 24 byte branch unreachable - DesfireGetAIDList() wrote unbounded into a 78 byte app_ids buffer Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + client/src/cmdhfmfdes.c | 312 ++++++++++++++++++++-------------------- client/src/fileutils.c | 106 ++++++++++++++ client/src/fileutils.h | 10 ++ include/desfire.h | 12 ++ 5 files changed, 284 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15871b6f8..e0bcd904f 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 mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) - Fixed `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) - Changed `tests/lf_t55xx_writetest.lua` - reads each block three times and names how a bad read differs (`rol1`, `ror5`, `inverted`, `shr1`) instead of only pass/fail (@mfcarroll) - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 6d05b8b50..6aea02817 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -57,6 +57,8 @@ #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 +// how many errors in a row from the card before we give up on a key number +#define MFDES_CHK_MAX_ERRORS 10 #define MFDES_BRUTEAID_RESELECT_ATTEMPTS 5 #define MFDES_BRUTEAID_RESELECT_WAIT_MS 200 #define MFDES_BRUTEAID_MAD_START 0xF0000FU @@ -1272,14 +1274,95 @@ static void DesFill2bPattern( (*startPattern)++; } +// Try every key in `keyList` against every key number the `usedkeys` map marks as +// in use on the currently selected application. Found keys are stored in `found`. +// Returns PM3_SUCCESS, or an error when the application can no longer be selected. +static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, + DesfireSecureChannel secureChannel, + uint32_t curaid, + DesfireCryptoAlgorithm keytype, + const char *keytypestr, + const uint8_t *keyList, size_t keyListStride, uint32_t keyListLen, + const int *usedkeys, + desfire_app_keys_t *found, + bool *result) { + + size_t keylen = desfire_get_key_length(keytype); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (usedkeys[keyno] != 1 || found->keys[keytype][keyno][0] != 0) { + continue; + } + + size_t errcount = 0; + + for (uint32_t curkey = 0; curkey < keyListLen; curkey++) { + + const uint8_t *key = &keyList[curkey * keyListStride]; + + DesfireSetKeyNoClear(dctx, keyno, keytype, (uint8_t *)key); + + int res = DesfireAuthenticate(dctx, secureChannel, false); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "AID 0x%06X, Found %s Key %02u... " _GREEN_("%s"), + curaid, keytypestr, keyno, sprint_hex_inrow(key, keylen)); + + found->keys[keytype][keyno][0] = 0x01; + memcpy(&found->keys[keytype][keyno][1], key, keylen); + *result = true; + break; + } + + // anything below 7 means the card gave up before the crypto stage, + // the channel is gone and the application has to be selected again + if (res < 7) { + DropField(); + int selres = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (selres != PM3_SUCCESS) { + return selres; + } + } + + // 4 - answer length doesn't match the algo + // 50 - PICC didn't answer AES, 51 - PICC didn't answer LRP + // the application doesn't use this key type, skip the rest of it + if (res == 4 || res == 50 || res == 51) { + return PM3_SUCCESS; + } + + // 3 - invalid key number. Every key fails the same way, but the + // remaining key numbers are still worth checking + if (res == 3) { + break; + } + + // 1, 2, 5, 6 - transmit or local crypto error. Carry on with the next + // key and only give up on this key number after a run of them + if (res < 7) { + errcount++; + if (errcount > MFDES_CHK_MAX_ERRORS) { + if (g_debugMode) { + PrintAndLogEx(DEBUG, "AID 0x%06X, %s key %02u... too many errors from card, skipping", curaid, keytypestr, keyno); + } + break; + } + } else { + errcount = 0; + } + } + } + + return PM3_SUCCESS; +} + static int AuthCheckDesfire(DesfireContext_t *dctx, DesfireSecureChannel secureChannel, const uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], uint32_t deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], uint32_t aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], uint32_t k3kkeyListLen, - uint8_t cmdKdfAlgo, uint8_t kdfInputLen, uint8_t *kdfInput, - uint8_t foundKeys[4][0xE][24 + 1], + desfire_app_keys_t *found, bool *result, bool verbose) { @@ -1292,7 +1375,7 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, return PM3_ESOFT; } - int usedkeys[0xF] = {0}; + int usedkeys[DESFIRE_MAX_KEY_COUNT + 1] = {0}; bool des = false; bool tdes = false; bool aes = false; @@ -1343,11 +1426,11 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, usedkeys[fileList[i].fileSettings.chAccess] = 1; } } else { - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) usedkeys[i] = 1; } } else { - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) usedkeys[i] = 1; } } @@ -1355,141 +1438,41 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, if (verbose) { PrintAndLogEx(INFO, "Check: %s %s %s %s " NOLF, (des) ? "DES" : "", (tdes) ? "2TDEA" : "", (k3kdes) ? "3TDEA" : "", (aes) ? "AES" : ""); PrintAndLogEx(NORMAL, "keys: " NOLF); - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) if (usedkeys[i] == 1) PrintAndLogEx(NORMAL, "%02x " NOLF, i); PrintAndLogEx(NORMAL, ""); } - bool badlen = false; + const struct { + bool check; + DesfireCryptoAlgorithm keytype; + const char *name; + const uint8_t *list; + size_t stride; + uint32_t len; + } checks[] = { + { des, T_DES, "DES", (const uint8_t *)deskeyList, sizeof(deskeyList[0]), deskeyListLen }, + { tdes, T_3DES, "2TDEA", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { aes, T_AES, "AES", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { k3kdes, T_3K3DES, "3TDEA", (const uint8_t *)k3kkeyList, sizeof(k3kkeyList[0]), k3kkeyListLen }, + }; - if (des) { + for (size_t i = 0; i < ARRAYLEN(checks); i++) { - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { + if (checks[i].check == false) { + continue; + } - if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < deskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_DES, deskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); - foundKeys[0][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[0][keyno][1], deskeyList[curkey], 8); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } + res = AuthCheckDesfireKeyType(dctx, secureChannel, curaid, checks[i].keytype, checks[i].name, + checks[i].list, checks[i].stride, checks[i].len, + usedkeys, found, result); + if (res != PM3_SUCCESS) { + DropField(); + return res; } } - if (tdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3DES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 2TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[1][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[1][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (aes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_AES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[2][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[2][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (k3kdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < k3kkeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3K3DES, k3kkeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(k3kkeyList[curkey], 24)); - foundKeys[3][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[3][keyno][1], k3kkeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - - if (badlen == true) { - break; - } - } - } - } DropField(); return PM3_SUCCESS; } @@ -1502,21 +1485,21 @@ static int CmdHF14aDesChk(const char *Cmd) { uint32_t deskeyListLen = 0; uint32_t aeskeyListLen = 0; uint32_t k3kkeyListLen = 0; - uint8_t foundKeys[4][0xE][24 + 1] = {{{0}}}; CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes chk", "Checks keys with MIFARE DESFire card.", - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456\n" - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card\n" - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456\n" - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`\n" - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00"); + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card\n" + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456\n" + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`\n" + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00\n" + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456\n" + ); void *argtable[] = { arg_param_begin, arg_str0(NULL, "aid", "", "Use specific AID (3 hex bytes, big endian)"), - arg_str0("k", "key", "", "Key for checking (HEX 16 bytes)"), + arg_str0("k", "key", "", "Key for checking (HEX 8, 16 or 24 bytes)"), arg_str0("f", "file", "", "Filename of dictionary"), arg_lit0(NULL, "pattern1b", "Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)"), arg_lit0(NULL, "pattern2b", "Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)"), @@ -1536,7 +1519,7 @@ static int CmdHF14aDesChk(const char *Cmd) { swap24(aid); - uint8_t vkey[16] = {0}; + uint8_t vkey[MAX_KEY_LEN] = {0}; int vkeylen = 0; CLIGetHexWithReturn(ctx, 2, vkey, &vkeylen); @@ -1548,7 +1531,7 @@ static int CmdHF14aDesChk(const char *Cmd) { memcpy(&aeskeyList[aeskeyListLen], vkey, 16); aeskeyListLen++; } else if (vkeylen == 24) { - memcpy(&k3kkeyList[k3kkeyListLen], vkey, 16); + memcpy(&k3kkeyList[k3kkeyListLen], vkey, 24); k3kkeyListLen++; } else { PrintAndLogEx(ERR, "Specified key must have 8, 16 or 24 bytes length."); @@ -1640,7 +1623,7 @@ static int CmdHF14aDesChk(const char *Cmd) { } bool result = false; - uint8_t app_ids[78] = {0}; + uint8_t app_ids[DESFIRE_MAX_APP_COUNT * 3] = {0}; size_t app_ids_len = 0; clearCommandBuffer(); @@ -1662,13 +1645,23 @@ static int CmdHF14aDesChk(const char *Cmd) { } - res = DesfireGetAIDList(&dctx, app_ids, &app_ids_len); + uint8_t aidbuf[250] = {0}; + size_t aidbuflen = 0; + res = DesfireGetAIDList(&dctx, aidbuf, &aidbuflen); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); DropField(); return PM3_ESOFT; } + if (aidbuflen > sizeof(app_ids)) { + PrintAndLogEx(WARNING, "Card returned " _YELLOW_("%zu") " applications, only checking the first " _YELLOW_("%d"), aidbuflen / 3, DESFIRE_MAX_APP_COUNT); + aidbuflen = sizeof(app_ids); + } + + memcpy(app_ids, aidbuf, aidbuflen); + app_ids_len = aidbuflen; + if (aidlength != 0) { memcpy(&app_ids[0], aid, 3); app_ids_len = 3; @@ -1730,11 +1723,24 @@ static int CmdHF14aDesChk(const char *Cmd) { } } + desfire_keys_dump_t *dump = calloc(1, sizeof(desfire_keys_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + DropField(); + return PM3_EMALLOC; + } + dump->appcount = app_ids_len / 3; + for (uint32_t x = 0; x < app_ids_len / 3; x++) { uint32_t curaid = (app_ids[x * 3] & 0xFF) + ((app_ids[(x * 3) + 1] & 0xFF) << 8) + ((app_ids[(x * 3) + 2] & 0xFF) << 16); PrintAndLogEx(INFO, "Checking aid " _YELLOW_("%06X"), curaid); + // found keys are tracked per application. A key number recovered on one + // AID must not stop us from checking the same key number on the next one + desfire_app_keys_t *found = &dump->app[x]; + found->aid = curaid; + bool loadedAllKeys = false; size_t desReadStart = 0; size_t desReadEnd = 1; @@ -1795,7 +1801,11 @@ static int CmdHF14aDesChk(const char *Cmd) { loadedAllKeys = true; } - res = AuthCheckDesfire(&dctx, secureChannel, &app_ids[x * 3], deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, cmdKDFAlgo, kdfInputLen, kdfInput, foundKeys, &foundKeyThisRound, verbose); + res = AuthCheckDesfire(&dctx, secureChannel, &app_ids[x * 3], + deskeyList, deskeyListLen, + aeskeyList, aeskeyListLen, + k3kkeyList, k3kkeyListLen, + found, &foundKeyThisRound, verbose); if (res == PM3_EOPABORTED) { break; } @@ -1829,31 +1839,19 @@ static int CmdHF14aDesChk(const char *Cmd) { uint8_t sel_1813 = 0; if (WaitForIso14aReply(&resp, 2500, NULL, &sel_1813) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply"); + free(dump); return PM3_ETIMEOUT; } - iso14a_card_select_t card; - memcpy(&card, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); - uint64_t select_status = sel_1813; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - - uint8_t data[10 + 1 + 2 + 1 + 256 + (4 * 0xE * (24 + 1))] = {0}; - uint8_t atslen = 0; if (select_status == 1 || select_status == 2) { - memcpy(data, card.uid, card.uidlen); - data[10] = card.sak; - data[11] = card.atqa[1]; - data[12] = card.atqa[0]; - atslen = card.ats_len; - data[13] = atslen; - memcpy(&data[14], card.ats, atslen); + memcpy(&dump->card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); } - // length: UID(10b)+SAK(1b)+ATQA(2b)+ATSlen(1b)+ATS(atslen)+foundKeys[2][64][AES_KEY_LEN + 1] - memcpy(&data[14 + atslen], foundKeys, 4 * 0xE * (24 + 1)); - saveFileJSON((char *)jsonname, jsfMfDesfireKeys, data, 0xE, NULL); + saveFileJSON((char *)jsonname, jsfMfDesfireKeys_v2, (uint8_t *)dump, sizeof(desfire_keys_dump_t), NULL); } + free(dump); DropField(); return PM3_SUCCESS; } diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 0763efc7a..42a98f3f2 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -982,6 +982,53 @@ int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, } break; } + case jsfMfDesfireKeys_v2: { + + // key lengths and names, indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + desfire_keys_dump_t *dump = (desfire_keys_dump_t *)(void *)data; + + JsonSaveStr(root, "FileType", "mfdes v2"); + + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", &dump->card_info.sak, 1); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", dump->card_info.atqa, 2); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", dump->card_info.ats, dump->card_info.ats_len); + } + } + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_app_keys_t *app = &dump->app[i]; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (app->keys[algo][keyno][0] == 0) { + continue; + } + + snprintf(path, sizeof(path), "$.Applications.%06X.%s.%u.Key", + app->aid, algo_name[algo], keyno); + + JsonSaveBufAsHexCompact(root, path, &app->keys[algo][keyno][1], algo_keylen[algo]); + } + } + } + break; + } case jsfCustom: { (*callback)(root); break; @@ -2700,6 +2747,65 @@ int loadFileJSONex(const char *preferredName, void *data, size_t maxdatalen, siz goto out; } + if (!strcmp(ctype, "mfdes v2")) { + + if (maxdatalen < sizeof(desfire_keys_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: maxdatalen=%zu, need %zu for a mfdes v2 dump", maxdatalen, sizeof(desfire_keys_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + JsonLoadBufAsHex(root, "$.Card.UID", udata.mfdes->card_info.uid, sizeof(udata.mfdes->card_info.uid), &len); + udata.mfdes->card_info.uidlen = len; + JsonLoadBufAsHex(root, "$.Card.SAK", &udata.mfdes->card_info.sak, 1, &len); + JsonLoadBufAsHex(root, "$.Card.ATQA", udata.mfdes->card_info.atqa, 2, &len); + JsonLoadBufAsHex(root, "$.Card.ATS", udata.mfdes->card_info.ats, sizeof(udata.mfdes->card_info.ats), &len); + udata.mfdes->card_info.ats_len = len; + + // key lengths indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps)) { + + const char *aidstr = NULL; + json_t *value = NULL; + + json_object_foreach(apps, aidstr, value) { + + if (udata.mfdes->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + + desfire_app_keys_t *app = &udata.mfdes->app[udata.mfdes->appcount]; + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + snprintf(blocks, sizeof(blocks), "$.%s.%u.Key", algo_name[algo], keyno); + + len = 0; + JsonLoadBufAsHex(value, blocks, &app->keys[algo][keyno][1], algo_keylen[algo], &len); + if (len == algo_keylen[algo]) { + app->keys[algo][keyno][0] = 0x01; + } + } + } + + udata.mfdes->appcount++; + } + } + + *datalen = sizeof(desfire_keys_dump_t); + goto out; + } + if (!strcmp(ctype, "14b v2")) { size_t sptr = 0; for (int i = 0; i < (maxdatalen / 4); i++) { diff --git a/client/src/fileutils.h b/client/src/fileutils.h index 7323a66e2..b53077d2e 100644 --- a/client/src/fileutils.h +++ b/client/src/fileutils.h @@ -33,6 +33,14 @@ #include "cmdhftopaz.h" // TOPAZ defines #include "mifare/mifaredefault.h" // MFP / AES defines #include "iso15.h" // iso15_tag_t +#include "desfire.h" // desfire_app_keys_t + +// keys recovered from a DESFire PICC by `hf mfdes chk`, one entry per application +typedef struct { + iso14a_card_select_t card_info; + uint8_t appcount; + desfire_app_keys_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_keys_dump_t; typedef union { void *v; @@ -42,6 +50,7 @@ typedef union { iso14a_mf_extdump_t *mfc; iso14a_mf_dump_ev1_t *mfc_ev1; iso15_tag_t *iso15; + desfire_keys_dump_t *mfdes; } udata_t; typedef enum { @@ -69,6 +78,7 @@ typedef enum { jsfMfPlusKeys, jsfCustom, jsfMfDesfireKeys, + jsfMfDesfireKeys_v2, jsfEM4x05, jsfEM4x69, jsfEM4x50, diff --git a/include/desfire.h b/include/desfire.h index 37716f11d..298acc069 100644 --- a/include/desfire.h +++ b/include/desfire.h @@ -30,4 +30,16 @@ typedef enum { T_AES = 0x03 } DesfireCryptoAlgorithm; +#define DESFIRE_MAX_ALGO_COUNT 4 // T_DES ... T_AES +#define DESFIRE_MAX_KEY_COUNT 0x0E // key numbers 0x00 ... 0x0D +#define DESFIRE_MAX_APP_COUNT 64 // applications we keep track of per PICC + +// Keys recovered for one application. +// keys[algo][keyno][0] is the found flag, keys[algo][keyno][1..] the key itself. +// `algo` is a DesfireCryptoAlgorithm, `keyno` the DESFire key number. +typedef struct { + uint32_t aid; + uint8_t keys[DESFIRE_MAX_ALGO_COUNT][DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE + 1]; +} desfire_app_keys_t; + #endif From 2610d0cfc2c89de725f46bce40cb5e634b487343 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 10:42:33 +0200 Subject: [PATCH 20/26] text --- doc/commands.json | 281 ++++++++++++++++++++++++++++------------------ doc/commands.md | 24 +++- 2 files changed, 191 insertions(+), 114 deletions(-) diff --git a/doc/commands.json b/doc/commands.json index 7a7c8b627..d52c20a70 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -6223,7 +6223,7 @@ }, "hf mf gdmgetblk": { "command": "hf mf gdmgetblk", - "description": "Read public block(s) from a GDM card", + "description": "Read public block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgetblk --blk 0", "hf mf gdmgetblk --sec 1 --gdm" @@ -6234,15 +6234,15 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgetcfg": { "command": "hf mf gdmgetcfg", - "description": "Get configuration data from a GDM card. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override.", + "description": "Get configuration data from a GDM card. With no wakeup flag it auto-detects the card's access mode (tries WUPA magic auth, then gen1a, then gdm alt). Use `--gdm`/`--gen1a`/`--wupa` to force one.", "notes": [ "hf mf gdmgetcfg", "hf mf gdmgetcfg --gen1a", @@ -6252,15 +6252,15 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetcfg [-h] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgethidblk": { "command": "hf mf gdmgethidblk", - "description": "Read hidden block(s) from a GDM card", + "description": "Read hidden block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgethidblk --blk 0", "hf mf gdmgethidblk --sec 1 --gdm" @@ -6271,9 +6271,9 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgethidblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, @@ -6292,7 +6292,7 @@ }, "hf mf gdmsetblk": { "command": "hf mf gdmsetblk", - "description": "Set public block data on a GDM card By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", + "description": "Set public block data on a GDM card With no wakeup flag it auto-detects the card's access mode (gen1a, gdm alt, or WUPA magic auth). `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f", "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f --gen1a", @@ -6304,19 +6304,20 @@ "--blk public block number", "-d, --data bytes to write, 16 hex bytes", "-k, --key key, 6 hex bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsetblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetcfg": { "command": "hf mf gdmsetcfg", - "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back.", + "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt). `access:` flags select how this command talks to the card; `config:` flags change what is stored.", "notes": [ "hf mf gdmsetcfg -d 850000000000000000005A5A00000008", - "hf mf gdmsetcfg --cuid on --gen1 on", + "hf mf gdmsetcfg --cuid on --wakestyle gen1a", + "hf mf gdmsetcfg --wakestyle off", "hf mf gdmsetcfg --shadow off --sigsec off --wupa -k FFFFFFFFFFFF" ], "offline": false, @@ -6324,22 +6325,22 @@ "-h, --help This help", "-d, --data raw bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for regular wakeup)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", - "--gen1 Gen1 mode (7A FF)", - "--cuid Gen2/CUID mode", - "--cl2 CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>` to set a valid UID", - "--shadow Shadow mode", - "--magicauth Magic auth", - "--statenc Static encrypted nonce", - "--sigsec Signature sector" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", + "--cuid config: Gen2/CUID mode", + "--cl2 config: CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>`", + "--shadow config: Shadow mode", + "--magicauth config: Magic auth (what --wupa uses)", + "--statenc config: Static encrypted nonce", + "--sigsec config: Signature sector", + "--wakestyle config: backdoor - gdm (7AFF85), gen1a (7AFF00), or off (8500, seal)" ], - "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--gen1 ] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ]" + "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ] [--wakestyle ]" }, "hf mf gdmsethidblk": { "command": "hf mf gdmsethidblk", - "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", + "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000", "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000 --gen1a", @@ -6352,16 +6353,16 @@ "--blk hidden block number (0-7)", "-d, --data bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsethidblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetsig": { "command": "hf mf gdmsetsig", - "description": "Set MFC EV1 signature on a GDM card", + "description": "Set MFC EV1 signature on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetsig -s <64 hex chars>" ], @@ -6370,15 +6371,15 @@ "-h, --help This help", "-s, --sig 32-byte signature (64 hex characters)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmsetsig [-h] -s [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmsetuid": { "command": "hf mf gdmsetuid", - "description": "Set UID on a GDM card", + "description": "Set UID on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetuid -u 01020304", "hf mf gdmsetuid -u 01020304050607 --gen1a" @@ -6388,16 +6389,16 @@ "-h, --help This help", "-u, --uid UID to set (4 or 7 hex bytes)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--f3d use F3 perso mode (writes to hidden block 1 instead of 0)" ], "usage": "hf mf gdmsetuid [-h] -u [-k ] [--gdm] [--gen1a] [--wupa] [--f3d]" }, "hf mf gdmwipe": { "command": "hf mf gdmwipe", - "description": "Wipe a GDM card to factory defaults", + "description": "Wipe a GDM card to factory defaults. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmwipe --gdm" ], @@ -6405,9 +6406,9 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "-a, --all wipe 4K card (40 sectors) instead of 1K card (16 sectors)" ], "usage": "hf mf gdmwipe [-ha] [-k ] [--gdm] [--gen1a] [--wupa]" @@ -7367,17 +7368,17 @@ "command": "hf mfdes chk", "description": "Checks keys with MIFARE DESFire card.", "notes": [ - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456", - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card", - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456", - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`", - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00" + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card", + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456", + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`", + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00", + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456" ], "offline": false, "options": [ "-h, --help This help", "--aid Use specific AID (3 hex bytes, big endian)", - "-k, --key Key for checking (HEX 16 bytes)", + "-k, --key Key for checking (HEX 8, 16 or 24 bytes)", "-f, --file Filename of dictionary", "--pattern1b Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)", "--pattern2b Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)", @@ -9416,6 +9417,30 @@ ], "usage": "hf mfu keygen [-hr] [-u ] [-b ]" }, + "hf mfu ndefformat": { + "command": "hf mfu ndefformat", + "description": "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", + "notes": [ + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" + }, "hf mfu ndefread": { "command": "hf mfu ndefread", "description": "Prints NFC Data Exchange Format (NDEF)", @@ -10874,83 +10899,92 @@ ], "usage": "hw break [-h]" }, - "hw bwmautooff": { - "command": "hw bwmautooff", - "description": "Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", - "notes": [ - "hw bwmautooff --off -> disable auto power-off", - "hw bwmautooff --on -> re-enable auto power-off" - ], - "offline": false, - "options": [ - "-h, --help This help", - "--on enable auto power-off (default)", - "--off disable auto power-off" - ], - "usage": "hw bwmautooff [-h] [--on] [--off]" - }, - "hw bwmcharge": { - "command": "hw bwmcharge", + "hw bwm charge": { + "command": "hw bwm charge", "description": "Enable or disable BWM battery charging by clearing/setting the AW32001E charge-enable bit (CEB, REG01[3]). PM5 only. One-shot: the charger watchdog reverts this after ~160 s unless serviced, so charging may stop on its own. Use to nudge a top-up.", "notes": [ - "hw bwmcharge -on -> enable charging", - "hw bwmcharge --off -> disable charging" + "hw bwm charge off -> disable charging", + "hw bwm charge on -> enable charging" ], "offline": false, "options": [ - "-h, --help This help", - "--on enable charging (default)", - "--off disable charging" + "-h, --help This help" ], - "usage": "hw bwmcharge [-h] [--on] [--off]" + "usage": "hw bwm charge [-h]" }, - "hw bwmsetcap": { - "command": "hw bwmsetcap", + "hw bwm help": { + "command": "hw bwm help", + "description": "help This help --------------------------------------------------------------------------------------- hw bwm autooff available offline: no Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", + "notes": [ + "hw bwm autooff off -> disable auto power-off", + "hw bwm autooff on -> re-enable auto power-off" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm autooff [-h]" + }, + "hw bwm setcap": { + "command": "hw bwm setcap", "description": "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell. Run ONCE after fitting or replacing the battery. This triggers a gauge config-update; do not run it repeatedly, as that disrupts the Impedance Track learning cycle. PM5 only.", "notes": [ - "hw bwmsetcap -> set design capacity to default 500 mAh", - "hw bwmsetcap --cap 500 -> set design capacity to 500 mAh" + "hw bwm setcap -> set design capacity to default 500 mAh", + "hw bwm setcap --cap 500 -> set design capacity to 500 mAh" ], "offline": false, "options": [ "-h, --help This help", "--cap design capacity in mAh (default 500)" ], - "usage": "hw bwmsetcap [-h] [--cap ]" + "usage": "hw bwm setcap [-h] [--cap ]" }, - "hw bwmvchg": { - "command": "hw bwmvchg", + "hw bwm upgrade": { + "command": "hw bwm upgrade", + "description": "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering. Requires a BWM that still responds; this updates a wrong-version ESP, it cannot recover a fully bricked one (that still needs the 5-pin header + esptool).", + "notes": [ + "hw bwm upgrade -f bwm_esp32.bin" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file ESP32 firmware image (.bin)", + "--delay per-chunk delay to pace the slow AT32<->ESP UART (default 20)" + ], + "usage": "hw bwm upgrade [-h] -f [--delay ]" + }, + "hw bwm vchg": { + "command": "hw bwm vchg", "description": "Set the BWM charger (AW32001E) charge-voltage regulation target. Lowering it below 4.2 V reduces top-of-charge stress and extends cell life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is a runtime register write (reverts on the charger watchdog / POR); the firmware re-applies the 4100 mV default at every boot. PM5 only.", "notes": [ - "hw bwmvchg -> set charge voltage to default 4100 mV (->4.095 V)", - "hw bwmvchg --mv 4200 -> set charge voltage to 4200 mV" + "hw bwm vchg -> set charge voltage to default 4100 mV (->4.095 V)", + "hw bwm vchg --mv 4200 -> set charge voltage to 4200 mV" ], "offline": false, "options": [ "-h, --help This help", "--mv charge voltage in mV (default 4100, clamped 3600..4200)" ], - "usage": "hw bwmvchg [-h] [--mv ]" + "usage": "hw bwm vchg [-h] [--mv ]" }, - "hw bwmwifi": { - "command": "hw bwmwifi", - "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only.", + "hw bwm wifi": { + "command": "hw bwm wifi", + "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only. Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", "notes": [ - "hw bwmwifi --ssid Home --pwd secret -> port 7777", - "hw bwmwifi --ssid Home --pwd secret --port 9000", - "hw bwmwifi --status -> show connection state + IP" + "hw bwm wifi status -> show connection state + IP", + "hw bwm wifi stop -> tear down WiFi, back to BLE-only", + "hw bwm wifi --ssid Home --pwd secret -> bring up, port 7777", + "hw bwm wifi --ssid Home --pwd secret --port 9000" ], "offline": false, "options": [ "-h, --help This help", - "--ssid WiFi SSID to join (omit with --stop)", + "--ssid WiFi SSID to join", "--pwd WiFi password (omit for open network)", "--port TCP server listen port (default 7777)", - "--hostname DHCP hostname (default Proxmark5)", - "--stop tear down WiFi and return to BLE-only", - "--status show current WiFi connection state + IP" + "--hostname DHCP hostname (default Proxmark5)" ], - "usage": "hw bwmwifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ] [--stop] [--status]" + "usage": "hw bwm wifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ]" }, "hw connect": { "command": "hw connect", @@ -11086,15 +11120,22 @@ "command": "hw qc_pm5", "description": "QC Test for the PM5", "notes": [ - "hw qc_pm5 -> run QC test with default 20 second timeout", - "hw qc_pm5 -t 3 -> run QC test with a 3 second timeout" + "hw qc_pm5 -> run hardware QC test with default 20 second timeout", + "hw qc_pm5 -t 3 -> run hardware QC test with a 3 second timeout", + "hw qc_pm5 --iolow --pwd -> drive PM5 test IO low", + "hw qc_pm5 --iohigh --pwd -> drive PM5 test IO high", + "hw qc_pm5 --ioreset --pwd -> reset PM5 test IO to default" ], "offline": false, "options": [ "-h, --help This help", - "-t, --timeout test sequence timeout in seconds (default 20)" + "-t, --timeout test sequence timeout in seconds (default 20)", + "--iolow drive PM5 test IO low", + "--iohigh drive PM5 test IO high", + "--ioreset reset PM5 test IO to default", + "--pwd QC test password in hex (required for IO tests)" ], - "usage": "hw qc_pm5 [-h] [-t ]" + "usage": "hw qc_pm5 [-h] [-t ] [--iolow ] [--iohigh ] [--ioreset ] [--pwd ]" }, "hw readmem": { "command": "hw readmem", @@ -15407,21 +15448,27 @@ }, "nfc type1 help": { "command": "nfc type1 help", - "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 read available offline: no Prints NFC Data Exchange Format (NDEF)", + "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 format available offline: no Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", "notes": [ - "hf mfu ndefread -> shows NDEF data", - "hf mfu ndefread -k ffffffff -> shows NDEF data with key", - "hf mfu ndefread -f myfilename -> save raw NDEF to file" + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" ], "offline": true, "options": [ "-h, --help This help", - "-l Swap entered key's endianness", - "-f, --file Save raw NDEF to file", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", "-v, --verbose Verbose output", "--schann use secure channel. Must have key" ], - "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" }, "nfc type1 read": { "command": "nfc type1 read", @@ -15451,6 +15498,24 @@ ], "usage": "hf 14a ndefformat [-hv]" }, + "nfc type2 read": { + "command": "nfc type2 read", + "description": "Prints NFC Data Exchange Format (NDEF)", + "notes": [ + "hf mfu ndefread -> shows NDEF data", + "hf mfu ndefread -k ffffffff -> shows NDEF data with key", + "hf mfu ndefread -f myfilename -> save raw NDEF to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-l Swap entered key's endianness", + "-f, --file Save raw NDEF to file", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + }, "nfc type2 write": { "command": "nfc type2 write", "description": "Write NFC Data Exchange Format (NDEF) records to a MIFARE Ultralight / NTAG tag. The tag must already be NDEF formatted, ie carry a Capability Container in block 3. Combine several of --uri, --text and --aar to build a multi record message, records are added in that order. Alternatively supply raw NDEF bytes with -d or -f, those get wrapped in a TLV container automatically when they are not already. Use `nfc encode` to build such raw bytes offline. Note: the tag is re-selected and re-authenticated for every block written, so a large message takes a while.", @@ -16427,8 +16492,8 @@ } }, "metadata": { - "commands_extracted": 912, + "commands_extracted": 918, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-04T11:31:07+00:00" + "extracted_on": "2026-09-11T08:39:52+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 79b30d2b7..8446cbe64 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -759,6 +759,7 @@ Check column "offline" for their availability. |`hf mfu dump `|N |`Dump MIFARE Ultralight family tag to binary file` |`hf mfu incr `|N |`Increments Ev1/NTAG counter` |`hf mfu info `|N |`Tag information` +|`hf mfu ndefformat `|N |`Format tag as NDEF, writes the Capability Container` |`hf mfu ndefread `|N |`Prints NDEF records from card` |`hf mfu ndefwrite `|N |`Write NDEF records to card` |`hf mfu rdbl `|N |`Read block` @@ -1016,7 +1017,7 @@ Check column "offline" for their availability. |`hw fpga `|N |`Fpga commands` |`hw fpgaoff `|N |`Turn off FPGA on device` |`hw ant_pm5 `|N |`Control the antennal of pm5` -|`hw qc_pm5 `|N |`Perform QC test for the PM5` +|`hw qc_pm5 `|N |`Perform QC test (hardware or IO) for the PM5` |`hw factorydata `|N |`Get/Set the factory data for Device` |`hw lcd `|N |`Send command/data to LCD` |`hw lcdreset `|N |`Hardware reset LCD` @@ -1028,15 +1029,25 @@ Check column "offline" for their availability. |`hw setmux `|N |`Set the ADC mux to a specific value` |`hw standalone `|N |`Start installed standalone mode on device` |`hw tia `|N |`Trigger a Timing Interval Acquisition to re-adjust the RealTimeCounter divider` -|`hw bwmsetcap `|N |`Set BWM fuel-gauge design capacity (PM5, run once after battery change)` -|`hw bwmvchg `|N |`Set BWM charger charge-voltage target (PM5, default 4100 mV)` -|`hw bwmcharge `|N |`Enable/disable BWM battery charging (PM5, one-shot)` -|`hw bwmautooff `|N |`Toggle auto power-off on USB unplug (PM5, BWM)` -|`hw bwmwifi `|N |`Bring up BWM WiFi (STA + TCP server) for a tcp: connection (PM5)` |`hw tune `|N |`Measure tuning of device antenna` |`hw decay `|N |`Measure HF antenna decay after field-off` +### hw bwm + + { BWM (battery/wireless module) commands... } + +|command |offline |description +|------- |------- |----------- +|`hw bwm help `|Y |`This help` +|`hw bwm autooff `|N |`Toggle auto power-off on USB unplug` +|`hw bwm charge `|N |`Enable/disable battery charging (one-shot)` +|`hw bwm setcap `|N |`Set fuel-gauge design capacity (run once after battery change)` +|`hw bwm upgrade `|N |`Reflash BWM (ESP32) firmware over the BWM link, no header` +|`hw bwm vchg `|N |`Set charger charge-voltage target (default 4100 mV)` +|`hw bwm wifi `|N |`Bring up WiFi (STA + TCP server) for a tcp: connection` + + ### lf { Low frequency commands... } @@ -1667,6 +1678,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- +|`nfc type2 format `|N |`format MIFARE Ultralight / NTAG as NFC Forum Tag Type 2` |`nfc type2 read `|N |`read NFC Forum Tag Type 2` |`nfc type2 write `|N |`write NFC Forum Tag Type 2` |`nfc type2 help `|Y |`This help` From cec0e800ab7d955d61202f24ac20fbcb9d3363ed Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 11:08:45 +0200 Subject: [PATCH 21/26] hf mfdes chk: detect the secure channel per application secureChannel was the constant DACEV1, and there was no way to override it, so a card in LRP mode could never be authenticated - chk reported no keys on a card 'hf mfdes detect' handles fine. When the key settings were unreadable it gave up instead of probing. Work the channel out per AID: the key settings give the algo, and for an AES app one AuthenticateLRPFirst probe separates EV1/EV2 from LRP, which the settings byte cannot. When the settings are unreadable, fall back to DesfireCheckAuthCommands() the way detect does. --schann d40|ev1|ev2|lrp pins it and skips detection. Only AES is tried on an LRP channel. Also clear the session after a found key, so the next key number starts a first auth rather than an EV2/LRP non-first one. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + client/src/cmdhfmfdes.c | 125 ++++++++++++++++++++++++++++++++++------ doc/commands.json | 8 ++- 3 files changed, 112 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0bcd904f..93c34c2d8 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 chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) - Fixed `hf mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) - Fixed `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) - Changed `tests/lf_t55xx_writetest.lua` - reads each block three times and names how a bad read differs (`rol1`, `ror5`, `inverted`, `shr1`) instead of only pass/fail (@mfcarroll) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 6aea02817..566fe3a5e 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -1311,6 +1311,10 @@ static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, found->keys[keytype][keyno][0] = 0x01; memcpy(&found->keys[keytype][keyno][1], key, keylen); *result = true; + + // EV2 and LRP turn an authenticated context into a "non first" + // auth for the next key number. Start each one clean instead. + DesfireClearSession(dctx); break; } @@ -1362,6 +1366,7 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], uint32_t deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], uint32_t aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], uint32_t k3kkeyListLen, + bool autoschann, desfire_app_keys_t *found, bool *result, bool verbose) { @@ -1381,28 +1386,72 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, bool aes = false; bool k3kdes = false; + bool uselrp = false; + uint8_t data[250] = {0}; size_t datalen = 0; res = DesfireGetKeySettings(dctx, data, &datalen); - if (res != PM3_SUCCESS && datalen < 2) { - PrintAndLogEx(ERR, "Could not get key settings"); - return res; - } - uint8_t num_keys = data[1]; - switch (num_keys >> 6) { - case 0: + if (res == PM3_SUCCESS && datalen >= 2) { + + switch (data[1] >> 6) { + case 0: + des = true; + tdes = true; + break; + case 1: + k3kdes = true; + break; + case 2: + aes = true; + break; + default: + break; + } + + } else { + + // key settings are not readable. Ask the card which AUTH commands it + // answers instead, the same way `hf mfdes detect` does + AuthCommandsChk_t authCmdCheck = {0}; + DesfireCheckAuthCommands(ISW6bAID, curaid, NULL, 0, &authCmdCheck); + + if (authCmdCheck.checked == false) { + PrintAndLogEx(ERR, "AID 0x%06X, could not get key settings", curaid); + DropField(); + return PM3_ESOFT; + } + + if (authCmdCheck.auth) { des = true; tdes = true; - break; - case 1: - k3kdes = true; - break; - case 2: + if (authCmdCheck.authISO) { + k3kdes = true; + } + } + + if (authCmdCheck.authAES || authCmdCheck.authEV2) { aes = true; - break; - default: - break; + } + + if (authCmdCheck.authLRP) { + aes = true; + uselrp = true; + } + + if (des == false && tdes == false && aes == false && k3kdes == false) { + PrintAndLogEx(ERR, "AID 0x%06X, card answers no known auth command", curaid); + DropField(); + return PM3_ESOFT; + } + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the auth command probe", curaid); + DropField(); + return PM3_ESOFT; + } } // always check master key @@ -1435,8 +1484,28 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, } } + // An AES application runs either the EV1/EV2 channel or LRP and the key + // settings don't say which, so it takes one probe to tell them apart. + if (autoschann && aes && uselrp == false) { + + uselrp = DesfireCheckAuthCmd(ISW6bAID, curaid, 0, MFDES_AUTHENTICATE_EV2F, true); + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the LRP probe", curaid); + DropField(); + return PM3_ESOFT; + } + } + + if (autoschann && uselrp) { + secureChannel = DACLRP; + } + if (verbose) { PrintAndLogEx(INFO, "Check: %s %s %s %s " NOLF, (des) ? "DES" : "", (tdes) ? "2TDEA" : "", (k3kdes) ? "3TDEA" : "", (aes) ? "AES" : ""); + PrintAndLogEx(NORMAL, "channel: %s " NOLF, CLIGetOptionListStr(DesfireSecureChannelOpts, secureChannel)); PrintAndLogEx(NORMAL, "keys: " NOLF); for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) if (usedkeys[i] == 1) @@ -1464,6 +1533,11 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, continue; } + // LRP only ever carries AES keys + if (secureChannel == DACLRP && checks[i].keytype != T_AES) { + continue; + } + res = AuthCheckDesfireKeyType(dctx, secureChannel, curaid, checks[i].keytype, checks[i].name, checks[i].list, checks[i].stride, checks[i].len, usedkeys, found, result); @@ -1494,7 +1568,8 @@ static int CmdHF14aDesChk(const char *Cmd) { "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`\n" "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00\n" "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456\n" - ); + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel\n" + ); void *argtable[] = { arg_param_begin, @@ -1508,6 +1583,7 @@ static int CmdHF14aDesChk(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0(NULL, "kdf", "<0|1|2>", "Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0(NULL, "schann", "", "Secure channel (default: detected per application)"), arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_param_end }; @@ -1597,7 +1673,19 @@ static int CmdHF14aDesChk(const char *Cmd) { int kdfInputLen = 0; CLIGetHexWithReturn(ctx, 10, kdfInput, &kdfInputLen); - bool APDULogging = arg_get_lit(ctx, 11); + // the secure channel is detected per application unless the user pins one + DesfireSecureChannel secureChannel = DACEV1; + bool autoschann = (arg_get_str(ctx, 11)->count == 0); + if (autoschann == false) { + int schann = DACEV1; + if (CLIGetOptionList(arg_get_str(ctx, 11), DesfireSecureChannelOpts, &schann)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } + secureChannel = schann; + } + + bool APDULogging = arg_get_lit(ctx, 12); CLIParserFree(ctx); SetAPDULogging(APDULogging); @@ -1632,7 +1720,6 @@ static int CmdHF14aDesChk(const char *Cmd) { DesfireSetKdf(&dctx, cmdKDFAlgo, kdfInput, kdfInputLen); DesfireSetCommandSet(&dctx, DCCNativeISO); DesfireSetCommMode(&dctx, DCMPlain); - DesfireSecureChannel secureChannel = DACEV1; // save card UID to dctx DesfireGetCardUID(&dctx); @@ -1805,7 +1892,7 @@ static int CmdHF14aDesChk(const char *Cmd) { deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, - found, &foundKeyThisRound, verbose); + autoschann, found, &foundKeyThisRound, verbose); if (res == PM3_EOPABORTED) { break; } diff --git a/doc/commands.json b/doc/commands.json index d52c20a70..5c2833a2a 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -7372,7 +7372,8 @@ "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456", "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`", "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00", - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456" + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456", + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel" ], "offline": false, "options": [ @@ -7387,9 +7388,10 @@ "-v, --verbose Verbose output", "--kdf <0|1|2> Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)", "-i, --kdfi KDF input (1-31 hex bytes)", + "--schann Secure channel (default: detected per application)", "-a, --apdu Show APDU requests and responses" ], - "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ]" + "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ] [--schann ]" }, "hf mfdes chkeysettings": { "command": "hf mfdes chkeysettings", @@ -16494,6 +16496,6 @@ "metadata": { "commands_extracted": 918, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-11T08:39:52+00:00" + "extracted_on": "2026-09-11T09:05:59+00:00" } } From e810245caab40660a6000de24c0ab52595c4af36 Mon Sep 17 00:00:00 2001 From: Matthew Carroll Date: Fri, 11 Sep 2026 02:20:10 -0700 Subject: [PATCH 22/26] lf t55xx detect: save and restore the graph buffer through the shared helpers The psk antenna-settle trim open-coded the save/restore pair: save_bufferS32 plus g_GridOffset on the way in, and restore_bufferS32's return assigned to g_GraphTraceLen on the way out. graph.c now has save_graphbuffer and restore_graphbuffer, which hold contents, length and grid offset together, so call those and drop the local copy of the length contract. No behaviour change. `lf t55xx detect -1` on the in-tree psk traces leaves the graph at 20000 samples before and after. Co-Authored-By: Claude Opus 5 --- client/src/cmdlft55xx.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index eb1006e90..67669749b 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -111,8 +111,7 @@ static void t55xx_record_hit(t55xx_conf_block_t *t) { // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) static buffer_savestate_t t55xx_psk_trim_head(void) { - buffer_savestate_t st = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - st.offset = g_GridOffset; + buffer_savestate_t st = save_graphbuffer(); char ltrim[16]; snprintf(ltrim, sizeof(ltrim), "-i %d", T55XX_PSK_SETTLE_TRIM); @@ -124,9 +123,7 @@ static buffer_savestate_t t55xx_psk_trim_head(void) { static void t55xx_psk_untrim_head(buffer_savestate_t st) { s_sample_bias = 0; - // restore_bufferS32 returns the length it put back; dropping it leaves the trim in place - g_GraphTraceLen = restore_bufferS32(st, g_GraphBuffer); - g_GridOffset = st.offset; + restore_graphbuffer(st); } // the bit offset to read a block at in the demod buffer loaded right now From e0543bd612e3a9b147477dc883217702eb5c6540 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 12:38:16 +0200 Subject: [PATCH 23/26] hf mfdes detect: probe for LRP, and use the DESFire dictionary Two things stopped 'detect' finding keys it should have found. An AES application and an LRP application report the same key settings byte, so a card in LRP mode was only caught when the settings happened to be unreadable and the auth-command fallback ran. Probe with AuthenticateLRPFirst whenever --schann was not given, then re-select. With no -f, candidates came from g_mifare_plus_default_keys, which is 26 entries of 16 byte AES. For DES that meant authenticating with the first half of an AES key, and for 3K3DES it fabricated 24 bytes as key[0..15] + key[0..7]. Default to the bundled mfdes_default_keys dictionary instead: 7 DES, 47 2TDEA/AES and 4 real 3K3DES keys. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 + client/src/cmdhfmfdes.c | 117 ++++++++++++++++++---------------------- 2 files changed, 53 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93c34c2d8..76d2f6db8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list,it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) +- Fixed `hf mfdes detect` - LRP was only found when the key settings happened to be unreadable (@iceman1001) - Added `hf mfdes chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) - Fixed `hf mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) - Fixed `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 566fe3a5e..4b3db4278 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -59,6 +59,8 @@ #define MAX_KEYS_LIST_LEN 1024 // how many errors in a row from the card before we give up on a key number #define MFDES_CHK_MAX_ERRORS 10 +// bundled dictionary used when no -f is given +#define MFDES_DEFAULT_DICT "mfdes_default_keys" #define MFDES_BRUTEAID_RESELECT_ATTEMPTS 5 #define MFDES_BRUTEAID_RESELECT_WAIT_MS 200 #define MFDES_BRUTEAID_MAD_START 0xF0000FU @@ -1971,8 +1973,8 @@ static int CmdHF14aDesDetect(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes detect", "Detect key type and tries to find one from the list.", "hf mfdes detect -> detect key 0 from PICC level\n" - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40\n" - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary\n" + "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40, skipping channel detection\n" + "hf mfdes detect -f my_keys -> detect key 0 from PICC level with your own dictionary\n" "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)\n" "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode"); @@ -1991,7 +1993,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), arg_str0(NULL, "isoid", "", "Application ISO ID (ISO DF ID) (2 hex bytes, big endian)."), arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), - arg_str0("f", "file", "", "Filename of dictionary"), + arg_str0("f", "file", "", "Filename of dictionary (default: `" MFDES_DEFAULT_DICT "`)"), arg_lit0(NULL, "save", "Save found key and parameters to defaults"), arg_param_end }; @@ -2020,6 +2022,16 @@ static int CmdHF14aDesDetect(const char *Cmd) { bool save = arg_get_lit(ctx, 15); + // whether the user pinned a secure channel, or we get to detect one + bool schannset = (arg_get_str(ctx, 10)->count > 0); + + // no dictionary given - use the bundled DESFire one. The built-in + // g_mifare_plus_default_keys list is 16 byte AES only, so it can produce + // neither the DES nor the 3K3DES defaults this card family ships with + if (dict_filenamelen == 0) { + dict_filenamelen = snprintf((char *)dict_filename, sizeof(dict_filename), "%s", MFDES_DEFAULT_DICT); + } + SetAPDULogging(APDULogging); CLIParserFree(ctx); @@ -2100,6 +2112,26 @@ static int CmdHF14aDesDetect(const char *Cmd) { } } + // An AES application runs either the EV1/EV2 channel or LRP, and the key + // settings byte reads the same for both, so it takes one probe to tell them + // apart. Without this an LRP card is only caught when the key settings + // happen to be unreadable and the fallback above runs. + if (schannset == false && uselrp == false && keytypes[T_AES]) { + + uselrp = DesfireCheckAuthCmd(selectway, id, dctx.keyNum, MFDES_AUTHENTICATE_EV2F, true); + if (uselrp) { + securechann = DACLRP; + } + + // the probe dropped the field behind us + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, true, verbose); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") " after the LRP probe. Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); + return res; + } + } + if (verbose) { if (DesfireMFSelected(selectway, id)) { @@ -2132,27 +2164,28 @@ static int CmdHF14aDesDetect(const char *Cmd) { PrintAndLogEx(INFO, "Scan key type: %s", CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); } - if (dict_filenamelen == 0) { - // keys from mifaredefault.h - for (int i = 0; i < g_mifare_plus_default_keys_len; i++) { + // candidate keys come from the dictionary + uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; + uint32_t keyListLen = 0; + size_t keylen = desfire_get_key_length(dctx.keyType); + size_t endFilePosition = 0; - uint8_t key[DESFIRE_MAX_KEY_SIZE] = {0}; - if (hex_to_bytes(g_mifare_plus_default_keys[i], key, 16) != 16) { - continue; - } + while (found == false) { - if (ktype == T_3K3DES) { - memcpy(&key[16], key, 8); - } + res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); + if (res != 1 && res != PM3_SUCCESS) { + break; + } - res = DesfireAuthCheck(&dctx, selectway, id, securechann, key); + for (int i = 0; i < keyListLen; i++) { + + res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); if (res == PM3_SUCCESS) { found = true; break; // all the params already in the dctx } if (res == -10) { - if (verbose) { PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); } @@ -2174,60 +2207,12 @@ static int CmdHF14aDesDetect(const char *Cmd) { } else { errcount = 0; } + } - } else { - // keys from file - uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; - uint32_t keyListLen = 0; - size_t keylen = desfire_get_key_length(dctx.keyType); - size_t endFilePosition = 0; - - while (found == false) { - - res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); - if (res != 1 && res != PM3_SUCCESS) { - break; - } - - for (int i = 0; i < keyListLen; i++) { - - res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); - if (res == PM3_SUCCESS) { - found = true; - break; // all the params already in the dctx - } - - if (res == -10) { - if (verbose) { - PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); - } - - found = false; - break; // we can't select app after invalid 1st auth stages - } - - if (res == -11) { - - if (errcount > 10) { - if (verbose) { - PrintAndLogEx(ERR, "Too much errors (%zu) from card", errcount); - } - break; - } - errcount++; - - } else { - errcount = 0; - } - - } - - if (endFilePosition == 0) { - break; - } + if (endFilePosition == 0) { + break; } - } if (found) { From 67c121f55459823df7500865db49869bc34815df Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 15:15:36 +0200 Subject: [PATCH 24/26] hf mfdes detect: sweep all key numbers, and count errors per key type errcount was declared before the key type loop and only reset by a non -11 result, so eleven scattered card errors during the DES pass left the AES pass to break on its first error without trying a key. Count per key type instead. With no -n, detect only ever looked at key 0. Sweep the key numbers the application declares (low nibble of the key settings) instead, falling back to 0x00..0x0D when the settings are unreadable. All keys in an application share an algo, so the first key number that succeeds narrows keytypes[] for the rest. --save now stores the first key found rather than whatever dctx was left holding, and a lost card aborts the sweep. -n behaves exactly as before. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 + client/src/cmdhfmfdes.c | 369 ++++++++++++++++++++++++---------------- doc/commands.json | 102 +++++------ 3 files changed, 275 insertions(+), 198 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76d2f6db8..f192a65a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `hf mfdes detect` - with no `-n` it now sweeps every key number the application declares instead of only key 0; the first hit pins the algo for the rest (@iceman1001) +- Fixed `hf mfdes detect` - the card error counter was shared by every key type, so a bad run during the DES pass could abort the AES pass before it tried a single key (@iceman1001) - Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list,it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) - Fixed `hf mfdes detect` - LRP was only found when the key settings happened to be unreadable (@iceman1001) - Added `hf mfdes chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 4b3db4278..919acedf6 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -822,14 +822,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { void *argtable[] = { arg_param_begin, - arg_int0("n", "keyno", "", "Key number"), - arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), - arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), - arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), - arg_str0("m", "cmode", "", "Communicaton mode"), - arg_str0("c", "ccset", "", "Communicaton command set"), - arg_str0(NULL, "schann", "", "Secure channel"), + arg_int0("n", "keyno", "", "Key number"), + arg_str0("t", "algo", "", "Crypt algo"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), + arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), + arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0("m", "cmode", "", "Communicaton mode"), + arg_str0("c", "ccset", "", "Communicaton command set"), + arg_str0(NULL, "schann", "", "Secure channel"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -860,14 +860,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); - PrintAndLogEx(INFO, "Key Num : %d", defaultKeyNum); - PrintAndLogEx(INFO, "Algo : %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); - PrintAndLogEx(INFO, "Key : %s", sprint_hex(defaultKey, desfire_get_key_length(defaultAlgoId))); - PrintAndLogEx(INFO, "KDF algo : %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); - PrintAndLogEx(INFO, "KDF input : [%d] %s", defaultKdfInputLen, sprint_hex(defaultKdfInput, defaultKdfInputLen)); - PrintAndLogEx(INFO, "Secure chan : %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); - PrintAndLogEx(INFO, "Command set : %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); - PrintAndLogEx(INFO, "Comm mode : %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); + PrintAndLogEx(INFO, "Key num........ %d", defaultKeyNum); + PrintAndLogEx(INFO, "Algo........... %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); + PrintAndLogEx(INFO, "Key............ %s", sprint_hex_inrow(defaultKey, desfire_get_key_length(defaultAlgoId))); + PrintAndLogEx(INFO, "KDF algo....... %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); + PrintAndLogEx(INFO, "KDF input...... [%d] %s", defaultKdfInputLen, sprint_hex_inrow(defaultKdfInput, defaultKdfInputLen)); + PrintAndLogEx(INFO, "Sec chann...... %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); + PrintAndLogEx(INFO, "Command set.... %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); + PrintAndLogEx(INFO, "Command mode... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); return PM3_SUCCESS; } @@ -1576,7 +1576,7 @@ static int CmdHF14aDesChk(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_str0(NULL, "aid", "", "Use specific AID (3 hex bytes, big endian)"), - arg_str0("k", "key", "", "Key for checking (HEX 8, 16 or 24 bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0("f", "file", "", "Filename of dictionary"), arg_lit0(NULL, "pattern1b", "Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)"), arg_lit0(NULL, "pattern2b", "Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)"), @@ -1890,11 +1890,18 @@ static int CmdHF14aDesChk(const char *Cmd) { loadedAllKeys = true; } - res = AuthCheckDesfire(&dctx, secureChannel, &app_ids[x * 3], - deskeyList, deskeyListLen, - aeskeyList, aeskeyListLen, - k3kkeyList, k3kkeyListLen, - autoschann, found, &foundKeyThisRound, verbose); + res = AuthCheckDesfire(&dctx, + secureChannel, + &app_ids[x * 3], + deskeyList, deskeyListLen, + aeskeyList, aeskeyListLen, + k3kkeyList, k3kkeyListLen, + autoschann, + found, + &foundKeyThisRound, + verbose + ); + if (res == PM3_EOPABORTED) { break; } @@ -1971,20 +1978,22 @@ static int DesfireAuthCheck(DesfireContext_t *dctx, DesfireISOSelectWay way, uin static int CmdHF14aDesDetect(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes detect", - "Detect key type and tries to find one from the list.", - "hf mfdes detect -> detect key 0 from PICC level\n" - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40, skipping channel detection\n" - "hf mfdes detect -f my_keys -> detect key 0 from PICC level with your own dictionary\n" - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)\n" - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode"); + "Detect PICC master key, key type, communication mode, command set and channel mode.\n" + "Uses `mfdes_default_keys.dic` per default\n" + " `--save` it saves details to be used with `hf mfdes default`\n", + "hf mfdes detect\n" + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40\n" + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary\n" + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults\n" + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode"); void *argtable[] = { arg_param_begin, arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), - arg_int0("n", "keyno", "", "Key number"), + arg_int0("n", "keyno", "", "Key number (def: all)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -2025,6 +2034,9 @@ static int CmdHF14aDesDetect(const char *Cmd) { // whether the user pinned a secure channel, or we get to detect one bool schannset = (arg_get_str(ctx, 10)->count > 0); + // whether the user asked for one key number, or we sweep the application + bool keynoset = (arg_get_int_count(ctx, 3) > 0); + // no dictionary given - use the bundled DESFire one. The built-in // g_mifare_plus_default_keys list is 16 byte AES only, so it can produce // neither the DES nor the 3K3DES defaults this card family ships with @@ -2045,6 +2057,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { bool keytypes[4] = {0}; bool uselrp = false; + uint8_t numkeys = 0; uint8_t data[250] = {0}; size_t datalen = 0; @@ -2053,6 +2066,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { if (res == PM3_SUCCESS && datalen >= 2) { uint8_t num_keys = data[1]; + numkeys = num_keys & 0x0F; switch (num_keys >> 6) { case 0: { @@ -2132,14 +2146,39 @@ static int CmdHF14aDesDetect(const char *Cmd) { } } - if (verbose) { + // Without -n we sweep every key number the application declares. All keys + // in one DESFire application share an algo, so the first key number that + // succeeds pins the type down for the rest. + uint8_t keynofirst = dctx.keyNum; + uint8_t keynolast = dctx.keyNum; + if (keynoset == false) { + keynofirst = 0; + keynolast = (numkeys > 0 && numkeys <= DESFIRE_MAX_KEY_COUNT) ? (numkeys - 1) : (DESFIRE_MAX_KEY_COUNT - 1); + } - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, "Check PICC key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Check: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + // What we worked out about the target. Worth printing even when no key is + // found - knowing the app is AES on LRP with 3 keys is half the answer. + char algostr[64] = {0}; + size_t algolen = 0; + for (uint8_t t = T_DES; t <= T_AES; t++) { + if (keytypes[t] == false) { + continue; } + algolen += snprintf(algostr + algolen, sizeof(algostr) - algolen, "%s%s", (algolen) ? "/" : "", CLIGetOptionListStr(DesfireAlgoOpts, t)); + } + if (algolen == 0) { + snprintf(algostr, sizeof(algostr), "unknown"); + } + PrintAndLogEx(INFO, "%s... key num " _YELLOW_("0x%02x") "-" _YELLOW_("0x%02x") ", algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), + (DesfireMFSelected(selectway, id)) ? "PICC level" : DesfireWayIDStr(selectway, id), + keynofirst, + keynolast, + algostr, + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann) + ); + + if (verbose) { PrintAndLogEx(INFO, "keys: DES: %s 2TDEA: %s 3TDEA: %s AES: %s LRP: %s", keytypes[T_DES] ? _GREEN_("YES") : _RED_("NO"), keytypes[T_3DES] ? _GREEN_("YES") : _RED_("NO"), @@ -2149,107 +2188,142 @@ static int CmdHF14aDesDetect(const char *Cmd) { ); } - // for key types - bool found = false; - size_t errcount = 0; - for (uint8_t ktype = T_DES; ktype <= T_AES; ktype++) { + uint8_t foundcount = 0; + uint8_t totalkeys = keynolast - keynofirst + 1; + bool nocard = false; - if (keytypes[ktype] == false) { - continue; - } + // the first key we find is what --save stores + DesfireContext_t savedctx = {0}; + bool savedctxvalid = false; - dctx.keyType = ktype; + for (uint8_t keyno = keynofirst; keyno <= keynolast && nocard == false; keyno++) { - if (verbose) { - PrintAndLogEx(INFO, "Scan key type: %s", CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); - } + dctx.keyNum = keyno; + bool found = false; - // candidate keys come from the dictionary - uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; - uint32_t keyListLen = 0; - size_t keylen = desfire_get_key_length(dctx.keyType); - size_t endFilePosition = 0; + // for key types + for (uint8_t ktype = T_DES; ktype <= T_AES && found == false; ktype++) { - while (found == false) { - - res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); - if (res != 1 && res != PM3_SUCCESS) { - break; + if (keytypes[ktype] == false) { + continue; } - for (int i = 0; i < keyListLen; i++) { + dctx.keyType = ktype; - res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); - if (res == PM3_SUCCESS) { - found = true; - break; // all the params already in the dctx + if (verbose) { + PrintAndLogEx(INFO, "Scan key num %d (0x%02x) type: %s", keyno, keyno, CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); + } + + // candidate keys come from the dictionary + uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; + uint32_t keyListLen = 0; + size_t keylen = desfire_get_key_length(dctx.keyType); + size_t endFilePosition = 0; + + // errors are counted per key type. A bad run on one must not cut + // the next one short before it has tried a single key + size_t errcount = 0; + + while (found == false) { + + res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); + if (res != 1 && res != PM3_SUCCESS) { + break; } - if (res == -10) { - if (verbose) { - PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); + for (uint32_t i = 0; i < keyListLen; i++) { + + res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); + if (res == PM3_SUCCESS) { + found = true; + break; // all the params already in the dctx } - found = false; - break; // we can't select app after invalid 1st auth stages - } - - if (res == -11) { - - if (errcount > 10) { + if (res == -10) { if (verbose) { - PrintAndLogEx(ERR, "Too much errors (%zu) from card", errcount); + PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); } - break; - } - errcount++; - } else { - errcount = 0; + nocard = true; + break; // we can't select app after invalid 1st auth stages + } + + if (res == -11) { + + if (errcount > 10) { + if (verbose) { + PrintAndLogEx(ERR, "Too much errors (%zu) from card", errcount); + } + break; + } + errcount++; + + } else { + errcount = 0; + } } - } + if (nocard) { + break; + } - if (endFilePosition == 0) { - break; + if (endFilePosition == 0) { + break; + } } } if (found) { - break; + + foundcount++; + + if (DesfireMFSelected(selectway, id)) { + PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); + } else { + PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + } + + PrintAndLogEx(INFO, "Channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), + CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), + desfire_get_key_length(dctx.keyType), + sprint_hex_inrow(dctx.key, desfire_get_key_length(dctx.keyType)) + ); + + // every key in an application uses the same algo, so the rest of + // the key numbers only have to try the one that just worked + for (uint8_t t = T_DES; t <= T_AES; t++) { + keytypes[t] = (t == dctx.keyType); + } + + if (savedctxvalid == false) { + savedctx = dctx; + savedctxvalid = true; + } + + } else if (verbose && nocard == false) { + PrintAndLogEx(INFO, "Key num: %d (0x%02x) " _RED_("not found"), keyno, keyno); } } - if (found) { - - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); - } - - PrintAndLogEx(INFO, "channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), - CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), - CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), - desfire_get_key_length(dctx.keyType), - sprint_hex(dctx.key, desfire_get_key_length(dctx.keyType))); - - } else { + if (foundcount == 0) { PrintAndLogEx(INFO, "Key " _RED_("not found")); + } else if (totalkeys > 1) { + PrintAndLogEx(INFO, "Found " _GREEN_("%u") " of %u keys", foundcount, totalkeys); } DropField(); - if (found && save) { + if (savedctxvalid && save) { - defaultKeyNum = dctx.keyNum; - defaultAlgoId = dctx.keyType; - memcpy(defaultKey, dctx.key, DESFIRE_MAX_KEY_SIZE); - defaultKdfAlgo = dctx.kdfAlgo; - defaultKdfInputLen = dctx.kdfInputLen; - memcpy(defaultKdfInput, dctx.kdfInput, sizeof(dctx.kdfInput)); + defaultKeyNum = savedctx.keyNum; + defaultAlgoId = savedctx.keyType; + memcpy(defaultKey, savedctx.key, DESFIRE_MAX_KEY_SIZE); + defaultKdfAlgo = savedctx.kdfAlgo; + defaultKdfInputLen = savedctx.kdfInputLen; + memcpy(defaultKdfInput, savedctx.kdfInput, sizeof(savedctx.kdfInput)); defaultSecureChannel = securechann; - defaultCommSet = dctx.cmdSet; + defaultCommSet = savedctx.cmdSet; PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); PrintAndLogEx(INFO, "Key Num....... %d", defaultKeyNum); @@ -2285,7 +2359,7 @@ static int CmdHF14aDesMAD(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -2459,7 +2533,7 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3402,7 +3476,7 @@ static int CmdHF14ADesBruteDAMSlots(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3608,7 +3682,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3707,7 +3781,7 @@ static int CmdHF14ADesSetConfiguration(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3805,8 +3879,8 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { "Change crypto algorithm for PICC key is possible, \n" "but for APP keys crypto algorithm is set by createapp command and can't be changed wo application delete\n" "\n" - "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" - "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" + "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" + "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" "hf mfdes changekey -t des --newalgo aes --newkey 11223344556677889900112233445566 --newver a5 -> change card master key to AES one\n" "hf mfdes changekey --aid 123456 -t aes --key 00000000000000000000000000000000 --newkey 11223344556677889900112233445566 -> change app master key\n" "hf mfdes changekey --aid 123456 -t des -n 0 --newkeyno 1 --oldkey 5555555555555555 --newkey 1122334455667788 -> change key 1 with auth from key 0\n" @@ -3818,7 +3892,7 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3980,7 +4054,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4157,7 +4231,7 @@ static int CmdHF14ADesCreateDelegateApp(const char *Cmd) { arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4474,7 +4548,7 @@ static int CmdHF14ADesGetDelegateAppInfo(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4566,7 +4640,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4630,7 +4704,7 @@ static int CmdHF14ADesGetUID(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4793,7 +4867,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4850,7 +4924,7 @@ static int CmdHF14ADesGetFreeMem(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4915,7 +4989,7 @@ static int CmdHF14ADesChKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4989,7 +5063,7 @@ static int CmdHF14ADesGetKeyVersions(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number for authentication"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5094,7 +5168,7 @@ static int CmdHF14ADesGetKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5174,7 +5248,7 @@ static int CmdHF14ADesGetAIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5246,7 +5320,7 @@ static int CmdHF14ADesGetAppNames(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5309,9 +5383,10 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes getfileids", "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", - "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup\n" - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs"); + "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs\n" + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup\n" + ); void *argtable[] = { arg_param_begin, @@ -5319,7 +5394,7 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5396,7 +5471,7 @@ static int CmdHF14ADesGetFileISOIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5471,7 +5546,7 @@ static int CmdHF14ADesGetFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5642,7 +5717,7 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5785,7 +5860,7 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5923,7 +5998,7 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6049,7 +6124,7 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6168,7 +6243,7 @@ static int CmdHF14ADesCreateTrMACFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6285,7 +6360,7 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6363,7 +6438,7 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6548,7 +6623,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes clearrecfile", "Clear record file. Master key needs to be provided or flag --no-auth set (depend on cards settings).", - "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" + "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" "hf mfdes clearrecfile --isoid df01 --fid 01 --schann lrp -t aes -n 3 -> clear record file for lrp channel with key number 3"); void *argtable[] = { @@ -6557,7 +6632,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6728,7 +6803,7 @@ static int CmdHF14ADesMakeMFCLicense(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_lit0("v", "verbose", "Show more output"), - arg_str0("k", "key", "", "Key for computing the MAC, must be HEX 16(AES)"), + arg_str0("k", "key", "", "Key for computing the MAC (16 hex bytes)"), arg_str0("b", "blk", "[,[,...]]", "The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)"), arg_lit0(NULL, "ka", "Allow updating key A from inside sector trailers mapped to DESFire files"), arg_lit0(NULL, "kb", "Allow updating key B from inside sector trailers mapped to DESFire files"), @@ -6963,7 +7038,7 @@ static int CmdHF14ADesCreateMFCMapping(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7480,7 +7555,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7652,7 +7727,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7992,7 +8067,7 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -8067,7 +8142,7 @@ static int CmdHF14ADesLsApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -8133,7 +8208,7 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -9483,7 +9558,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), // 3 arg_int0("n", "keyno", "", "Key number for DESFire authentication"), // 4 arg_str0("t", "algo", "", "DESFire auth crypt algo"), // 5 - arg_str0("k", "key", "", "DESFire authentication key"), // 6 + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), // 6 arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), // 7 arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), // 8 arg_str0("m", "cmode", "", "Communication mode"), // 9 diff --git a/doc/commands.json b/doc/commands.json index 5c2833a2a..1f94cb5e9 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -7207,7 +7207,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7257,7 +7257,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7311,7 +7311,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7344,7 +7344,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7379,7 +7379,7 @@ "options": [ "-h, --help This help", "--aid Use specific AID (3 hex bytes, big endian)", - "-k, --key Key for checking (HEX 8, 16 or 24 bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "-f, --file Filename of dictionary", "--pattern1b Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)", "--pattern2b Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)", @@ -7407,7 +7407,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7432,7 +7432,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7489,7 +7489,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7526,7 +7526,7 @@ "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7570,7 +7570,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7614,7 +7614,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7650,7 +7650,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7687,7 +7687,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7726,7 +7726,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7759,7 +7759,7 @@ "-h, --help This help", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7781,7 +7781,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7805,7 +7805,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7820,22 +7820,22 @@ }, "hf mfdes detect": { "command": "hf mfdes detect", - "description": "Detect key type and tries to find one from the list.", + "description": "Detect PICC master key, key type, communication mode, command set and channel mode. Uses `mfdes_default_keys.dic` per default `--save` it saves details to be used with `hf mfdes default`", "notes": [ - "hf mfdes detect -> detect key 0 from PICC level", - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40", - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary", - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)", - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode" + "hf mfdes detect", + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40", + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary", + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults", + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode" ], "offline": false, "options": [ "-h, --help This help", "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", - "-n, --keyno Key number", + "-n, --keyno Key number (def: all)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7844,7 +7844,7 @@ "--aid Application ID (3 hex bytes, big endian)", "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian).", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", - "-f, --file Filename of dictionary", + "-f, --file Filename of dictionary (default: `mfdes_default_keys`)", "--save Save found key and parameters to defaults" ], "usage": "hf mfdes detect [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-f ] [--save]" @@ -7862,7 +7862,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7889,7 +7889,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7912,7 +7912,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7936,7 +7936,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7959,7 +7959,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7985,7 +7985,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8001,8 +8001,8 @@ "description": "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", "notes": [ "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command", - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup", - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs", + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup" ], "offline": false, "options": [ @@ -8011,7 +8011,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8041,7 +8041,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8070,7 +8070,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8099,7 +8099,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8127,7 +8127,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for authentication", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8157,7 +8157,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8259,7 +8259,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8287,7 +8287,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8318,7 +8318,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8341,7 +8341,7 @@ "options": [ "-h, --help This help", "-v, --verbose Show more output", - "-k, --key Key for computing the MAC, must be HEX 16(AES)", + "-k, --key Key for computing the MAC (16 hex bytes)", "-b, --blk [,[,...]] The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)", "--ka Allow updating key A from inside sector trailers mapped to DESFire files", "--kb Allow updating key B from inside sector trailers mapped to DESFire files", @@ -8401,7 +8401,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8438,7 +8438,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8501,7 +8501,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8543,7 +8543,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8607,7 +8607,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for DESFire authentication", "-t, --algo DESFire auth crypt algo", - "-k, --key DESFire authentication key", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communication mode", @@ -8655,7 +8655,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -16496,6 +16496,6 @@ "metadata": { "commands_extracted": 918, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-11T09:05:59+00:00" + "extracted_on": "2026-09-11T13:13:54+00:00" } } From 7fb520ce18fdad7d0b6dbd20c120d9efcdd2bd44 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 11 Sep 2026 15:17:52 +0200 Subject: [PATCH 25/26] text --- client/src/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 919acedf6..0a4ffb1d7 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -2170,7 +2170,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { snprintf(algostr, sizeof(algostr), "unknown"); } - PrintAndLogEx(INFO, "%s... key num " _YELLOW_("0x%02x") "-" _YELLOW_("0x%02x") ", algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), + PrintAndLogEx(INFO, "%s... key num " _YELLOW_("0x%02x") ".." _YELLOW_("0x%02x") ", algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), (DesfireMFSelected(selectway, id)) ? "PICC level" : DesfireWayIDStr(selectway, id), keynofirst, keynolast, From 6341f40b4cc46da46bdc071b71dd7bbc74a66de3 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 12 Sep 2026 10:44:00 +0200 Subject: [PATCH 26/26] hf mf hardnested: fix the nonce reply length, 9 bytes per pair not 4 per nonce Thanks @TheArchitect0880 for pointing it out and suggested a first fix. MifareAcquireEncryptedNonces packs two 4 byte encrypted nonces plus one byte holding both their encrypted parity nibbles into every entry, but the reply declared num_nonces * 4 bytes. The client walks that buffer 9 bytes at a time, so on RDV4 it read 612 bytes out of a 544 byte payload and handed roughly 15 of every 136 nonces to add_nonce() from stale packet buffer content. Those fake nonces went into the .bin nonce file too. Count pairs instead of bytes. num_nonces now reports whole pairs only, so a button abort or a static nonce bailout part way through a pair drops the dangling nonce rather than shipping a half built entry whose parity nibble was never filled in. MFC_NONCE_PAIR_SIZE and MFC_MAX_NONCE_PAIRS document the layout next to mf_nonces_resp_t so the 9 vs 4 confusion cannot come back, and the client now refuses a reply too short for the nonce count it carries. Both acquisition functions collect straight into the reply buffer rather than a second PM3_CMD_DATA_SIZE stack array, which halves the stack used per call. MifareAcquireNonces also returned isOK = 2 on button press, which is not a PM3_* status; that is PM3_EOPABORTED now. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 7 +++--- armsrc/mifarecmd.c | 47 +++++++++++++++++++++++++--------------- client/src/cmdhfmfhard.c | 15 ++++++++++--- include/pm3_cmd.h | 8 +++++++ 4 files changed, 53 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f192a65a2..92a8d833d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,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] -- Changed `hf mfdes detect` - with no `-n` it now sweeps every key number the application declares instead of only key 0; the first hit pins the algo for the rest (@iceman1001) -- Fixed `hf mfdes detect` - the card error counter was shared by every key type, so a bad run during the DES pass could abort the AES pass before it tried a single key (@iceman1001) -- Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list,it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) +- Fixed `hf mf hardnested` - the device declared `num_nonces * 4` bytes but packs 9 bytes per nonce pair. Thanks @TheArchitect0880 (@iceman1001) +- Changed `hf mfdes detect` - with no `-n` it now sweeps every key number the application declares instead of only key 0 (@iceman1001) +- Fixed `hf mfdes detect` - the card error counter was shared by every key type, so a bad run during the DES pass could abort the AES pass (@iceman1001) +- Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list, it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) - Fixed `hf mfdes detect` - LRP was only found when the key settings happened to be unreadable (@iceman1001) - Added `hf mfdes chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) - Fixed `hf mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c35953ac0..d803ce08e 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -991,9 +991,14 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCES * 4)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; + uint32_t cuid = 0; - int16_t isOK = 0; + int16_t isOK = PM3_SUCCESS; uint16_t num_nonces = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1019,7 +1024,7 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { // Test if the action was cancelled if (BUTTON_PRESS()) { - isOK = 2; + isOK = PM3_EOPABORTED; field_off = true; break; } @@ -1072,12 +1077,12 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // one bare 4 byte nonce per entry here, unlike the paired layout used by + // MifareAcquireEncryptedNonces. The loop above already caps num_nonces + uint16_t noncelen = num_nonces * 4; response->cuid = cuid; response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); reply_ng(CMD_HF_MIFARE_ACQ_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); @@ -1106,12 +1111,17 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par_enc[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCE_PAIRS * MFC_NONCE_PAIR_SIZE)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; uint64_t ui64Key = bytes_to_num(payload->key, 6); uint32_t cuid = 0; int16_t isOK = PM3_SUCCESS; uint16_t num_nonces = 0; + uint16_t num_pairs = 0; uint8_t nt_par_enc = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1139,7 +1149,7 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t prev_enc_nt[] = {0, 0, 0, 0}; uint8_t prev_counter = 0; - for (uint16_t i = 0; i <= (MFC_MAX_NONCES * 4) - 9;) { + while (num_pairs < MFC_MAX_NONCE_PAIRS) { // Test if the action was cancelled if (BUTTON_PRESS()) { @@ -1196,14 +1206,15 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { } num_nonces++; + uint16_t ofs = num_pairs * MFC_NONCE_PAIR_SIZE; if (num_nonces % 2) { - memcpy(buf + i, receivedAnswer, 4); + memcpy(buf + ofs, receivedAnswer, 4); nt_par_enc = par_enc[0] & 0xf0; } else { nt_par_enc |= par_enc[0] >> 4; - memcpy(buf + i + 4, receivedAnswer, 4); - memcpy(buf + i + 8, &nt_par_enc, 1); - i += 9; + memcpy(buf + ofs + 4, receivedAnswer, 4); + buf[ofs + 8] = nt_par_enc; + num_pairs++; } @@ -1231,12 +1242,12 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); crypto1_deinit(pcs); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // only whole pairs are transferred. An abort or a static nonce bailout can + // leave a dangling first nonce, it has no parity nibble yet so it is dropped + uint16_t noncelen = num_pairs * MFC_NONCE_PAIR_SIZE; response->cuid = cuid; - response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); + response->num_nonces = num_pairs * 2; reply_ng(CMD_HF_MIFARE_ACQ_ENCRYPTED_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 3f3f47b1b..88204437f 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -1733,9 +1733,18 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ if (initialize == false) { const mf_nonces_resp_t *nresp = (const mf_nonces_resp_t *)resp.data.asBytes; - uint16_t num_sampled_nonces = nresp->num_nonces; + uint16_t num_sampled_nonces = nresp->num_nonces & ~1; // nonces come in pairs const uint8_t *bufp = nresp->nonces; + if (resp.length < sizeof(mf_nonces_resp_t) + ((num_sampled_nonces / 2) * MFC_NONCE_PAIR_SIZE)) { + PrintAndLogEx(FAILED, "Truncated nonce reply, got %u bytes for %u nonces", resp.length, num_sampled_nonces); + if (nonce_file_write) { + fclose(fnonces); + } + DropField(); + return PM3_ESOFT; + } + for (uint16_t i = 0; i < num_sampled_nonces; i += 2) { uint32_t nt_enc1 = bytes_to_num(bufp, 4); uint32_t nt_enc2 = bytes_to_num(bufp + 4, 4); @@ -1760,10 +1769,10 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ num_acquired_nonces += add_res; if (nonce_file_write) { - fwrite(bufp, 1, 9, fnonces); + fwrite(bufp, 1, MFC_NONCE_PAIR_SIZE, fnonces); fflush(fnonces); } - bufp += 9; + bufp += MFC_NONCE_PAIR_SIZE; } //total_num_nonces += num_sampled_nonces; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 56f643c35..c0268adcd 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -541,6 +541,14 @@ typedef struct { // most 4 byte nonces that fit alongside the reply header in one frame #define MFC_MAX_NONCES ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / 4) +// ACQ_ENCRYPTED_NONCES does not store bare nonces. It stores pairs: two 4 byte +// encrypted nonces followed by one byte holding both their encrypted parity +// nibbles, high nibble first. num_nonces in the reply counts nonces, so the +// payload is always (num_nonces / 2) * MFC_NONCE_PAIR_SIZE bytes and +// num_nonces is always even. +#define MFC_NONCE_PAIR_SIZE 9 +#define MFC_MAX_NONCE_PAIRS ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / MFC_NONCE_PAIR_SIZE) + // CMD_HF_MIFARE_CHKKEYS_FAST payload. // Replaces three bit-packed oldargs: // arg0 = sectorcnt | firstchunk<<8 | lastchunk<<12 | singlesector_params<<16