From 89c23828a0c19717aa2b10e94a72585274376e31 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 10:50:05 +0200 Subject: [PATCH 01/22] Create a small kgh_tools.exe that runs in Windows and can be used from another program to read a badge number, write a new KGH badge (given a badge number). You also have to provide a stamp (as .bin file, 4 bytes). The tool can also get a full set of info from a KGH badge in JSON form (including checking KGH crc for correctness). All based on publicly available knowledge, existing lua scripts, and careful obeservations! --- client/experimental_lib/CMakeLists.txt | 66 ++ client/experimental_lib/KGH_TOOLS_BUILD.md | 30 + .../example_c/legic_migrate_tool.c | 584 ++++++++++++++++++ client/src/cmdhflegic.c | 61 +- client/src/cmdhflegic.h | 6 + client/src/pm3line.c | 23 +- 6 files changed, 755 insertions(+), 15 deletions(-) create mode 100644 client/experimental_lib/KGH_TOOLS_BUILD.md create mode 100644 client/experimental_lib/example_c/legic_migrate_tool.c diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index 5c82868fb..764b25933 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -56,6 +56,13 @@ if (NOT SKIPPYTHON EQUAL 1) pkg_search_module(PYTHON3EMBED QUIET ${PYTHON3_PKGCONFIG}-embed) endif (NOT SKIPPYTHON EQUAL 1) +if (MINGW) + # Prefer static archives for kiosk-style single-exe deployments. + set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) + set(ZLIB_USE_STATIC_LIBS ON) + set(BZIP2_USE_STATIC_LIBS ON) +endif() + # If cross-compiled, we need to init source and build. if (CMAKE_TOOLCHAIN_FILE) if (ANDROID) @@ -495,17 +502,26 @@ endif(NOT SKIPREADLINE EQUAL 1) if (BZIP2_FOUND) set(ADDITIONAL_DIRS ${BZIP2_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) + if (MINGW) + set(BZIP2_LIBRARIES /mingw64/lib/libbz2.a) + endif() set(ADDITIONAL_LNK ${BZIP2_LIBRARIES} ${ADDITIONAL_LNK}) endif (BZIP2_FOUND) if (LZ4_FOUND) set(ADDITIONAL_DIRS ${LZ4_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) + if (MINGW) + set(LZ4_LIBRARIES /mingw64/lib/liblz4.a) + endif() set(ADDITIONAL_LNK ${LZ4_LIBRARIES} ${ADDITIONAL_LNK}) endif (LZ4_FOUND) if (ZLIB_FOUND) add_definitions("-DHAVE_ZLIB") set(ADDITIONAL_DIRS ${ZLIB_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) + if (MINGW) + set(ZLIB_LIBRARIES /mingw64/lib/libz.a) + endif() set(ADDITIONAL_LNK ${ZLIB_LIBRARIES} ${ADDITIONAL_LNK}) endif (ZLIB_FOUND) @@ -671,7 +687,32 @@ add_library(pm3rrg_rdv4 SHARED ${ADDITIONAL_SRC} ) +add_library(pm3rrg_rdv4_static STATIC + ${PM3_ROOT}/client/src/proxmark3.c + ${PM3_ROOT}/client/src/guidummy.cpp + ${TARGET_SOURCES} + ${ADDITIONAL_SRC} +) + +add_executable(kgh_tools + ${PM3_ROOT}/client/experimental_lib/example_c/legic_migrate_tool.c +) + +set_target_properties(kgh_tools PROPERTIES OUTPUT_NAME "kgh_tools") +if (MINGW) + target_link_options(kgh_tools PRIVATE -static -static-libgcc) +endif() + +target_link_libraries(kgh_tools PRIVATE pm3rrg_rdv4_static) +target_include_directories(kgh_tools PRIVATE + ${PM3_ROOT}/common + ${PM3_ROOT}/client/include + ${PM3_ROOT}/client/src + ${PM3_ROOT}/include +) + target_compile_definitions(pm3rrg_rdv4 PRIVATE LIBPM3) +target_compile_definitions(pm3rrg_rdv4_static PRIVATE LIBPM3) if (UNIX AND NOT APPLE) # Fail the build if a client source file is missing from TARGET_SOURCES. @@ -680,6 +721,7 @@ if (UNIX AND NOT APPLE) endif() target_compile_options(pm3rrg_rdv4 PUBLIC -Wall -Werror -O3) +target_compile_options(pm3rrg_rdv4_static PUBLIC -Wall -Werror -O3) if (EMBED_READLINE) if (NOT SKIPREADLINE EQUAL 1) add_dependencies(pm3rrg_rdv4 ncurses readline) @@ -726,6 +768,15 @@ target_include_directories(pm3rrg_rdv4 PRIVATE ${ADDITIONAL_DIRS} ) +target_include_directories(pm3rrg_rdv4_static PRIVATE + ${PM3_ROOT}/common + ${PM3_ROOT}/common_fpga + ${PM3_ROOT}/include + ${PM3_ROOT}/client/src + ${PM3_ROOT}/client/include + ${ADDITIONAL_DIRS} +) + if (NOT APPLE) # required for Raspberry Pi, but breaks with clang (OSX). Need to be at the end of the linker line. set(ADDITIONAL_LNK ${ADDITIONAL_LNK} -Wl,--as-needed -latomic -Wl,--no-as-needed) @@ -763,8 +814,23 @@ target_link_libraries(pm3rrg_rdv4 PRIVATE pm3rrg_rdv4_vec ${ADDITIONAL_LNK}) +target_link_libraries(pm3rrg_rdv4_static PRIVATE + m + pm3rrg_rdv4_mbedtls + pm3rrg_rdv4_cliparser + pm3rrg_rdv4_lua + pm3rrg_rdv4_tinycbor + pm3rrg_rdv4_amiibo + pm3rrg_rdv4_reveng + pm3rrg_rdv4_hardnested + pm3rrg_rdv4_id48 + pm3rrg_rdv4_mqtt + pm3rrg_rdv4_vec + ${ADDITIONAL_LNK}) + if (NOT SKIPPTHREAD EQUAL 1) target_link_libraries(pm3rrg_rdv4 PRIVATE pthread) + target_link_libraries(pm3rrg_rdv4_static PRIVATE pthread) endif (NOT SKIPPTHREAD EQUAL 1) if (NOT SKIPPYTHON EQUAL 1) diff --git a/client/experimental_lib/KGH_TOOLS_BUILD.md b/client/experimental_lib/KGH_TOOLS_BUILD.md new file mode 100644 index 000000000..bd969dc05 --- /dev/null +++ b/client/experimental_lib/KGH_TOOLS_BUILD.md @@ -0,0 +1,30 @@ +# kgh_tools Build Notes + +## Configure And Build + +Do this in ProxSpace: + +```bash +cd ~/proxmark3_rfrg/client/experimental_lib +rm -rf build-lite +cmake -G "MSYS Makefiles" -S . -B build-lite \ + -DSKIPPYTHON=1 \ + -DSKIPREADLINE=1 \ + -DSKIPJANSSYSTEM=1 \ + -DSKIPWHEREAMISYSTEM=1 \ + -DSKIPBT=1 +cmake --build build-lite --target kgh_tools -j +objdump -p build-lite/kgh_tools.exe | grep -i "DLL Name" +``` + +## Static Link Notes + +- `kgh_tools` is linked against `pm3rrg_rdv4_static`. +- On MinGW, CMake adds `-static -static-libgcc` for the target. +- If CMakeCache paths change between ProxSpace and a native shell, delete `build-lite` and reconfigure. + +## Existing Helper Scripts + +- `01make_lib.sh` creates `build/`, runs `cmake ..`, then `make -j`. +- `01make_lib_continue.sh` reruns `make -j` in `build/`. +- `00make_swig.sh` regenerates the SWIG wrappers before building the library. diff --git a/client/experimental_lib/example_c/legic_migrate_tool.c b/client/experimental_lib/example_c/legic_migrate_tool.c new file mode 100644 index 000000000..bb6e87eb1 --- /dev/null +++ b/client/experimental_lib/example_c/legic_migrate_tool.c @@ -0,0 +1,584 @@ +#include +#include +#include +#include +#include + +#include "pm3.h" +#include "pm3_cmd.h" +#include "legic.h" +#include "cmdhflegic.h" +#include "ui.h" +#include "util.h" +#include "util_posix.h" +#include "crc.h" + +static pm3 *open_pm3_with_retry(const char *port) { + for (int i = 0; i < 3; ++i) { + pm3 *dev = pm3_open(port); + if (g_session.pm3_present) { + return dev; + } + msleep(250); + } + return pm3_open(port); +} + +static bool has_flag(int argc, char *argv[], const char *flag) { + for (int i = 2; i < argc; ++i) { + if (strcmp(argv[i], flag) == 0) { + return true; + } + } + return false; +} + +static const uint8_t k_legic_template_head[35] = { + 0x3e, 0x00, 0x00, 0xb6, 0x00, 0x60, 0xea, 0x9f, 0xff, 0x00, 0x00, 0x00, 0x11, 0x01, 0x06, 0x80, + 0x00, 0x00, 0xeb, 0xa1, 0x00, 0x00, 0x0d, 0xc0, 0x08, 0x00, 0x2f, 0x73, 0x73, 0x73, 0x73, 0x62, + 0x62, 0x62, 0x54 +}; + +static bool encode_badge_bcd(uint32_t badge, uint8_t out[3]) { + if (badge > 999999u) { + return false; + } + + uint32_t digits[6] = {0}; + for (int i = 5; i >= 0; --i) { + digits[i] = badge % 10u; + badge /= 10u; + } + + out[0] = (uint8_t)((digits[0] << 4) | digits[1]); + out[1] = (uint8_t)((digits[2] << 4) | digits[3]); + out[2] = (uint8_t)((digits[4] << 4) | digits[5]); + return true; +} + +static bool decode_badge_bcd(const uint8_t in[3], uint32_t *badge_out) { + uint32_t digits[6] = { + (uint32_t)(in[0] >> 4), (uint32_t)(in[0] & 0x0F), + (uint32_t)(in[1] >> 4), (uint32_t)(in[1] & 0x0F), + (uint32_t)(in[2] >> 4), (uint32_t)(in[2] & 0x0F) + }; + + for (size_t i = 0; i < 6; ++i) { + if (digits[i] > 9u) { + return false; + } + } + + *badge_out = digits[0] * 100000u + digits[1] * 10000u + digits[2] * 1000u + digits[3] * 100u + digits[4] * 10u + digits[5]; + return true; +} + +static bool parse_badge_text(const char *text, uint32_t *badge_out) { + if (text == NULL || *text == '\0') { + return false; + } + + char *end = NULL; + unsigned long badge = strtoul(text, &end, 10); + if (end == text || *end != '\0' || badge > 999999UL) { + return false; + } + + *badge_out = (uint32_t)badge; + return true; +} + +static bool parse_stamp_hex(const char *text, uint8_t stamp[4]) { + if (text == NULL || strlen(text) != 8) { + return false; + } + + for (int i = 0; i < 4; ++i) { + char byte_str[3] = { text[i * 2], text[i * 2 + 1], '\0' }; + char *end = NULL; + long value = strtol(byte_str, &end, 16); + if (end == byte_str || *end != '\0' || value < 0 || value > 255) { + return false; + } + stamp[i] = (uint8_t)value; + } + + return true; +} + +static bool load_stamp_file(const char *path, uint8_t stamp[4]) { + FILE *fp = fopen(path, "rb"); + if (fp == NULL) { + return false; + } + + uint8_t buf[4] = {0}; + size_t read_len = fread(buf, 1, sizeof(buf), fp); + int extra = fgetc(fp); + fclose(fp); + + if (read_len != sizeof(buf) || extra != EOF) { + return false; + } + + memcpy(stamp, buf, sizeof(buf)); + return true; +} + +static bool get_arg_value(int argc, char *argv[], const char *flag, const char **value) { + for (int i = 3; i < argc - 1; ++i) { + if (strcmp(argv[i], flag) == 0) { + *value = argv[i + 1]; + return true; + } + } + return false; +} + +static void apply_stamp(uint8_t *dump, size_t dump_len, const uint8_t stamp[4]) { + if (dump_len <= 30) { + return; + } + memcpy(dump + 27, stamp, 4); +} + +static void build_migration_dump(uint32_t badge, const uint8_t stamp[4], uint8_t *dump, size_t dump_len) { + memset(dump, 0, dump_len); + memcpy(dump, k_legic_template_head, sizeof(k_legic_template_head)); + apply_stamp(dump, dump_len, stamp); + uint8_t bcd[3] = {0}; + if (!encode_badge_bcd(badge, bcd)) { + fprintf(stderr, "badge number out of range\n"); + exit(EXIT_FAILURE); + } + + dump[31] = bcd[0]; + dump[32] = bcd[1]; + dump[33] = bcd[2]; + dump[34] = 0xBD; +} + +typedef struct { + uint8_t *dump; + uint16_t len; + legic_card_select_t card; +} legic_read_result_t; + +static bool read_legic_dump(legic_read_result_t *res, bool verbose) { + memset(res, 0, sizeof(*res)); + + uint8_t prev_print = g_printAndLog; + g_printAndLog &= ~PRINTANDLOG_PRINT; + + for (int attempt = 0; attempt < 3; ++attempt) { + free(res->dump); + memset(res, 0, sizeof(*res)); + + if (legic_get_type(&res->card) != PM3_SUCCESS) { + if (verbose) { + fprintf(stderr, "read_info retry %d: legic_get_type failed\n", attempt + 1); + } + msleep(100); + continue; + } + + res->dump = calloc(res->card.cardsize, sizeof(uint8_t)); + if (res->dump == NULL) { + g_printAndLog = prev_print; + return false; + } + + int status = legic_read_mem(0, res->card.cardsize, 0x55, res->dump, &res->len); + if (status != PM3_SUCCESS || res->len < 35) { + if (verbose) { + fprintf(stderr, "read_info retry %d: legic_read_mem failed\n", attempt + 1); + } + msleep(100); + continue; + } + + uint8_t crc = res->dump[4]; + if (CRC8Legic(res->dump, 4) != crc) { + if (verbose) { + fprintf(stderr, "read_info retry %d: header crc mismatch\n", attempt + 1); + } + msleep(100); + continue; + } + + for (uint16_t i = 22; i < res->len; ++i) { + res->dump[i] ^= crc; + } + + g_printAndLog = prev_print; + return true; + } + + free(res->dump); + memset(res, 0, sizeof(*res)); + g_printAndLog = prev_print; + return false; +} + +static void free_legic_read_result(legic_read_result_t *res) { + free(res->dump); + res->dump = NULL; + res->len = 0; + memset(&res->card, 0, sizeof(res->card)); +} + +static const char *classify_legic_card(const uint8_t *dump, uint16_t len) { + if (len < 9) { + return "unknown"; + } + + uint16_t dcf = ((uint16_t)dump[6] << 8) | dump[5]; + if (dcf == 0xFFFF) { + return "NM"; + } + + if (dcf > 60000u) { + return "IAM"; + } + + if ((dump[7] & 0x0F) == 0x0F && dump[8] == 0xFF) { + return "KGH"; + } + + return "unknown"; +} + +static bool check_kgh_crc_ok(const uint8_t *dump, uint16_t len) { + if (strcmp(classify_legic_card(dump, len), "KGH") != 0) { + return false; + } + + if (len <= 34) { + return false; + } + + uint8_t *copy = calloc(len, sizeof(uint8_t)); + if (copy == NULL) { + return false; + } + + memcpy(copy, dump, len); + const uint8_t uid[4] = { copy[0], copy[1], copy[2], copy[3] }; + bool ok = legic_clone_update_segment_crcs(copy, len, uid) && legic_clone_update_kgh_crcs(copy, len, uid) && (copy[34] == dump[34]); + free(copy); + return ok; +} + +static bool check_kgh_crc_calc(const uint8_t *dump, uint16_t len, uint8_t *crc_out) { + if (strcmp(classify_legic_card(dump, len), "KGH") != 0) { + return false; + } + + if (len <= 34) { + return false; + } + + uint8_t *copy = calloc(len, sizeof(uint8_t)); + if (copy == NULL) { + return false; + } + + memcpy(copy, dump, len); + const uint8_t uid[4] = { copy[0], copy[1], copy[2], copy[3] }; + if (!legic_clone_update_segment_crcs(copy, len, uid) || !legic_clone_update_kgh_crcs(copy, len, uid)) { + free(copy); + return false; + } + + *crc_out = copy[34]; + bool ok = (*crc_out == dump[34]); + free(copy); + return ok; +} + +static bool has_extra_segments(const uint8_t *dump, uint16_t len) { + size_t start = 22; + bool saw_first = false; + + while (start + 5 <= len) { + uint16_t seg_len = (((uint16_t)dump[start + 1] & 0x0F) << 8) | dump[start]; + if (seg_len < 5 || start + seg_len > len) { + break; + } + + if (saw_first) { + return true; + } + + saw_first = true; + if (start + seg_len >= len) { + break; + } + + start += seg_len; + } + + return false; +} + +static bool check_segment_crc_ok(const uint8_t *dump, uint16_t len) { + if (len < 27) { + return false; + } + + uint8_t prev_print = g_printAndLog; + g_printAndLog &= ~PRINTANDLOG_PRINT; + + uint8_t *copy = calloc(len, sizeof(uint8_t)); + if (copy == NULL) { + g_printAndLog = prev_print; + return false; + } + + memcpy(copy, dump, len); + const uint8_t uid[4] = { copy[0], copy[1], copy[2], copy[3] }; + bool ok = legic_clone_update_segment_crcs(copy, len, uid) && (memcmp(copy, dump, len) == 0); + free(copy); + g_printAndLog = prev_print; + return ok; +} + +static bool check_segment_crc_calc(const uint8_t *dump, uint16_t len, uint8_t *crc_out) { + if (len < 27) { + return false; + } + + uint8_t prev_print = g_printAndLog; + g_printAndLog &= ~PRINTANDLOG_PRINT; + + uint8_t *copy = calloc(len, sizeof(uint8_t)); + if (copy == NULL) { + g_printAndLog = prev_print; + return false; + } + + memcpy(copy, dump, len); + const uint8_t uid[4] = { copy[0], copy[1], copy[2], copy[3] }; + if (!legic_clone_update_segment_crcs(copy, len, uid)) { + free(copy); + g_printAndLog = prev_print; + return false; + } + + *crc_out = copy[26]; + bool ok = (memcmp(copy, dump, len) == 0); + free(copy); + g_printAndLog = prev_print; + return ok; +} + +static bool decode_badge_value(const uint8_t *dump, uint16_t len, uint32_t *badge_out) { + if (len < 34) { + return false; + } + return decode_badge_bcd(&dump[31], badge_out); +} + +static void print_json_string(const char *key, const char *value, bool last) { + printf("\"%s\": \"%s\"%s", key, value, last ? "" : ","); +} + +static void print_json_bool(const char *key, bool value, bool last) { + printf("\"%s\": %s%s", key, value ? "true" : "false", last ? "" : ","); +} + +static void print_json_uint32(const char *key, uint32_t value, bool last) { + printf("\"%s\": %u%s", key, value, last ? "" : ","); +} + +static void print_json_null(const char *key, bool last) { + printf("\"%s\": null%s", key, last ? "" : ","); +} + +static void print_read_info_json(const legic_read_result_t *res) { + const uint8_t *dump = res->dump; + uint16_t len = res->len; + uint32_t calc_mcc = (uint32_t)CRC8Legic((uint8_t *)dump, 4); + bool mcc_ok = (calc_mcc == dump[4]); + bool is_kgh = (strcmp(classify_legic_card(dump, len), "KGH") == 0); + bool segment_crc_ok = check_segment_crc_ok(dump, len); + bool kgh_crc_ok = check_kgh_crc_ok(dump, len); + uint8_t segment_header_crc_calc = 0; + uint8_t kgh_segment_crc_calc = 0; + (void)check_segment_crc_calc(dump, len, &segment_header_crc_calc); + (void)(is_kgh ? check_kgh_crc_calc(dump, len, &kgh_segment_crc_calc) : false); + char segment_header_crc_calc_hex[3] = {0}; + char kgh_segment_crc_calc_hex[3] = {0}; + snprintf(segment_header_crc_calc_hex, sizeof(segment_header_crc_calc_hex), "%02X", segment_header_crc_calc); + if (is_kgh) { + snprintf(kgh_segment_crc_calc_hex, sizeof(kgh_segment_crc_calc_hex), "%02X", kgh_segment_crc_calc); + } + bool extra_segments = has_extra_segments(dump, len); + + uint32_t badge = 0; + bool badge_ok = decode_badge_value(dump, len, &badge); + char badge_raw[16] = {0}; + if (!badge_ok) { + snprintf(badge_raw, sizeof(badge_raw), "0x%02X%02X%02X", dump[31], dump[32], dump[33]); + } + + printf("{"); + print_json_string("card_type", classify_legic_card(dump, len), false); + print_json_string("mcd", sprint_hex_inrow((uint8_t *)dump, 1), false); + print_json_string("msn", sprint_hex_inrow((uint8_t *)dump + 1, 3), false); + print_json_string("mcc", sprint_hex_inrow((uint8_t *)dump + 4, 1), false); + print_json_bool("mcc_ok", mcc_ok, false); + print_json_string("dcf", sprint_hex_inrow((uint8_t *)dump + 5, 2), false); + print_json_bool("segment_header_crc_ok", segment_crc_ok, false); + print_json_string("segment_header_crc", sprint_hex_inrow((uint8_t *)dump + 26, 1), false); + print_json_string("segment_header_crc_calc", segment_header_crc_calc_hex, false); + print_json_bool("is_kgh", is_kgh, false); + print_json_bool("has_extra_segments", extra_segments, false); + + if (is_kgh) { + char stamp[16] = {0}; + snprintf(stamp, sizeof(stamp), "%02X%02X%02X%02X", dump[27], dump[28], dump[29], dump[30]); + print_json_string("stamp", stamp, false); + print_json_string("kgh_segment_crc", sprint_hex_inrow((uint8_t *)dump + 34, 1), false); + print_json_string("kgh_segment_crc_calc", kgh_segment_crc_calc_hex, false); + if (badge_ok) { + print_json_uint32("badge_number", badge, false); + print_json_null("badge_number_raw", false); + print_json_string("badge_number_format", "dec", false); + } else { + print_json_null("badge_number", false); + print_json_string("badge_number_raw", badge_raw, false); + print_json_string("badge_number_format", "hex", false); + } + print_json_bool("kgh_segment_crc_ok", kgh_crc_ok, true); + } else { + print_json_null("stamp", false); + print_json_null("kgh_segment_crc", false); + print_json_null("kgh_segment_crc_calc", false); + print_json_null("badge_number", false); + print_json_null("badge_number_raw", false); + print_json_null("badge_number_format", false); + print_json_bool("kgh_segment_crc_ok", false, true); + } + printf("}\n"); +} + +static int read_badge_from_card(uint32_t *badge_out) { + uint8_t prev_print = g_printAndLog; + g_printAndLog &= ~PRINTANDLOG_PRINT; + + legic_card_select_t card; + if (legic_get_type(&card) != PM3_SUCCESS) { + g_printAndLog = prev_print; + return 1; + } + + uint8_t *dump = calloc(card.cardsize, sizeof(uint8_t)); + if (dump == NULL) { + g_printAndLog = prev_print; + return 1; + } + + uint16_t datalen = 0; + int status = legic_read_mem(0, card.cardsize, 0x55, dump, &datalen); + if (status != PM3_SUCCESS || datalen < 35) { + free(dump); + g_printAndLog = prev_print; + return 1; + } + + uint8_t crc = dump[4]; + if (CRC8Legic(dump, 4) != crc) { + free(dump); + g_printAndLog = prev_print; + return 1; + } + + for (uint16_t i = 22; i < datalen; ++i) { + dump[i] ^= crc; + } + + bool ok = decode_badge_bcd(&dump[31], badge_out); + free(dump); + g_printAndLog = prev_print; + return ok ? 0 : 1; +} + +int main(int argc, char *argv[]) { + if (argc < 3) { + fprintf(stderr, "Usage:\n"); + fprintf(stderr, " %s read_badge_number [-v|--verbose]\n", argv[0]); + fprintf(stderr, " %s read_info\n", argv[0]); + fprintf(stderr, " %s write_card (--stamp-file | --stamp-hex <8hex>)\n", argv[0]); + return EXIT_FAILURE; + } + + g_session.incognito = true; + bool verbose = has_flag(argc, argv, "-v") || has_flag(argc, argv, "--verbose"); + g_printAndLog = verbose ? PRINTANDLOG_PRINT : 0; + pm3 *dev = open_pm3_with_retry(argv[1]); + int rc = EXIT_FAILURE; + + if (strcmp(argv[2], "read_badge_number") == 0) { + uint32_t badge = 0; + if (read_badge_from_card(&badge) == 0) { + printf("%u\n", badge); + rc = EXIT_SUCCESS; + } + } else if (strcmp(argv[2], "read_info") == 0) { + legic_read_result_t res; + if (read_legic_dump(&res, verbose)) { + print_read_info_json(&res); + rc = EXIT_SUCCESS; + free_legic_read_result(&res); + } else if (verbose) { + fprintf(stderr, "failed to read card info\n"); + } + } else if (strcmp(argv[2], "write_card") == 0) { + if (argc < 4) { + fprintf(stderr, "missing badge number\n"); + } else { + uint32_t badge = 0; + if (!parse_badge_text(argv[3], &badge)) { + fprintf(stderr, "invalid badge number\n"); + pm3_close(dev); + return EXIT_FAILURE; + } + const char *stamp_file = NULL; + const char *stamp_hex = NULL; + bool has_file = get_arg_value(argc, argv, "--stamp-file", &stamp_file); + bool has_hex = get_arg_value(argc, argv, "--stamp-hex", &stamp_hex); + if (has_file == has_hex) { + fprintf(stderr, "specify exactly one of --stamp-file or --stamp-hex\n"); + pm3_close(dev); + return EXIT_FAILURE; + } + + uint8_t stamp[4] = {0}; + if (has_file) { + if (!load_stamp_file(stamp_file, stamp)) { + fprintf(stderr, "failed to load stamp file\n"); + pm3_close(dev); + return EXIT_FAILURE; + } + } else if (!parse_stamp_hex(stamp_hex, stamp)) { + fprintf(stderr, "invalid stamp hex\n"); + pm3_close(dev); + return EXIT_FAILURE; + } + + uint8_t dump[35] = {0}; + build_migration_dump(badge, stamp, dump, sizeof(dump)); + if (legic_migrate_dump(dump, sizeof(dump), true, (const uint8_t[2]){0x60, 0xEA}, true) == PM3_SUCCESS) { + rc = EXIT_SUCCESS; + } else { + fprintf(stderr, "failed to write card\n"); + } + } + } else { + fprintf(stderr, "unknown command: %s\n", argv[2]); + } + + pm3_close(dev); + return rc; +} diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index 8d90fa6f6..367f9a86c 100644 --- a/client/src/cmdhflegic.c +++ b/client/src/cmdhflegic.c @@ -58,13 +58,13 @@ static bool legic_xor(uint8_t *data, uint16_t cardsize) { return true; } -static void legic_xor_with_crc(uint8_t *data, uint16_t cardsize, uint8_t crc) { +void legic_xor_with_crc(uint8_t *data, uint16_t cardsize, uint8_t crc) { for (uint16_t i = 22; i < cardsize; i++) { data[i] ^= crc; } } -static bool legic_clone_update_segment_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]) { +bool legic_clone_update_segment_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]) { // Segment headers are parsed from offset 22 everywhere else in LEGIC decoding. size_t start = 22; bool found_segment = false; @@ -96,7 +96,7 @@ static bool legic_clone_update_segment_crcs(uint8_t *data, size_t bytes_read, co return true; } -static bool legic_clone_update_kgh_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]) { +bool legic_clone_update_kgh_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]) { // Decoded segmented payload starts at byte 22. size_t start = 22; bool found_kgh = false; @@ -142,7 +142,7 @@ static bool legic_clone_update_kgh_crcs(uint8_t *data, size_t bytes_read, const return true; } -static int legic_write_bytes_to_tag(uint16_t offset, uint8_t iv, const uint8_t *data, size_t bytes_read, const char *verb) { +int legic_write_bytes_to_tag(uint16_t offset, uint8_t iv, const uint8_t *data, size_t bytes_read, const char *verb) { PrintAndLogEx(SUCCESS, "%s", verb); // fast push mode @@ -183,21 +183,68 @@ static int legic_write_bytes_to_tag(uint16_t offset, uint8_t iv, const uint8_t * PrintAndLogEx(NORMAL, ""); if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Failed writing tag"); + PrintAndLogEx(WARNING, "Failed writing tag at offset %zu len %zu. Status: %d", i, len, resp.status); g_conn.block_after_ACK = false; return PM3_ERFTRANS; } - PrintAndLogEx(SUCCESS, "Wrote chunk [offset %zu | len %zu | total %zu", i, len, i + len); + PrintAndLogEx(SUCCESS, "Wrote chunk [offset %zu | len %zu | end %zu of %zu]", i, len, i + len, bytes_read); } g_conn.block_after_ACK = false; return PM3_SUCCESS; } -static int legic_write_dump_to_tag(uint8_t *dump, size_t bytes_read) { +int legic_write_dump_to_tag(uint8_t *dump, size_t bytes_read) { return legic_write_bytes_to_tag(7, 0x55, dump, bytes_read, "Restoring to card"); } +int legic_migrate_dump(uint8_t *dump, size_t bytes_read, bool rewrite_kgh, const uint8_t dcf[2], bool allow_dcf) { + if (dump == NULL || bytes_read <= 22) { + return PM3_EINVARG; + } + + if (dcf != NULL && !allow_dcf) { + return PM3_EINVARG; + } + + legic_card_select_t card; + if (legic_get_type(&card) != PM3_SUCCESS) { + return PM3_ESOFT; + } + + if (card.cardsize < bytes_read) { + return PM3_EFILE; + } + + uint8_t target_uid[4] = {0}; + memcpy(target_uid, card.uid, sizeof(target_uid)); + uint8_t target_mcc = (uint8_t)CRC8Legic(target_uid, sizeof(target_uid)); + + if (!legic_clone_update_segment_crcs(dump, bytes_read, target_uid)) { + return PM3_EFAILED; + } + if (rewrite_kgh && !legic_clone_update_kgh_crcs(dump, bytes_read, target_uid)) { + return PM3_EFAILED; + } + + memcpy(dump, target_uid, sizeof(target_uid)); + dump[4] = target_mcc; + legic_xor_with_crc(dump, bytes_read, dump[4]); + + int write_res = legic_write_dump_to_tag(dump, bytes_read); + if (write_res != PM3_SUCCESS) { + return write_res; + } + + if (dcf != NULL) { + uint8_t dcf_dump[7] = {0}; + memcpy(dcf_dump + 5, dcf, 2); + return legic_write_bytes_to_tag(5, 0x55, dcf_dump, sizeof(dcf_dump), "Applying explicit DCF update"); + } + + return PM3_SUCCESS; +} + static int CmdLegicMigrate(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf legic migrate", diff --git a/client/src/cmdhflegic.h b/client/src/cmdhflegic.h index 9f5681845..3ad60fe43 100644 --- a/client/src/cmdhflegic.h +++ b/client/src/cmdhflegic.h @@ -31,5 +31,11 @@ int legic_get_type(legic_card_select_t *card); void legic_chk_iv(uint32_t *iv); void legic_seteml(uint8_t *src, uint32_t offset, uint32_t numofbytes); int legic_read_mem(uint32_t offset, uint32_t len, uint32_t iv, uint8_t *out, uint16_t *outlen); +int legic_migrate_dump(uint8_t *dump, size_t bytes_read, bool rewrite_kgh, const uint8_t dcf[2], bool allow_dcf); +void legic_xor_with_crc(uint8_t *data, uint16_t cardsize, uint8_t crc); +bool legic_clone_update_segment_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]); +bool legic_clone_update_kgh_crcs(uint8_t *data, size_t bytes_read, const uint8_t uid[4]); +int legic_write_bytes_to_tag(uint16_t offset, uint8_t iv, const uint8_t *data, size_t bytes_read, const char *verb); +int legic_write_dump_to_tag(uint8_t *dump, size_t bytes_read); #endif diff --git a/client/src/pm3line.c b/client/src/pm3line.c index 5270a5fbe..27f03d1a0 100644 --- a/client/src/pm3line.c +++ b/client/src/pm3line.c @@ -186,15 +186,22 @@ char *pm3line_read(const char *s) { return linenoise(s); #else printf("%s", s); - char *answer = NULL; - size_t anslen = 0; - int ret; - if ((ret = getline(&answer, &anslen, stdin)) < 0) { - // TODO this happens also when kbd_enter_pressed() is used, with a key pressed or not - printf("DEBUG: getline returned %i", ret); - free(answer); - answer = NULL; + char input[1024] = {0}; + if (fgets(input, sizeof(input), stdin) == NULL) { + return NULL; } + + size_t len = strlen(input); + while (len > 0 && (input[len - 1] == '\n' || input[len - 1] == '\r')) { + input[--len] = '\0'; + } + + char *answer = calloc(len + 1, sizeof(char)); + if (answer == NULL) { + return NULL; + } + + memcpy(answer, input, len); return answer; #endif } From b1bc5b11522895996b0d66912923d179141651d6 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 11:25:46 +0200 Subject: [PATCH 02/22] Added quick doco on how to ssh from ProxSpace --- .../Development/GitHub_ssh_from_ProxSpace.md | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 doc/md/Development/GitHub_ssh_from_ProxSpace.md diff --git a/doc/md/Development/GitHub_ssh_from_ProxSpace.md b/doc/md/Development/GitHub_ssh_from_ProxSpace.md new file mode 100644 index 000000000..875f64c59 --- /dev/null +++ b/doc/md/Development/GitHub_ssh_from_ProxSpace.md @@ -0,0 +1,113 @@ +# GitHub SSH from ProxSpace + +This is a quick guide to configuring Git and SSH authentication for GitHub from ProxSpace. + +## Configure Git + +Configure your Git email address and username: + +```bash +git config --global user.email "You@YourEmail.com" +git config --global user.name "YourUserName" +``` + +## Generate an SSH key + +Use `ssh-keygen` to generate an Ed25519 SSH key pair if you do not already have one: + +```bash +ssh-keygen -t ed25519 -C "You@YourEmail.com" +``` + +Accept the defaults: + +```text +Enter file in which to save the key (/pm3/.ssh/id_ed25519): +Enter passphrase (empty for no passphrase): +Enter same passphrase again: +``` + +This creates: + +```text +/pm3/.ssh/id_ed25519 # Private key +/pm3/.ssh/id_ed25519.pub # Public key +``` + +## Add the public key to GitHub + +Display the public key: + +```bash +cat /pm3/.ssh/id_ed25519.pub +``` + +Copy the complete output and add it to your GitHub account under: + +**Settings → SSH and GPG keys → New SSH key** + +Only the `.pub` file should be added to GitHub. Keep the private key private. + +## Test SSH authentication + +Test SSH authentication to GitHub using the specified private key, without attempting to open a shell session: + +```bash +ssh -i /pm3/.ssh/id_ed25519 -T git@github.com +``` + +A successful response looks like: + +```text +Hi YourUserName! You've successfully authenticated, but GitHub does not provide shell access. +``` + +## Check the Git remote + +Check that the repository remote is configured to use SSH rather than HTTPS: + +```bash +git remote -v +``` + +If it shows HTTPS: + +```text +origin https://github.com/YourUserName/proxmark3.git (fetch) +origin https://github.com/YourUserName/proxmark3.git (push) +``` + +Git will still try to authenticate over HTTPS and may prompt for a username/password. + +Change the remote to use SSH: + +```bash +git remote set-url origin git@github.com:YourUserName/proxmark3.git +``` + +Check it again: + +```bash +git remote -v +``` + +It should now show: + +```text +origin git@github.com:YourUserName/proxmark3.git (fetch) +origin git@github.com:YourUserName/proxmark3.git (push) +``` + +## Push + +Git should now use SSH authentication when pushing: + +```bash +git push origin +``` + +For example: + +```bash +git push origin feature/my_fab_feature +``` From e3ca960ae00d97e82605f72ef5a1de76c3329c42 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 11:32:36 +0200 Subject: [PATCH 03/22] Update wording --- client/experimental_lib/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index 764b25933..e49c52d4a 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -57,7 +57,7 @@ if (NOT SKIPPYTHON EQUAL 1) endif (NOT SKIPPYTHON EQUAL 1) if (MINGW) - # Prefer static archives for kiosk-style single-exe deployments. + # Prefer static archives for single-exe deployments. set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) set(ZLIB_USE_STATIC_LIBS ON) set(BZIP2_USE_STATIC_LIBS ON) From 2b463e4bf910d5d023ace3cc78a1fdff973d6a59 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 11:53:06 +0200 Subject: [PATCH 04/22] Remove suffix from repo name in build doco --- client/experimental_lib/KGH_TOOLS_BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/experimental_lib/KGH_TOOLS_BUILD.md b/client/experimental_lib/KGH_TOOLS_BUILD.md index bd969dc05..991665b3c 100644 --- a/client/experimental_lib/KGH_TOOLS_BUILD.md +++ b/client/experimental_lib/KGH_TOOLS_BUILD.md @@ -5,7 +5,7 @@ Do this in ProxSpace: ```bash -cd ~/proxmark3_rfrg/client/experimental_lib +cd ~/proxmark3/client/experimental_lib rm -rf build-lite cmake -G "MSYS Makefiles" -S . -B build-lite \ -DSKIPPYTHON=1 \ From 51752c3e1df8cf0b48a6acdffbe48cd3863435b8 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 12:22:30 +0200 Subject: [PATCH 05/22] Updated documentation to add usage, how to build in Linux as well as Windows (ProxSpace) --- client/experimental_lib/KGH_TOOLS.md | 74 ++++++++++++++++++++++ client/experimental_lib/KGH_TOOLS_BUILD.md | 30 --------- 2 files changed, 74 insertions(+), 30 deletions(-) create mode 100644 client/experimental_lib/KGH_TOOLS.md delete mode 100644 client/experimental_lib/KGH_TOOLS_BUILD.md diff --git a/client/experimental_lib/KGH_TOOLS.md b/client/experimental_lib/KGH_TOOLS.md new file mode 100644 index 000000000..26a7c93d4 --- /dev/null +++ b/client/experimental_lib/KGH_TOOLS.md @@ -0,0 +1,74 @@ +# kgh_tools + +## Running + +`kgh_tools` is a small CLI wrapper around the LEGIC migration helpers. + +Examples: + +```bash +./kgh_tools COM13 read_badge_number +./kgh_tools COM13 read_info +./kgh_tools COM13 write_card 600001 --stamp-file stamp.bin +``` + +Commands: + +- `read_badge_number` prints the badge number only. +- `read_info` prints one-line JSON. +- `write_card (--stamp-file | --stamp-hex <8hex>)` writes the card. + +Notes: + +- Windows ProxSpace examples use `COM13`. +- The stamp is 4 bytes and specific to your site. + It can be specified as a .bin (use .e.g hexedit to create it) + Or as a command-line option (less secure) as --stamp-hex (e.g.) 003EF417 + You can find the stamp on any card in use at your site by using read_info (see above) +- Linux examples usually use `/dev/ttyACM0` or similar. +- `--verbose` can be useful for `read_badge_number` and `write_card`, if they fail for mysterious reasons. + +## Building in ProxSpace (for Windows) + +Do this in ProxSpace: + +```bash +cd ~/proxmark3/client/experimental_lib +rm -rf build-lite +cmake -G "MSYS Makefiles" -S . -B build-lite \ + -DSKIPPYTHON=1 \ + -DSKIPREADLINE=1 \ + -DSKIPJANSSYSTEM=1 \ + -DSKIPWHEREAMISYSTEM=1 \ + -DSKIPBT=1 +cmake --build build-lite --target kgh_tools -j +objdump -p build-lite/kgh_tools.exe | grep -i "DLL Name" +``` + +## Building Linux + +```bash +cd client/experimental_lib +rm -rf build-linux +cmake -S . -B build-linux \ + -DSKIPPYTHON=1 \ + -DSKIPREADLINE=1 \ + -DSKIPJANSSYSTEM=1 \ + -DSKIPWHEREAMISYSTEM=1 \ + -DSKIPBT=1 +cmake --build build-linux --target kgh_tools -j +ldd build-linux/kgh_tools +``` + +## Static Link Notes + +- `kgh_tools` is linked against `pm3rrg_rdv4_static`. +- On MinGW, CMake adds `-static -static-libgcc` for the target. +- Linux builds are not the same as the ProxSpace single-EXE deployment. +- If CMakeCache paths change between ProxSpace and a native shell, delete the build dir and reconfigure. + +## Existing Helper Scripts + +- `01make_lib.sh` creates `build/`, runs `cmake ..`, then `make -j`. +- `01make_lib_continue.sh` reruns `make -j` in `build/`. +- `00make_swig.sh` regenerates the SWIG wrappers before building the library. diff --git a/client/experimental_lib/KGH_TOOLS_BUILD.md b/client/experimental_lib/KGH_TOOLS_BUILD.md deleted file mode 100644 index 991665b3c..000000000 --- a/client/experimental_lib/KGH_TOOLS_BUILD.md +++ /dev/null @@ -1,30 +0,0 @@ -# kgh_tools Build Notes - -## Configure And Build - -Do this in ProxSpace: - -```bash -cd ~/proxmark3/client/experimental_lib -rm -rf build-lite -cmake -G "MSYS Makefiles" -S . -B build-lite \ - -DSKIPPYTHON=1 \ - -DSKIPREADLINE=1 \ - -DSKIPJANSSYSTEM=1 \ - -DSKIPWHEREAMISYSTEM=1 \ - -DSKIPBT=1 -cmake --build build-lite --target kgh_tools -j -objdump -p build-lite/kgh_tools.exe | grep -i "DLL Name" -``` - -## Static Link Notes - -- `kgh_tools` is linked against `pm3rrg_rdv4_static`. -- On MinGW, CMake adds `-static -static-libgcc` for the target. -- If CMakeCache paths change between ProxSpace and a native shell, delete `build-lite` and reconfigure. - -## Existing Helper Scripts - -- `01make_lib.sh` creates `build/`, runs `cmake ..`, then `make -j`. -- `01make_lib_continue.sh` reruns `make -j` in `build/`. -- `00make_swig.sh` regenerates the SWIG wrappers before building the library. From 591551c2366d863e773ec240fdfbaa89aa510702 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Wed, 19 Aug 2026 22:50:41 +0200 Subject: [PATCH 06/22] Removed extra doc file not relevant to kgh tools pr --- .../Development/GitHub_ssh_from_ProxSpace.md | 113 ------------------ 1 file changed, 113 deletions(-) delete mode 100644 doc/md/Development/GitHub_ssh_from_ProxSpace.md diff --git a/doc/md/Development/GitHub_ssh_from_ProxSpace.md b/doc/md/Development/GitHub_ssh_from_ProxSpace.md deleted file mode 100644 index 875f64c59..000000000 --- a/doc/md/Development/GitHub_ssh_from_ProxSpace.md +++ /dev/null @@ -1,113 +0,0 @@ -# GitHub SSH from ProxSpace - -This is a quick guide to configuring Git and SSH authentication for GitHub from ProxSpace. - -## Configure Git - -Configure your Git email address and username: - -```bash -git config --global user.email "You@YourEmail.com" -git config --global user.name "YourUserName" -``` - -## Generate an SSH key - -Use `ssh-keygen` to generate an Ed25519 SSH key pair if you do not already have one: - -```bash -ssh-keygen -t ed25519 -C "You@YourEmail.com" -``` - -Accept the defaults: - -```text -Enter file in which to save the key (/pm3/.ssh/id_ed25519): -Enter passphrase (empty for no passphrase): -Enter same passphrase again: -``` - -This creates: - -```text -/pm3/.ssh/id_ed25519 # Private key -/pm3/.ssh/id_ed25519.pub # Public key -``` - -## Add the public key to GitHub - -Display the public key: - -```bash -cat /pm3/.ssh/id_ed25519.pub -``` - -Copy the complete output and add it to your GitHub account under: - -**Settings → SSH and GPG keys → New SSH key** - -Only the `.pub` file should be added to GitHub. Keep the private key private. - -## Test SSH authentication - -Test SSH authentication to GitHub using the specified private key, without attempting to open a shell session: - -```bash -ssh -i /pm3/.ssh/id_ed25519 -T git@github.com -``` - -A successful response looks like: - -```text -Hi YourUserName! You've successfully authenticated, but GitHub does not provide shell access. -``` - -## Check the Git remote - -Check that the repository remote is configured to use SSH rather than HTTPS: - -```bash -git remote -v -``` - -If it shows HTTPS: - -```text -origin https://github.com/YourUserName/proxmark3.git (fetch) -origin https://github.com/YourUserName/proxmark3.git (push) -``` - -Git will still try to authenticate over HTTPS and may prompt for a username/password. - -Change the remote to use SSH: - -```bash -git remote set-url origin git@github.com:YourUserName/proxmark3.git -``` - -Check it again: - -```bash -git remote -v -``` - -It should now show: - -```text -origin git@github.com:YourUserName/proxmark3.git (fetch) -origin git@github.com:YourUserName/proxmark3.git (push) -``` - -## Push - -Git should now use SSH authentication when pushing: - -```bash -git push origin -``` - -For example: - -```bash -git push origin feature/my_fab_feature -``` From 3632166bb4be65c8ee289a6aa7464aef0b3b82a8 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Tue, 25 Aug 2026 17:20:12 +0200 Subject: [PATCH 07/22] Revert pm3line fallback change --- client/src/pm3line.c | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/client/src/pm3line.c b/client/src/pm3line.c index 27f03d1a0..5270a5fbe 100644 --- a/client/src/pm3line.c +++ b/client/src/pm3line.c @@ -186,22 +186,15 @@ char *pm3line_read(const char *s) { return linenoise(s); #else printf("%s", s); - char input[1024] = {0}; - if (fgets(input, sizeof(input), stdin) == NULL) { - return NULL; + char *answer = NULL; + size_t anslen = 0; + int ret; + if ((ret = getline(&answer, &anslen, stdin)) < 0) { + // TODO this happens also when kbd_enter_pressed() is used, with a key pressed or not + printf("DEBUG: getline returned %i", ret); + free(answer); + answer = NULL; } - - size_t len = strlen(input); - while (len > 0 && (input[len - 1] == '\n' || input[len - 1] == '\r')) { - input[--len] = '\0'; - } - - char *answer = calloc(len + 1, sizeof(char)); - if (answer == NULL) { - return NULL; - } - - memcpy(answer, input, len); return answer; #endif } From 9def79f8be8492c9ceaf95b3776c44dbf2442e5b Mon Sep 17 00:00:00 2001 From: YoungJules Date: Tue, 25 Aug 2026 17:24:09 +0200 Subject: [PATCH 08/22] Fix extra segments identification if first segment also the last --- client/experimental_lib/example_c/legic_migrate_tool.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/experimental_lib/example_c/legic_migrate_tool.c b/client/experimental_lib/example_c/legic_migrate_tool.c index bb6e87eb1..1f4d298a6 100644 --- a/client/experimental_lib/example_c/legic_migrate_tool.c +++ b/client/experimental_lib/example_c/legic_migrate_tool.c @@ -302,6 +302,7 @@ static bool has_extra_segments(const uint8_t *dump, uint16_t len) { while (start + 5 <= len) { uint16_t seg_len = (((uint16_t)dump[start + 1] & 0x0F) << 8) | dump[start]; + bool is_last = ((dump[start + 1] & 0x08) != 0); if (seg_len < 5 || start + seg_len > len) { break; } @@ -311,7 +312,7 @@ static bool has_extra_segments(const uint8_t *dump, uint16_t len) { } saw_first = true; - if (start + seg_len >= len) { + if (is_last) { break; } From 6235eadf21c214706a711885c0281ca712e07997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sat, 29 Aug 2026 23:42:28 +0800 Subject: [PATCH 09/22] feat: hf mfu format command --- CHANGELOG.md | 1 + client/src/cmdhfmfu.c | 556 +++++++++++++++++++++++++++++++++++++++++- client/src/cmdhfmfu.h | 1 + client/src/cmdnfc.c | 6 +- 4 files changed, 561 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d5ac5633..5cc000b85 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 mfu format` - NDEF format Ultralight/NTAG tags, restores the NXP factory Capability Container for the detected type (@0x6r1an0y) - Added tools script `external_sam_read.py` enabling PM3 3 Easy and Proxmark 5 to use an external SIM/SAM reader for `hf iclass sam` and `hf seos sam` commands (@antiklesys) - Added `nfc encode` and `hf mfu ndefwrite` - build NDEF URI/Text/AAR records and write them to Ultralight tags (@0x6r1an0y) - Fixed `hf emrtd info` - the picture viewer now scales images to the window instead of pinning them at native size (@iceman1001) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 1b307e2bd..37a273d6a 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -68,8 +68,9 @@ #define MIFAREU3P_KEY_SIZE 16 #define MIFAREULC_KEY_INDEX 3 -// NDEF data area starts at block 4 and READ takes a one byte block number, -// so block 255 is the last one reachable. +// The Capability Container sits in block 3, the NDEF data area starts at block 4 +// and READ takes a one byte block number, so block 255 is the last one reachable. +#define MFU_NDEF_CC_BLOCK 3 #define MFU_NDEF_FIRST_BLOCK 4 #define MFU_NDEF_MAX_BYTES ((0xFF - MFU_NDEF_FIRST_BLOCK + 1) * MFU_BLOCK_SIZE) @@ -7827,6 +7828,556 @@ int CmdHF14MfuNDEFWrite(const char *Cmd) { PrintAndLogEx(NORMAL, ""); return PM3_SUCCESS; } + +// --------------------------------------------------------------------------- +// NDEF formatting +// +// Page 03h is the Capability Container. On every MIFARE Ultralight / NTAG type +// it is a One Time Programmable page: a WRITE is bit-wise OR'ed with the current +// content and a bit set to 1 can never be cleared again. Getting the value wrong +// is therefore permanent, which is why an unknown tag type is refused rather than +// guessed at, and why the requested value is checked for reachability first. +// +// The table below restores the NXP "memory content at delivery" for pages 03h, +// 04h and 05h. Note that NTAG212/213/213F ship with a Lock Control TLV in front +// of the NDEF TLV while the other types do not, so the delivery content is copied +// per type instead of being assembled here. +// +// Only the NTAG21x family is delivered with a Capability Container at all. The +// MF0ICU1 / MF0ICU2 / MF0ULx1 parts leave page 03h at 00 00 00 00, so their CC is +// derived from the user memory page range given in the datasheet and they use the +// plain "empty NDEF message" layout of NTAG210/215/216. +typedef struct { + uint64_t tagtype; + const char *name; + uint8_t page[3][MFU_BLOCK_SIZE]; // pages 03h, 04h, 05h +} mfu_ndef_format_t; + +static const mfu_ndef_format_t mfu_ndef_format_table[] = { + // https://www.nxp.com/docs/en/data-sheet/MF0ICU1.pdf + // MIFARE Ultralight MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // NXP MF0ICU1, doc 028639, rev 3.9 - 23 July 2014 + // memory organization ........ section 7.5, Table 5, page 10 of 31 + // page 03h is OTP, no CC at delivery ..... section 7.5, page 10 of 31 + // CC derived from the user memory page range, not an NXP delivery value. + + { + MFU_TT_UL, "MIFARE Ultralight", + {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf + // MIFARE Ultralight C MLEN 12h = 144 bytes, user memory pages 04h-27h + // NXP MF0ICU2, rev 3.5 - 30 January 2026 + // memory organization ........ section 7.5, Table 5, page 8 of 35 + // OTP bytes preset to all 0 .. section 7.5.4, page 11 of 35 + // CC derived from the user memory page range, not an NXP delivery value. + // The data area ends at page 27h, right before the lock bytes at page 28h, + // so no Lock Control TLV is required. + { + MFU_TT_UL_C, "MIFARE Ultralight C", + {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf + // MIFARE Ultralight EV1 48 (MF0UL11) MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // NXP MF0ULX1, doc 234533, rev 3.3 - 9 April 2019 + // memory organization MF0UL11 ... section 8.5, Fig 5, page 10 of 45 + // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + // data pages .................... section 8.5.5, page 14 of 45 + // CC derived from the user memory page range, not an NXP delivery value. + { + MFU_TT_UL_EV1_48, "MIFARE Ultralight EV1 48", + {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf + // MIFARE Ultralight EV1 128 (MF0UL21) MLEN 10h = 128 bytes, user memory pages 04h-23h + // NXP MF0ULX1, doc 234533, rev 3.3 - 9 April 2019 + // memory organization MF0UL21 ... section 8.5, Fig 6, page 11 of 45 + // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + // data pages .................... section 8.5.5, page 14 of 45 + // CC derived from the user memory page range, not an NXP delivery value. + { + MFU_TT_UL_EV1_128, "MIFARE Ultralight EV1 128", + {{0xE1, 0x10, 0x10, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf + // NTAG210 MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // NXP NTAG210/212, doc 242330, rev 3.0 - 14 March 2013 + // data pages ................. section 8.5.5, page 13 of 46 + // memory content at delivery . section 8.5.6, Table 4, page 14 of 46 + { + MFU_TT_NTAG_210, "NTAG210", + {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NT2L1001_NT2H1001.pdf + // NTAG210u same geometry as NTAG210 + // No dedicated datasheet was consulted. getTagType assigns this its own type + // bit (an exclusive GET_VERSION match), but UL_MEMORY_ARRAY gives it + // MAX_NTAG_210 and ul_print_type reports 48 bytes, so the user memory range - + // and therefore the CC - is the same as NTAG210. + { + MFU_TT_NTAG_210u, "NTAG210u", + {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf + // NTAG212 MLEN 10h = 128 bytes, user memory pages 04h-23h + // NXP NTAG210/212, doc 242330, rev 3.0 - 14 March 2013 + // data pages ................. section 8.5.5, page 13 of 46 + // memory content at delivery . section 8.5.6, Table 5, page 14 of 46 + // Ships with a Lock Control TLV (01 03 90 0A 34) ahead of the NDEF TLV. + { + MFU_TT_NTAG_212, "NTAG212", + {{0xE1, 0x10, 0x10, 0x00}, {0x01, 0x03, 0x90, 0x0A}, {0x34, 0x03, 0x00, 0xFE}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf + // NTAG213 MLEN 12h = 144 bytes, user memory pages 04h-27h + // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 + // memory organization ........ section 8.5, Fig 5, page 11 of 60 + // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 + // data pages ................. section 8.5.5, page 16 of 60 + // memory content at delivery . section 8.5.6, Table 5, page 17 of 60 + // Ships with a Lock Control TLV (01 03 A0 0C 34) ahead of the NDEF TLV. + { + MFU_TT_NTAG_213, "NTAG213", + {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf + // NTAG213F identical delivery content to NTAG213 + // NXP NTAG213F/216F, doc 262236, rev 3.6 - 28 September 2015 + // memory content at delivery . section 8.5.6, Table 5, page 17 of 55 + { + MFU_TT_NTAG_213_F, "NTAG213F", + {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NT2H1311TT.pdf + // NTAG213TT and NTAG213C same geometry as NTAG213 + // No dedicated datasheet was consulted for either. getTagType assigns each its + // own type bit (exclusive GET_VERSION matches differing only in the product + // version bytes, storage size stays 0Fh), but UL_MEMORY_ARRAY gives both + // MAX_NTAG_213 and ul_print_type reports 144 bytes, so the user memory range - + // and therefore the CC - is the same as NTAG213. Note only page 03h is + // irreversible; pages 04h/05h are ordinary user memory and can be rewritten if + // a variant turns out to ship a different Lock Control TLV. + { + MFU_TT_NTAG_213_TT, "NTAG213TT", + {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} + }, + { + MFU_TT_NTAG_213_C, "NTAG213C", + {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf + // NTAG215 MLEN 3Eh = 496 bytes, user memory pages 04h-81h + // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 + // memory organization ........ section 8.5, Fig 6, page 11 of 60 + // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 + // memory content at delivery . section 8.5.6, Table 6, page 17 of 60 + // The factory MLEN announces 496 bytes while the user memory holds 504. + // The datasheet gives no reason for the 8 byte difference; the NXP value is + // kept on purpose since under reporting can never push a write past the + // user memory, while a larger value could. + { + MFU_TT_NTAG_215, "NTAG215", + {{0xE1, 0x10, 0x3E, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf + // NTAG216 MLEN 6Dh = 872 bytes, user memory pages 04h-E1h + // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 + // memory organization ........ section 8.5, Fig 7, page 12 of 60 + // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 + // memory content at delivery . section 8.5.6, Table 7, page 17 of 60 + // Same 16 byte under reporting as NTAG215, kept for the same reason. + { + MFU_TT_NTAG_216, "NTAG216", + {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf + // NTAG216F identical delivery content to NTAG216 + // NXP NTAG213F/216F, doc 262236, rev 3.6 - 28 September 2015 + // memory content at delivery . section 8.5.6, Table 6, page 17 of 55 + { + MFU_TT_NTAG_216_F, "NTAG216F", + {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + // https://www.orangetags.com/wp-content/downloads/datasheet/NXP/NTAG203.pdf + // NTAG203 no datasheet of its own was consulted, but NTAG213/215/216 + // (doc 265332, rev 3.2, section 8.5, page 11 of 60) states that the + // manufacturing data, lock bytes, capability container and user memory + // pages of NTAG213 are compatible to NTAG203. + { + MFU_TT_NTAG_203, "NTAG203", + {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} + }, +}; + +static const mfu_ndef_format_t *mfu_get_ndef_format(uint64_t tagtype) { + for (size_t i = 0; i < ARRAYLEN(mfu_ndef_format_table); i++) { + uint64_t tt = mfu_ndef_format_table[i].tagtype; + if ((tagtype & tt) == tt) { + return &mfu_ndef_format_table[i]; + } + } + return NULL; +} + +int CmdHF14AMfUFormat(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfu format", + "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability\n" + "Container to block 3, followed by an empty NDEF message. This is what a tag\n" + "needs before `hf mfu ndefwrite` will touch it.\n" + "\n" + "The values written are the NXP factory delivery content for the detected tag\n" + "type. Block 3 is One Time Programmable on every supported type: a write is\n" + "OR'ed with the current content and a bit set to 1 can never be cleared. An\n" + "unknown tag type is therefore refused rather than guessed at, and a Capability\n" + "Container that cannot be reached from the current content is refused as well.\n" + "\n" + "Note: the tag is re-selected and re-authenticated for every block written.", + "hf mfu format\n" + "hf mfu format -v\n" + "hf mfu format --erase\n" + "hf mfu format -k FFFFFFFF\n" + "hf mfu format -k 49454D4B41455242214E4143554F5946\n" + "hf mfu format -d E1101200 --force" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("k", "key", "", "Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)"), + arg_lit0("l", NULL, "Swap entered key endianness"), + arg_str0("d", "data", "", "Capability Container to write, 4 bytes. Overrides the detected type"), + arg_lit0(NULL, "erase", "Also zero the rest of the NDEF data area"), + arg_lit0(NULL, "force", "Continue on an unknown tag type, or with an oversized -d value"), + arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "schann", "use secure channel. Must have key"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + int ak_len = 0; + uint8_t authenticationkey[16] = {0x00}; + CLIGetHexWithReturn(ctx, 1, authenticationkey, &ak_len); + bool swap_endian = arg_get_lit(ctx, 2); + + int cc_len = 0; + uint8_t cc_override[MFU_BLOCK_SIZE] = {0x00}; + CLIGetHexWithReturn(ctx, 3, cc_override, &cc_len); + + bool erase = arg_get_lit(ctx, 4); + bool force = arg_get_lit(ctx, 5); + bool verbose = arg_get_lit(ctx, 6); + bool use_schann = arg_get_lit(ctx, 7); + CLIParserFree(ctx); + + if ((cc_len != 0) && (cc_len != MFU_BLOCK_SIZE)) { + PrintAndLogEx(WARNING, "Capability Container must be %d bytes, got %d", MFU_BLOCK_SIZE, cc_len); + return PM3_EINVARG; + } + + bool has_auth_key = false; + bool has_pwd = false; + switch (ak_len) { + case 0: + break; + case 4: + has_pwd = true; + break; + case 16: + has_auth_key = true; + break; + default: + PrintAndLogEx(WARNING, "ERROR: Key is incorrect length\n"); + return PM3_EINVARG; + } + + if (use_schann && (has_auth_key == false)) { + PrintAndLogEx(WARNING, "Secure channel must be called with key"); + return PM3_EINVARG; + } + + uint64_t tagtype = GetHF14AMfU_Type(); + if (tagtype == MFU_TT_UL_ERROR) { + PrintAndLogEx(WARNING, "No Ultralight / NTAG based tag found"); + return PM3_ESOFT; + } + + ul_print_type(tagtype, 0); + + const mfu_ndef_format_t *fmt = mfu_get_ndef_format(tagtype); + if (fmt == NULL) { + if (cc_len == 0) { + PrintAndLogEx(FAILED, "Don't know the Capability Container for this tag type"); + PrintAndLogEx(INFO, "Block 3 is One Time Programmable, a wrong value can not be undone,"); + PrintAndLogEx(INFO, "so this command will not guess one."); + PrintAndLogEx(HINT, "Hint: supply it yourself with `" _YELLOW_("hf mfu format -d --force") "`"); + return PM3_ENOTIMPL; + } + if (force == false) { + PrintAndLogEx(FAILED, "Unknown tag type, add `" _YELLOW_("--force") "` to write anyway"); + return PM3_EINVARG; + } + if (erase) { + PrintAndLogEx(FAILED, "Refusing to erase on an unknown tag type"); + PrintAndLogEx(INFO, "The end of the data area can not be established, so the erase"); + PrintAndLogEx(INFO, "could run into the lock bytes, configuration or key pages."); + return PM3_EINVARG; + } + } + + // pages 03h, 04h and 05h as they will be written + uint8_t pages[3][MFU_BLOCK_SIZE] = {{0}}; + if (fmt != NULL) { + memcpy(pages, fmt->page, sizeof(pages)); + } else { + // unknown type, -d plus --force: user supplied CC and an empty NDEF message + const uint8_t empty[2][MFU_BLOCK_SIZE] = {{0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}}; + memcpy(pages[1], empty[0], MFU_BLOCK_SIZE); + memcpy(pages[2], empty[1], MFU_BLOCK_SIZE); + } + + if (cc_len == MFU_BLOCK_SIZE) { + + // A hand written Capability Container still must not announce more NDEF + // area than the tag physically holds. Block 3 is OTP, so an over reporting + // MLEN can never be taken back, and ndefwrite would then clamp against the + // whole chip - lock bytes, configuration and key pages included. + if ((fmt != NULL) && (cc_override[2] > fmt->page[0][2]) && (force == false)) { + PrintAndLogEx(FAILED, "Capability Container announces more memory than this tag has"); + PrintAndLogEx(INFO, " requested... %d bytes ( MLEN %02X )", cc_override[2] * 8, cc_override[2]); + PrintAndLogEx(INFO, " tag holds... %d bytes ( MLEN %02X )", fmt->page[0][2] * 8, fmt->page[0][2]); + PrintAndLogEx(INFO, "Block 3 is One Time Programmable, this can not be undone."); + PrintAndLogEx(HINT, "Hint: add `" _YELLOW_("--force") "` if you really mean it"); + return PM3_EINVARG; + } + + memcpy(pages[0], cc_override, MFU_BLOCK_SIZE); + } + + if (verbose) { + PrintAndLogEx(INFO, "Tag type... " _YELLOW_("%s"), (fmt != NULL) ? fmt->name : "unknown"); + for (uint8_t i = 0; i < 3; i++) { + PrintAndLogEx(INFO, "Block %2u... %s" + , MFU_NDEF_CC_BLOCK + i + , sprint_hex_inrow(pages[i], MFU_BLOCK_SIZE) + ); + } + } + + uint8_t *auth_key_ptr = authenticationkey; + if (swap_endian) { + if (ak_len == 16) { + if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 8); + } else if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 16); + } + } else if (ak_len == 4) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 4); + } + } + + iso14a_card_select_t card; + uint8_t pack[4] = {0, 0, 0, 0}; + if (ul_auth_select(&card, tagtype, (has_auth_key || has_pwd), auth_key_ptr, pack, sizeof(pack), use_schann) == PM3_ESOFT) { + return PM3_ESOFT; + } + + // read blocks 0..3 so the current Capability Container can be inspected + uint8_t data[16] = {0x00}; + int status = ul_read(0, data, sizeof(data), use_schann); + DropField(); + + if (status <= 0) { + PrintAndLogEx(ERR, "Error: tag didnt answer to READ"); + return PM3_ESOFT; + } + + if (status != 16) { + PrintAndLogEx(ERR, "Error: tag returned %d bytes, need 16 to read the NDEF Container", status); + return PM3_ESOFT; + } + + // Block 3 is OTP: a WRITE is OR'ed with what is already there and a bit that + // is set can never be cleared. Anything the OR can not produce is refused + // before a single byte goes to the tag. + uint8_t *cur = data + (MFU_NDEF_CC_BLOCK * MFU_BLOCK_SIZE); + bool blank = true; + bool reachable = true; + for (uint8_t i = 0; i < MFU_BLOCK_SIZE; i++) { + if (cur[i] != 0x00) { + blank = false; + } + if ((cur[i] | pages[0][i]) != pages[0][i]) { + reachable = false; + } + } + + if (reachable == false) { + PrintAndLogEx(FAILED, "Capability Container can not be written on this tag"); + PrintAndLogEx(INFO, " on tag now... " _RED_("%s"), sprint_hex_inrow(cur, MFU_BLOCK_SIZE)); + PrintAndLogEx(INFO, " wanted....... " _GREEN_("%s"), sprint_hex_inrow(pages[0], MFU_BLOCK_SIZE)); + PrintAndLogEx(INFO, "Block 3 is One Time Programmable. A write is OR'ed with the current"); + PrintAndLogEx(INFO, "content, so a bit that is already 1 can not be cleared again."); + ndef_print_CC(cur); + return PM3_EINVARG; + } + + if (blank == false) { + PrintAndLogEx(WARNING, "Tag already carries a Capability Container ( " _YELLOW_("%s") " )" + , sprint_hex_inrow(cur, MFU_BLOCK_SIZE) + ); + if (verbose) { + ndef_print_CC(cur); + } + } + + uint8_t keytype = 0; + if (has_auth_key || has_pwd) { + if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { + keytype = 1; // UL_C auth + } else if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { + keytype = 3; // UL_AES auth + } else { + keytype = 2; // UL_EV1/NTAG auth + } + } + + // The erase range is derived from the MLEN in the table, never from -d, so a + // hand written Capability Container can not push it past the user memory. + // Every table entry announces at most the user memory of that type, which + // keeps the last block below the lock bytes and configuration pages. + uint16_t last_block = MFU_NDEF_CC_BLOCK + 2; + if (erase && (fmt != NULL)) { + last_block = (uint16_t)(MFU_NDEF_CC_BLOCK + (fmt->page[0][2] * 2)); + } + + // WRITE addresses blocks with a single byte, so block 255 is the last one + // reachable - the same limit MFU_NDEF_MAX_BYTES encodes for ndefread/ndefwrite. + // No current table entry comes close, but mfu_write_block takes a uint8_t and + // the cast below would silently wrap a larger block number back onto the UID + // and lock pages, so clamp here rather than rely on the table staying small. + if (last_block > 0xFF) { + PrintAndLogEx(INFO, "Data area runs past block 255, stopping at the last addressable block"); + last_block = 0xFF; + } + + uint16_t total = (uint16_t)(last_block - MFU_NDEF_CC_BLOCK + 1); + + PrintAndLogEx(INFO, "Writing " _YELLOW_("%u") " blocks from block " _YELLOW_("%d"), total, MFU_NDEF_CC_BLOCK); + PrintAndLogEx(INFO, "Press " _GREEN_("") " to abort"); + + uint16_t done = 0; + const uint8_t zeros[MFU_BLOCK_SIZE] = {0x00, 0x00, 0x00, 0x00}; + + for (uint16_t blockno = MFU_NDEF_CC_BLOCK; blockno <= last_block; blockno++) { + + if (kbd_enter_pressed()) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(WARNING, "aborted via keyboard!"); + if (done > 0) { + PrintAndLogEx(WARNING, "tag holds a partially written NDEF data area, blocks %d..%u" + , MFU_NDEF_CC_BLOCK + , blockno - 1 + ); + } + return PM3_EOPABORTED; + } + + const uint8_t *src = zeros; + if (blockno < MFU_NDEF_CC_BLOCK + 3) { + src = pages[blockno - MFU_NDEF_CC_BLOCK]; + } + + int res = mfu_write_block(src, MFU_BLOCK_SIZE, keytype, auth_key_ptr, (uint8_t)blockno, use_schann); + if (res != PM3_SUCCESS) { + PrintAndLogEx(NORMAL, ""); + + // a protected tag simply stops answering, so the write times out + // rather than coming back with an explicit error + if (res == PM3_ETIMEOUT) { + PrintAndLogEx(FAILED, "Write block %u ( " _RED_("timeout") " )", blockno); + } else { + PrintAndLogEx(FAILED, "Write block %u ( " _RED_("fail") " )", blockno); + } + PrintAndLogEx(HINT, "Hint: Check password / key!"); + + if (done > 0) { + PrintAndLogEx(WARNING, "tag holds a partially written NDEF data area, blocks %d..%u" + , MFU_NDEF_CC_BLOCK + , blockno - 1 + ); + } + return PM3_ESOFT; + } + + done++; + PrintAndLogEx(INPLACE, "Block %u / %u", done, total); + } + + DropField(); + PrintAndLogEx(NORMAL, ""); + + // Block 3 is one time programmable, so there is exactly one chance to get it + // right. A tag can ACK a WRITE and still not commit the page - a weak field, a + // tear, or a block locking bit that was already set - and the write status + // alone would not show it. Read the formatted blocks back rather than trust it. + if (ul_auth_select(&card, tagtype, (has_auth_key || has_pwd), auth_key_ptr, pack, sizeof(pack), use_schann) == PM3_ESOFT) { + PrintAndLogEx(WARNING, "Wrote the tag but could not re-select it to verify"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread") "` to check it yourself"); + return PM3_ESOFT; + } + + uint8_t verify[16] = {0x00}; + status = ul_read(MFU_NDEF_CC_BLOCK, verify, sizeof(verify), use_schann); + DropField(); + + if (status != 16) { + PrintAndLogEx(WARNING, "Wrote the tag but could not read it back to verify"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread") "` to check it yourself"); + return PM3_ESOFT; + } + + // the read started at block 3, so the three formatted blocks are at offset 0 + if (memcmp(verify, pages[0], MFU_BLOCK_SIZE) != 0) { + PrintAndLogEx(FAILED, "Capability Container did not take"); + PrintAndLogEx(INFO, " wanted...... " _GREEN_("%s"), sprint_hex_inrow(pages[0], MFU_BLOCK_SIZE)); + PrintAndLogEx(INFO, " on tag now.. " _RED_("%s"), sprint_hex_inrow(verify, MFU_BLOCK_SIZE)); + PrintAndLogEx(HINT, "Hint: block 3 is OTP, check whether its block locking bit is set"); + return PM3_ESOFT; + } + + if (memcmp(verify + MFU_BLOCK_SIZE, pages[1], 2 * MFU_BLOCK_SIZE) != 0) { + PrintAndLogEx(FAILED, "Capability Container is correct but the empty NDEF message is not"); + // pages[1] and pages[2] are contiguous, and so are the two blocks in + // verify, so each side prints in a single call - sprint_hex_inrow hands + // back one shared static buffer, so two calls per line would alias. + PrintAndLogEx(INFO, " wanted...... " _GREEN_("%s"), sprint_hex_inrow(pages[1], 2 * MFU_BLOCK_SIZE)); + PrintAndLogEx(INFO, " on tag now.. " _RED_("%s"), sprint_hex_inrow(verify + MFU_BLOCK_SIZE, 2 * MFU_BLOCK_SIZE)); + PrintAndLogEx(HINT, "Hint: these blocks are ordinary user memory, check the lock bytes"); + return PM3_ESOFT; + } + + if (verbose) { + PrintAndLogEx(INFO, "Verified blocks %d..%d against the tag", MFU_NDEF_CC_BLOCK, MFU_NDEF_CC_BLOCK + 2); + } + + PrintAndLogEx(SUCCESS, "Format ( " _GREEN_("ok") " )"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefwrite") "` to write a NDEF message"); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; +} // utility function. Retrieves emulator memory static int GetMfuDumpFromEMul(mfu_dump_t **buf) { @@ -8696,6 +9247,7 @@ static command_t CommandTable[] = { {"aesgetuid", CmdHF14AMfUAESGetUID, IfPm3Iso14443a, "Ultralight-AES - Get UID when RID in use"}, {"setkey", CmdHF14AMfUSetKey, IfPm3Iso14443a, "Ultralight C/AES - Set 3DES/AES keys"}, {"dump", CmdHF14AMfUDump, IfPm3Iso14443a, "Dump MIFARE Ultralight family tag to binary file"}, + {"format", CmdHF14AMfUFormat, IfPm3Iso14443a, "Format tag as NDEF, writes the Capability Container"}, {"incr", CmdHF14AMfUIncr, IfPm3Iso14443a, "Increments Ev1/NTAG counter"}, {"info", CmdHF14AMfUInfo, IfPm3Iso14443a, "Tag information"}, {"ndefread", CmdHF14MfuNDEFRead, IfPm3Iso14443a, "Prints NDEF records from card"}, diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h index 1eb49488b..73b92962d 100644 --- a/client/src/cmdhfmfu.h +++ b/client/src/cmdhfmfu.h @@ -59,6 +59,7 @@ int mfuc_test_authentication_support(void); int CmdHFMFUltra(const char *Cmd); int CmdHF14MfuNDEFRead(const char *Cmd); // used by cmdnfc.c int CmdHF14MfuNDEFWrite(const char *Cmd); // used by cmdnfc.c +int CmdHF14AMfUFormat(const char *Cmd); // used by cmdnfc.c int CmdHF14MfUTamper(const char *Cmd); #define MFU_TT_UNKNOWN 0x0ULL diff --git a/client/src/cmdnfc.c b/client/src/cmdnfc.c index 67dfa2720..7b88126af 100644 --- a/client/src/cmdnfc.c +++ b/client/src/cmdnfc.c @@ -391,12 +391,16 @@ static int CmdNFCType2Write(const char *Cmd) { return CmdHF14MfuNDEFWrite(Cmd); } +static int CmdNFCType2Format(const char *Cmd) { + return CmdHF14AMfUFormat(Cmd); +} + static int CmdNFCType2Help(const char *Cmd); static command_t CommandNFCType2Table[] = { {"--------", CmdNFCType2Help, AlwaysAvailable, "-------------- " _CYAN_("NFC Forum Tag Type 2") " ---------------"}, -// {"format", CmdNFCType2Format, IfPm3Iso14443a, "format ISO-14443-a tag as NFC Tag"}, + {"format", CmdNFCType2Format, IfPm3Iso14443a, "format MIFARE Ultralight / NTAG as NFC Forum Tag Type 2"}, {"read", CmdNFCType2Read, IfPm3Iso14443a, "read NFC Forum Tag Type 2"}, {"write", CmdNFCType2Write, IfPm3Iso14443a, "write NFC Forum Tag Type 2"}, {"--------", CmdNFCType2Help, AlwaysAvailable, "--------------------- " _CYAN_("General") " ---------------------"}, From ded9ac868b200aa5735ccfdb07fd56725ffc50b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sun, 30 Aug 2026 02:46:16 +0800 Subject: [PATCH 10/22] style: datasheet url --- client/src/cmdhfmfu.c | 207 +++++++++++++++++++++--------------------- 1 file changed, 101 insertions(+), 106 deletions(-) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 37a273d6a..5500f0c04 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -7832,21 +7832,19 @@ int CmdHF14MfuNDEFWrite(const char *Cmd) { // --------------------------------------------------------------------------- // NDEF formatting // -// Page 03h is the Capability Container. On every MIFARE Ultralight / NTAG type -// it is a One Time Programmable page: a WRITE is bit-wise OR'ed with the current -// content and a bit set to 1 can never be cleared again. Getting the value wrong -// is therefore permanent, which is why an unknown tag type is refused rather than -// guessed at, and why the requested value is checked for reachability first. +// Page 03h is the Capability Container and is One Time Programmable on every type +// below: a WRITE is bit-wise OR'ed with the current content and a bit set to 1 can +// never be cleared again. A wrong value is permanent, hence an unknown tag type is +// refused rather than guessed at. // -// The table below restores the NXP "memory content at delivery" for pages 03h, -// 04h and 05h. Note that NTAG212/213/213F ship with a Lock Control TLV in front -// of the NDEF TLV while the other types do not, so the delivery content is copied -// per type instead of being assembled here. +// Each entry restores the NXP "memory content at delivery" for pages 03h, 04h and +// 05h. NTAG212/213/213F/213TT ship a Lock Control TLV in front of the NDEF TLV and +// the others do not, so the content is copied per type rather than assembled here. // // Only the NTAG21x family is delivered with a Capability Container at all. The -// MF0ICU1 / MF0ICU2 / MF0ULx1 parts leave page 03h at 00 00 00 00, so their CC is -// derived from the user memory page range given in the datasheet and they use the -// plain "empty NDEF message" layout of NTAG210/215/216. +// MF0ICU1 / MF0ICU2 / MF0ULx1 parts and NTAG203 leave page 03h as a blank OTP +// page, so their CC is derived from the user memory page range and they get the +// plain empty NDEF message. typedef struct { uint64_t tagtype; const char *name; @@ -7854,170 +7852,167 @@ typedef struct { } mfu_ndef_format_t; static const mfu_ndef_format_t mfu_ndef_format_table[] = { - // https://www.nxp.com/docs/en/data-sheet/MF0ICU1.pdf - // MIFARE Ultralight MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // NXP MF0ICU1, doc 028639, rev 3.9 - 23 July 2014 - // memory organization ........ section 7.5, Table 5, page 10 of 31 - // page 03h is OTP, no CC at delivery ..... section 7.5, page 10 of 31 - // CC derived from the user memory page range, not an NXP delivery value. + // MIFARE Ultralight MF0ICU1 MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // https://www.nxp.com/docs/en/data-sheet/MF0ICU1.pdf rev 3.9 - 23 July 2014 + // memory organization ........... section 7.5, Table 5, page 10 of 31 + // data pages .................... section 7.5, Table 5, page 10 of 31 + // page 03h is OTP, no CC at delivery - CC derived from the page range { MFU_TT_UL, "MIFARE Ultralight", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf - // MIFARE Ultralight C MLEN 12h = 144 bytes, user memory pages 04h-27h - // NXP MF0ICU2, rev 3.5 - 30 January 2026 - // memory organization ........ section 7.5, Table 5, page 8 of 35 - // OTP bytes preset to all 0 .. section 7.5.4, page 11 of 35 - // CC derived from the user memory page range, not an NXP delivery value. - // The data area ends at page 27h, right before the lock bytes at page 28h, - // so no Lock Control TLV is required. + // MIFARE Ultralight C MF0ICU2 MLEN 12h = 144 bytes, user memory pages 04h-27h + // https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf rev 3.5 - 30 January 2026 + // memory organization ........... section 7.5, Table 5, page 8 of 35 + // data pages .................... section 7.5, Table 5, page 8 of 35 + // OTP preset to all 0 ........... section 7.5.4, page 11 of 35 + // CC derived from the page range. The data area ends at page 27h, right before + // the lock bytes at page 28h, so no Lock Control TLV is needed. { MFU_TT_UL_C, "MIFARE Ultralight C", {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf - // MIFARE Ultralight EV1 48 (MF0UL11) MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // NXP MF0ULX1, doc 234533, rev 3.3 - 9 April 2019 - // memory organization MF0UL11 ... section 8.5, Fig 5, page 10 of 45 - // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + // MIFARE Ultralight EV1 48 MF0UL11 MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf rev 3.3 - 9 April 2019 + // memory organization ........... section 8.5, Fig 5, page 10 of 45 // data pages .................... section 8.5.5, page 14 of 45 - // CC derived from the user memory page range, not an NXP delivery value. + // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + // CC derived from the page range. { MFU_TT_UL_EV1_48, "MIFARE Ultralight EV1 48", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf - // MIFARE Ultralight EV1 128 (MF0UL21) MLEN 10h = 128 bytes, user memory pages 04h-23h - // NXP MF0ULX1, doc 234533, rev 3.3 - 9 April 2019 - // memory organization MF0UL21 ... section 8.5, Fig 6, page 11 of 45 - // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + + // MIFARE Ultralight EV1 128 MF0UL21 MLEN 10h = 128 bytes, user memory pages 04h-23h + // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf rev 3.3 - 9 April 2019 + // memory organization ........... section 8.5, Fig 6, page 11 of 45 // data pages .................... section 8.5.5, page 14 of 45 - // CC derived from the user memory page range, not an NXP delivery value. + // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 + // CC derived from the page range. { MFU_TT_UL_EV1_128, "MIFARE Ultralight EV1 128", {{0xE1, 0x10, 0x10, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf - // NTAG210 MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // NXP NTAG210/212, doc 242330, rev 3.0 - 14 March 2013 - // data pages ................. section 8.5.5, page 13 of 46 - // memory content at delivery . section 8.5.6, Table 4, page 14 of 46 + // NTAG203 NT2H0301 MLEN 12h = 144 bytes, user memory pages 04h-27h + // https://www.nxp.com/docs/en/data-sheet/NTAG203.pdf rev 3.0 - 17 October 2011 + // memory organization ........... section 8.5, Table 5, page 10 of 30 + // data pages .................... section 8.5.4, page 13 of 30 + // OTP preset to all 0 ........... section 8.5.3, page 13 of 30 + // CC derived from the page range: page 03h is a plain OTP page here, not a + // Capability Container, so there is no delivery value to copy. Its dynamic + // lock bytes at page 28h use 4 page granularity (section 8.5.2, Fig 7, page + // 12 of 30) against 2 for NTAG213, so that Lock Control TLV would misdescribe + // this part - the plain empty NDEF message is written instead. + { + MFU_TT_NTAG_203, "NTAG203", + {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} + }, + + // NTAG210 NT2H1011 MLEN 06h = 48 bytes, user memory pages 04h-0Fh + // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf rev 3.0 - 14 March 2013 + // memory organization ........... section 8.5, Fig 4, page 10 of 46 + // data pages .................... section 8.5.5, page 13 of 46 + // content at delivery ........... section 8.5.6, Table 4, page 14 of 46 { MFU_TT_NTAG_210, "NTAG210", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/NT2L1001_NT2H1001.pdf - // NTAG210u same geometry as NTAG210 - // No dedicated datasheet was consulted. getTagType assigns this its own type - // bit (an exclusive GET_VERSION match), but UL_MEMORY_ARRAY gives it - // MAX_NTAG_210 and ul_print_type reports 48 bytes, so the user memory range - - // and therefore the CC - is the same as NTAG210. + // NTAG210u NT2L1001 / NT2H1001 MLEN 06h = 48 bytes, user memory blocks 04h-0Fh + // https://www.nxp.com/docs/en/data-sheet/NT2L1001_NT2H1001.pdf rev 3.0 - 7 September 2016 + // data blocks ................... section 9.5.4, page 11 of 32 + // content at delivery ........... section 9.5.5, Table 4, page 11 of 32 { MFU_TT_NTAG_210u, "NTAG210u", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf - // NTAG212 MLEN 10h = 128 bytes, user memory pages 04h-23h - // NXP NTAG210/212, doc 242330, rev 3.0 - 14 March 2013 - // data pages ................. section 8.5.5, page 13 of 46 - // memory content at delivery . section 8.5.6, Table 5, page 14 of 46 - // Ships with a Lock Control TLV (01 03 90 0A 34) ahead of the NDEF TLV. + // NTAG212 NT2L1211 MLEN 10h = 128 bytes, user memory pages 04h-23h + // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf rev 3.0 - 14 March 2013 + // memory organization ........... section 8.5, Fig 5, page 10 of 46 + // data pages .................... section 8.5.5, page 13 of 46 + // content at delivery ........... section 8.5.6, Table 5, page 14 of 46 { MFU_TT_NTAG_212, "NTAG212", {{0xE1, 0x10, 0x10, 0x00}, {0x01, 0x03, 0x90, 0x0A}, {0x34, 0x03, 0x00, 0xFE}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf - // NTAG213 MLEN 12h = 144 bytes, user memory pages 04h-27h - // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 - // memory organization ........ section 8.5, Fig 5, page 11 of 60 - // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 - // data pages ................. section 8.5.5, page 16 of 60 - // memory content at delivery . section 8.5.6, Table 5, page 17 of 60 - // Ships with a Lock Control TLV (01 03 A0 0C 34) ahead of the NDEF TLV. + // NTAG213 NT2H1311 MLEN 12h = 144 bytes, user memory pages 04h-27h + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 + // memory organization ........... section 8.5, Fig 5, page 11 of 60 + // data pages .................... section 8.5.5, page 16 of 60 + // content at delivery ........... section 8.5.6, Table 5, page 17 of 60 { MFU_TT_NTAG_213, "NTAG213", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf - // NTAG213F identical delivery content to NTAG213 - // NXP NTAG213F/216F, doc 262236, rev 3.6 - 28 September 2015 - // memory content at delivery . section 8.5.6, Table 5, page 17 of 55 + // NTAG213F NT2H1311F MLEN 12h = 144 bytes, user memory pages 04h-27h + // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf rev 3.6 - 28 September 2015 + // memory organization ........... section 8.5, Fig 6, page 12 of 55 + // data pages .................... section 8.5.5, page 16 of 55 + // content at delivery ........... section 8.5.6, Table 5, page 17 of 55 { MFU_TT_NTAG_213_F, "NTAG213F", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, - // https://www.nxp.com/docs/en/data-sheet/NT2H1311TT.pdf - // NTAG213TT and NTAG213C same geometry as NTAG213 - // No dedicated datasheet was consulted for either. getTagType assigns each its - // own type bit (exclusive GET_VERSION matches differing only in the product - // version bytes, storage size stays 0Fh), but UL_MEMORY_ARRAY gives both - // MAX_NTAG_213 and ul_print_type reports 144 bytes, so the user memory range - - // and therefore the CC - is the same as NTAG213. Note only page 03h is - // irreversible; pages 04h/05h are ordinary user memory and can be rewritten if - // a variant turns out to ship a different Lock Control TLV. + // NTAG213TT NT2H1311TT MLEN 12h = 144 bytes, user memory pages 04h-27h + // https://www.nxp.com/docs/en/data-sheet/NT2H1311TT.pdf rev 1.1 - 28 March 2017 + // memory organization ........... section 8.5, Fig 4, page 11 of 57 + // data pages .................... section 8.5.5, page 14 of 57 + // content at delivery ........... section 8.5.6, Table 5, page 15 of 57 { MFU_TT_NTAG_213_TT, "NTAG213TT", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, + + // NTAG213C NT2H1311C1DTL MLEN 12h = 144 bytes, user memory pages 04h-27h + // NO DATA SHEET. NXP publishes nothing for this part number and no other + // public documentation could be found. + // Most data come from commit ad19f8384 (2020-09-26, "add accurate detection for + // NT2H1311C1DTL") { MFU_TT_NTAG_213_C, "NTAG213C", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf - // NTAG215 MLEN 3Eh = 496 bytes, user memory pages 04h-81h - // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 - // memory organization ........ section 8.5, Fig 6, page 11 of 60 - // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 - // memory content at delivery . section 8.5.6, Table 6, page 17 of 60 - // The factory MLEN announces 496 bytes while the user memory holds 504. - // The datasheet gives no reason for the 8 byte difference; the NXP value is - // kept on purpose since under reporting can never push a write past the - // user memory, while a larger value could. + // NTAG215 NT2H1511 MLEN 3Eh = 496 bytes, user memory pages 04h-81h + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 + // memory organization ........... section 8.5, Fig 6, page 11 of 60 + // data pages .................... section 8.5.5, page 16 of 60 + // content at delivery ........... section 8.5.6, Table 6, page 17 of 60 + // The factory MLEN announces 496 bytes while the user memory holds 504. The + // data sheet gives no reason for the 8 byte difference { MFU_TT_NTAG_215, "NTAG215", {{0xE1, 0x10, 0x3E, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf - // NTAG216 MLEN 6Dh = 872 bytes, user memory pages 04h-E1h - // NXP NTAG213/215/216, doc 265332, rev 3.2 - 2 June 2015 - // memory organization ........ section 8.5, Fig 7, page 12 of 60 - // NDEF memory size ........... section 8.5.4, Table 4, page 16 of 60 - // memory content at delivery . section 8.5.6, Table 7, page 17 of 60 - // Same 16 byte under reporting as NTAG215, kept for the same reason. + // NTAG216 NT2H1611 MLEN 6Dh = 872 bytes, user memory pages 04h-E1h + // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 + // memory organization ........... section 8.5, Fig 7, page 12 of 60 + // data pages .................... section 8.5.5, page 16 of 60 + // content at delivery ........... section 8.5.6, Table 7, page 17 of 60 + // Announces 872 bytes against 888 of user memory. { MFU_TT_NTAG_216, "NTAG216", {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf - // NTAG216F identical delivery content to NTAG216 - // NXP NTAG213F/216F, doc 262236, rev 3.6 - 28 September 2015 - // memory content at delivery . section 8.5.6, Table 6, page 17 of 55 + // NTAG216F NT2H1611F MLEN 6Dh = 872 bytes, user memory pages 04h-E1h + // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf rev 3.6 - 28 September 2015 + // memory organization ........... section 8.5, Fig 7, page 12 of 55 + // data pages .................... section 8.5.5, page 16 of 55 + // content at delivery ........... section 8.5.6, Table 6, page 17 of 55 { MFU_TT_NTAG_216_F, "NTAG216F", {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, - // https://www.orangetags.com/wp-content/downloads/datasheet/NXP/NTAG203.pdf - // NTAG203 no datasheet of its own was consulted, but NTAG213/215/216 - // (doc 265332, rev 3.2, section 8.5, page 11 of 60) states that the - // manufacturing data, lock bytes, capability container and user memory - // pages of NTAG213 are compatible to NTAG203. - { - MFU_TT_NTAG_203, "NTAG203", - {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} - }, }; static const mfu_ndef_format_t *mfu_get_ndef_format(uint64_t tagtype) { From f3883a36498e8c174d4c69b164f1a4fd59db568c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sun, 30 Aug 2026 02:53:30 +0800 Subject: [PATCH 11/22] style: content compress --- client/src/cmdhfmfu.c | 40 ++++++++++++---------------------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 5500f0c04..f61243100 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -7832,19 +7832,13 @@ int CmdHF14MfuNDEFWrite(const char *Cmd) { // --------------------------------------------------------------------------- // NDEF formatting // -// Page 03h is the Capability Container and is One Time Programmable on every type -// below: a WRITE is bit-wise OR'ed with the current content and a bit set to 1 can -// never be cleared again. A wrong value is permanent, hence an unknown tag type is -// refused rather than guessed at. -// -// Each entry restores the NXP "memory content at delivery" for pages 03h, 04h and -// 05h. NTAG212/213/213F/213TT ship a Lock Control TLV in front of the NDEF TLV and -// the others do not, so the content is copied per type rather than assembled here. -// -// Only the NTAG21x family is delivered with a Capability Container at all. The -// MF0ICU1 / MF0ICU2 / MF0ULx1 parts and NTAG203 leave page 03h as a blank OTP -// page, so their CC is derived from the user memory page range and they get the -// plain empty NDEF message. +// Page 03h is the OTP Capability Container (CC): once written, it cannot be +// changed. Refuse unknown types to avoid a permanent wrong CC. +// Restore NXP's delivery content for pages 03h-05h. NTAG212/213/213F/213TT +// include a Lock Control TLV before the NDEF TLV; other types do not, so +// content is copied per type. +// Only NTAG21x ships with a CC. MF0ICU1/2, MF0ULx1 and NTAG203 leave 03h +// blank; derive their CC from the user memory range and use an empty NDEF. typedef struct { uint64_t tagtype; const char *name; @@ -8030,23 +8024,13 @@ int CmdHF14AMfUFormat(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfu format", "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability\n" - "Container to block 3, followed by an empty NDEF message. This is what a tag\n" - "needs before `hf mfu ndefwrite` will touch it.\n" + "Container to block 3, followed by an empty NDEF message.\n" "\n" - "The values written are the NXP factory delivery content for the detected tag\n" - "type. Block 3 is One Time Programmable on every supported type: a write is\n" - "OR'ed with the current content and a bit set to 1 can never be cleared. An\n" - "unknown tag type is therefore refused rather than guessed at, and a Capability\n" - "Container that cannot be reached from the current content is refused as well.\n" + "Writes NXP factory delivery content for the detected tag type. Block 3 is\n" + "One Time Programmable; unknown types and unreachable CCs are refused.\n" "\n" - "Note: the tag is re-selected and re-authenticated for every block written.", - "hf mfu format\n" - "hf mfu format -v\n" - "hf mfu format --erase\n" - "hf mfu format -k FFFFFFFF\n" - "hf mfu format -k 49454D4B41455242214E4143554F5946\n" - "hf mfu format -d E1101200 --force" - ); + "Note: the tag is re-selected and re-authenticated for each block written." + ); void *argtable[] = { arg_param_begin, From 5484d2083f02bdcbab1a0b32fcb3b8570357c18f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sun, 30 Aug 2026 03:00:07 +0800 Subject: [PATCH 12/22] fix: oops --- client/src/cmdhfmfu.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index f61243100..a2eee5ba4 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -8029,7 +8029,13 @@ int CmdHF14AMfUFormat(const char *Cmd) { "Writes NXP factory delivery content for the detected tag type. Block 3 is\n" "One Time Programmable; unknown types and unreachable CCs are refused.\n" "\n" - "Note: the tag is re-selected and re-authenticated for each block written." + "Note: the tag is re-selected and re-authenticated for each block written.", + "hf mfu format\n" + "hf mfu format -v\n" + "hf mfu format --erase\n" + "hf mfu format -k FFFFFFFF\n" + "hf mfu format -k 49454D4B41455242214E4143554F5946\n" + "hf mfu format -d E1101200 --force" ); void *argtable[] = { From 4a276dfcbc43fa1d91df0c19edf7a2d0e93868c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sun, 30 Aug 2026 03:39:19 +0800 Subject: [PATCH 13/22] docs: content clean up --- client/src/cmdhfmfu.c | 220 ++++------------------------------- doc/mfu_ndef_format_notes.md | 102 ++++++++++++++++ 2 files changed, 127 insertions(+), 195 deletions(-) create mode 100644 doc/mfu_ndef_format_notes.md diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index a2eee5ba4..2c1a443cd 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -7829,16 +7829,9 @@ int CmdHF14MfuNDEFWrite(const char *Cmd) { return PM3_SUCCESS; } -// --------------------------------------------------------------------------- -// NDEF formatting -// -// Page 03h is the OTP Capability Container (CC): once written, it cannot be -// changed. Refuse unknown types to avoid a permanent wrong CC. -// Restore NXP's delivery content for pages 03h-05h. NTAG212/213/213F/213TT -// include a Lock Control TLV before the NDEF TLV; other types do not, so -// content is copied per type. -// Only NTAG21x ships with a CC. MF0ICU1/2, MF0ULx1 and NTAG203 leave 03h -// blank; derive their CC from the user memory range and use an empty NDEF. +// NDEF formatting - restores the NXP factory delivery content (Capability +// Container + empty NDEF message) for the detected tag type. Block 3 is OTP. +// Per-type sources and rationale: doc/mfu_ndef_format_notes.md typedef struct { uint64_t tagtype; const char *name; @@ -7846,167 +7839,21 @@ typedef struct { } mfu_ndef_format_t; static const mfu_ndef_format_t mfu_ndef_format_table[] = { - - // MIFARE Ultralight MF0ICU1 MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // https://www.nxp.com/docs/en/data-sheet/MF0ICU1.pdf rev 3.9 - 23 July 2014 - // memory organization ........... section 7.5, Table 5, page 10 of 31 - // data pages .................... section 7.5, Table 5, page 10 of 31 - // page 03h is OTP, no CC at delivery - CC derived from the page range - { - MFU_TT_UL, "MIFARE Ultralight", - {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // MIFARE Ultralight C MF0ICU2 MLEN 12h = 144 bytes, user memory pages 04h-27h - // https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf rev 3.5 - 30 January 2026 - // memory organization ........... section 7.5, Table 5, page 8 of 35 - // data pages .................... section 7.5, Table 5, page 8 of 35 - // OTP preset to all 0 ........... section 7.5.4, page 11 of 35 - // CC derived from the page range. The data area ends at page 27h, right before - // the lock bytes at page 28h, so no Lock Control TLV is needed. - { - MFU_TT_UL_C, "MIFARE Ultralight C", - {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // MIFARE Ultralight EV1 48 MF0UL11 MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf rev 3.3 - 9 April 2019 - // memory organization ........... section 8.5, Fig 5, page 10 of 45 - // data pages .................... section 8.5.5, page 14 of 45 - // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 - // CC derived from the page range. - { - MFU_TT_UL_EV1_48, "MIFARE Ultralight EV1 48", - {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // MIFARE Ultralight EV1 128 MF0UL21 MLEN 10h = 128 bytes, user memory pages 04h-23h - // https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf rev 3.3 - 9 April 2019 - // memory organization ........... section 8.5, Fig 6, page 11 of 45 - // data pages .................... section 8.5.5, page 14 of 45 - // OTP default 00 00 00 00h ...... section 8.5.4, page 13-14 of 45 - // CC derived from the page range. - { - MFU_TT_UL_EV1_128, "MIFARE Ultralight EV1 128", - {{0xE1, 0x10, 0x10, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG203 NT2H0301 MLEN 12h = 144 bytes, user memory pages 04h-27h - // https://www.nxp.com/docs/en/data-sheet/NTAG203.pdf rev 3.0 - 17 October 2011 - // memory organization ........... section 8.5, Table 5, page 10 of 30 - // data pages .................... section 8.5.4, page 13 of 30 - // OTP preset to all 0 ........... section 8.5.3, page 13 of 30 - // CC derived from the page range: page 03h is a plain OTP page here, not a - // Capability Container, so there is no delivery value to copy. Its dynamic - // lock bytes at page 28h use 4 page granularity (section 8.5.2, Fig 7, page - // 12 of 30) against 2 for NTAG213, so that Lock Control TLV would misdescribe - // this part - the plain empty NDEF message is written instead. - { - MFU_TT_NTAG_203, "NTAG203", - {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG210 NT2H1011 MLEN 06h = 48 bytes, user memory pages 04h-0Fh - // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf rev 3.0 - 14 March 2013 - // memory organization ........... section 8.5, Fig 4, page 10 of 46 - // data pages .................... section 8.5.5, page 13 of 46 - // content at delivery ........... section 8.5.6, Table 4, page 14 of 46 - { - MFU_TT_NTAG_210, "NTAG210", - {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG210u NT2L1001 / NT2H1001 MLEN 06h = 48 bytes, user memory blocks 04h-0Fh - // https://www.nxp.com/docs/en/data-sheet/NT2L1001_NT2H1001.pdf rev 3.0 - 7 September 2016 - // data blocks ................... section 9.5.4, page 11 of 32 - // content at delivery ........... section 9.5.5, Table 4, page 11 of 32 - { - MFU_TT_NTAG_210u, "NTAG210u", - {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG212 NT2L1211 MLEN 10h = 128 bytes, user memory pages 04h-23h - // https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf rev 3.0 - 14 March 2013 - // memory organization ........... section 8.5, Fig 5, page 10 of 46 - // data pages .................... section 8.5.5, page 13 of 46 - // content at delivery ........... section 8.5.6, Table 5, page 14 of 46 - { - MFU_TT_NTAG_212, "NTAG212", - {{0xE1, 0x10, 0x10, 0x00}, {0x01, 0x03, 0x90, 0x0A}, {0x34, 0x03, 0x00, 0xFE}} - }, - - // NTAG213 NT2H1311 MLEN 12h = 144 bytes, user memory pages 04h-27h - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 - // memory organization ........... section 8.5, Fig 5, page 11 of 60 - // data pages .................... section 8.5.5, page 16 of 60 - // content at delivery ........... section 8.5.6, Table 5, page 17 of 60 - { - MFU_TT_NTAG_213, "NTAG213", - {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} - }, - - // NTAG213F NT2H1311F MLEN 12h = 144 bytes, user memory pages 04h-27h - // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf rev 3.6 - 28 September 2015 - // memory organization ........... section 8.5, Fig 6, page 12 of 55 - // data pages .................... section 8.5.5, page 16 of 55 - // content at delivery ........... section 8.5.6, Table 5, page 17 of 55 - { - MFU_TT_NTAG_213_F, "NTAG213F", - {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} - }, - - // NTAG213TT NT2H1311TT MLEN 12h = 144 bytes, user memory pages 04h-27h - // https://www.nxp.com/docs/en/data-sheet/NT2H1311TT.pdf rev 1.1 - 28 March 2017 - // memory organization ........... section 8.5, Fig 4, page 11 of 57 - // data pages .................... section 8.5.5, page 14 of 57 - // content at delivery ........... section 8.5.6, Table 5, page 15 of 57 - { - MFU_TT_NTAG_213_TT, "NTAG213TT", - {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} - }, - - // NTAG213C NT2H1311C1DTL MLEN 12h = 144 bytes, user memory pages 04h-27h - // NO DATA SHEET. NXP publishes nothing for this part number and no other - // public documentation could be found. - // Most data come from commit ad19f8384 (2020-09-26, "add accurate detection for - // NT2H1311C1DTL") - { - MFU_TT_NTAG_213_C, "NTAG213C", - {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} - }, - - // NTAG215 NT2H1511 MLEN 3Eh = 496 bytes, user memory pages 04h-81h - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 - // memory organization ........... section 8.5, Fig 6, page 11 of 60 - // data pages .................... section 8.5.5, page 16 of 60 - // content at delivery ........... section 8.5.6, Table 6, page 17 of 60 - // The factory MLEN announces 496 bytes while the user memory holds 504. The - // data sheet gives no reason for the 8 byte difference - { - MFU_TT_NTAG_215, "NTAG215", - {{0xE1, 0x10, 0x3E, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG216 NT2H1611 MLEN 6Dh = 872 bytes, user memory pages 04h-E1h - // https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf rev 3.2 - 2 June 2015 - // memory organization ........... section 8.5, Fig 7, page 12 of 60 - // data pages .................... section 8.5.5, page 16 of 60 - // content at delivery ........... section 8.5.6, Table 7, page 17 of 60 - // Announces 872 bytes against 888 of user memory. - { - MFU_TT_NTAG_216, "NTAG216", - {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, - - // NTAG216F NT2H1611F MLEN 6Dh = 872 bytes, user memory pages 04h-E1h - // https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf rev 3.6 - 28 September 2015 - // memory organization ........... section 8.5, Fig 7, page 12 of 55 - // data pages .................... section 8.5.5, page 16 of 55 - // content at delivery ........... section 8.5.6, Table 6, page 17 of 55 - { - MFU_TT_NTAG_216_F, "NTAG216F", - {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} - }, + { MFU_TT_UL, "MIFARE Ultralight", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_UL_C, "MIFARE Ultralight C", {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_UL_EV1_48, "MIFARE Ultralight EV1 48", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_UL_EV1_128, "MIFARE Ultralight EV1 128", {{0xE1, 0x10, 0x10, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_203, "NTAG203", {{0xE1, 0x10, 0x12, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_210, "NTAG210", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_210u, "NTAG210u", {{0xE1, 0x10, 0x06, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_212, "NTAG212", {{0xE1, 0x10, 0x10, 0x00}, {0x01, 0x03, 0x90, 0x0A}, {0x34, 0x03, 0x00, 0xFE}} }, + { MFU_TT_NTAG_213, "NTAG213", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, + { MFU_TT_NTAG_213_F, "NTAG213F", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, + { MFU_TT_NTAG_213_TT, "NTAG213TT", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, + { MFU_TT_NTAG_213_C, "NTAG213C", {{0xE1, 0x10, 0x12, 0x00}, {0x01, 0x03, 0xA0, 0x0C}, {0x34, 0x03, 0x00, 0xFE}} }, + { MFU_TT_NTAG_215, "NTAG215", {{0xE1, 0x10, 0x3E, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_216, "NTAG216", {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, + { MFU_TT_NTAG_216_F, "NTAG216F", {{0xE1, 0x10, 0x6D, 0x00}, {0x03, 0x00, 0xFE, 0x00}, {0x00, 0x00, 0x00, 0x00}} }, }; static const mfu_ndef_format_t *mfu_get_ndef_format(uint64_t tagtype) { @@ -8036,7 +7883,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { "hf mfu format -k FFFFFFFF\n" "hf mfu format -k 49454D4B41455242214E4143554F5946\n" "hf mfu format -d E1101200 --force" - ); + ); void *argtable[] = { arg_param_begin, @@ -8134,10 +7981,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { if (cc_len == MFU_BLOCK_SIZE) { - // A hand written Capability Container still must not announce more NDEF - // area than the tag physically holds. Block 3 is OTP, so an over reporting - // MLEN can never be taken back, and ndefwrite would then clamp against the - // whole chip - lock bytes, configuration and key pages included. + // -d must not announce more memory than this tag type actually has if ((fmt != NULL) && (cc_override[2] > fmt->page[0][2]) && (force == false)) { PrintAndLogEx(FAILED, "Capability Container announces more memory than this tag has"); PrintAndLogEx(INFO, " requested... %d bytes ( MLEN %02X )", cc_override[2] * 8, cc_override[2]); @@ -8194,9 +8038,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { return PM3_ESOFT; } - // Block 3 is OTP: a WRITE is OR'ed with what is already there and a bit that - // is set can never be cleared. Anything the OR can not produce is refused - // before a single byte goes to the tag. + // block 3 is OTP: refuse a target the current content can't reach via OR uint8_t *cur = data + (MFU_NDEF_CC_BLOCK * MFU_BLOCK_SIZE); bool blank = true; bool reachable = true; @@ -8239,20 +8081,13 @@ int CmdHF14AMfUFormat(const char *Cmd) { } } - // The erase range is derived from the MLEN in the table, never from -d, so a - // hand written Capability Container can not push it past the user memory. - // Every table entry announces at most the user memory of that type, which - // keeps the last block below the lock bytes and configuration pages. + // erase range from the table MLEN, never from -d - can't run past user memory uint16_t last_block = MFU_NDEF_CC_BLOCK + 2; if (erase && (fmt != NULL)) { last_block = (uint16_t)(MFU_NDEF_CC_BLOCK + (fmt->page[0][2] * 2)); } - // WRITE addresses blocks with a single byte, so block 255 is the last one - // reachable - the same limit MFU_NDEF_MAX_BYTES encodes for ndefread/ndefwrite. - // No current table entry comes close, but mfu_write_block takes a uint8_t and - // the cast below would silently wrap a larger block number back onto the UID - // and lock pages, so clamp here rather than rely on the table staying small. + // block 255 is the last one WRITE can reach with its single address byte if (last_block > 0xFF) { PrintAndLogEx(INFO, "Data area runs past block 255, stopping at the last addressable block"); last_block = 0xFF; @@ -8314,10 +8149,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { DropField(); PrintAndLogEx(NORMAL, ""); - // Block 3 is one time programmable, so there is exactly one chance to get it - // right. A tag can ACK a WRITE and still not commit the page - a weak field, a - // tear, or a block locking bit that was already set - and the write status - // alone would not show it. Read the formatted blocks back rather than trust it. + // read the formatted blocks back rather than trust the write status alone if (ul_auth_select(&card, tagtype, (has_auth_key || has_pwd), auth_key_ptr, pack, sizeof(pack), use_schann) == PM3_ESOFT) { PrintAndLogEx(WARNING, "Wrote the tag but could not re-select it to verify"); PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread") "` to check it yourself"); @@ -8345,9 +8177,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { if (memcmp(verify + MFU_BLOCK_SIZE, pages[1], 2 * MFU_BLOCK_SIZE) != 0) { PrintAndLogEx(FAILED, "Capability Container is correct but the empty NDEF message is not"); - // pages[1] and pages[2] are contiguous, and so are the two blocks in - // verify, so each side prints in a single call - sprint_hex_inrow hands - // back one shared static buffer, so two calls per line would alias. + // one sprint_hex_inrow() call per line: it returns a shared static buffer PrintAndLogEx(INFO, " wanted...... " _GREEN_("%s"), sprint_hex_inrow(pages[1], 2 * MFU_BLOCK_SIZE)); PrintAndLogEx(INFO, " on tag now.. " _RED_("%s"), sprint_hex_inrow(verify + MFU_BLOCK_SIZE, 2 * MFU_BLOCK_SIZE)); PrintAndLogEx(HINT, "Hint: these blocks are ordinary user memory, check the lock bytes"); diff --git a/doc/mfu_ndef_format_notes.md b/doc/mfu_ndef_format_notes.md new file mode 100644 index 000000000..d4a79a86e --- /dev/null +++ b/doc/mfu_ndef_format_notes.md @@ -0,0 +1,102 @@ +# Notes on `hf mfu format` + + +# Table of Contents +- [Notes on hf mfu format](#notes-on-hf-mfu-format) +- [Table of Contents](#table-of-contents) + - [Why the command exists](#why-the-command-exists) + - [Capability Container basics](#capability-container-basics) + - [Per-type delivery content](#per-type-delivery-content) + - [Lock Control TLV](#lock-control-tlv) + - [NTAG215 / NTAG216 under-reporting](#ntag215--ntag216-under-reporting) + - [NTAG213C](#ntag213c) + +## Why the command exists +^[Top](#top) + +`hf mfu ndefwrite` refuses a tag with no Capability Container (CC). Before this command the only +way to add one was a hand computed `hf mfu wrbl -b 3 -d ` — block 3 is One Time Programmable +(OTP), so a wrong value is permanent. + +`hf mfu format` writes the NXP factory delivery content (CC + an empty NDEF message) for the +detected tag type, restoring what the tag looked like before anything was written to it. + +## Capability Container basics +^[Top](#top) + +Page 3 (`E1 10 00`) is OTP on every type below: a WRITE is bit-wise OR'ed with the current +content, so a bit already set to 1 can never be cleared again. `MLEN * 8` is the size of the NDEF +data area in bytes. + +Consequences for the implementation, in `mfu_get_ndef_format()` / `CmdHF14AMfUFormat()` in +`client/src/cmdhfmfu.c`: + +- an unknown tag type is refused rather than guessed at +- a target CC that the current OTP content cannot reach (checked with the same bit-wise OR) is + refused before anything is written +- `-d` on a *known* type is capped at that type's own MLEN unless `--force` is given, so a typo + cannot silently announce more memory than the tag holds +- `--erase`'s end block is derived from the table's MLEN, never from `-d`, so it cannot run past + the user memory into the lock bytes or configuration pages +- after writing, the command re-selects and reads blocks 3-5 back to confirm the OTP write + actually took — a tag can ACK a WRITE and still not commit the page (weak field, tearing, a lock + bit already set) + +## Per-type delivery content +^[Top](#top) + +Only the NTAG21x family ships with a CC at all. UL / UL-C / UL EV1 and NTAG203 leave page 3 blank +at delivery, so their CC is derived from the user memory range instead of copied from a data +sheet. + +| Type | Part | MLEN | User memory | Data sheet | +|---|---|---|---|---| +| MIFARE Ultralight | MF0ICU1 | 06h (48B) | pages 04h-0Fh | [MF0ICU1.pdf](https://www.nxp.com/docs/en/data-sheet/MF0ICU1.pdf) rev 3.9, §7.5 Table 5 (p.10/31, OTP blank) | +| MIFARE Ultralight C | MF0ICU2 | 12h (144B) | pages 04h-27h | [MF0ICU2.pdf](https://www.nxp.com/docs/en/data-sheet/MF0ICU2.pdf) rev 3.5, §7.5 Table 5 (p.8/35), §7.5.4 (p.11/35, OTP blank) | +| MIFARE Ultralight EV1 48 | MF0UL11 | 06h (48B) | pages 04h-0Fh | [MF0ULX1.pdf](https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf) rev 3.3, §8.5 Fig 5 (p.10/45), §8.5.4 (p.13-14/45, OTP blank) | +| MIFARE Ultralight EV1 128 | MF0UL21 | 10h (128B) | pages 04h-23h | [MF0ULX1.pdf](https://www.nxp.com/docs/en/data-sheet/MF0ULX1.pdf) rev 3.3, §8.5 Fig 6 (p.11/45), §8.5.4 (p.13-14/45, OTP blank) | +| NTAG203 | NT2H0301 | 12h (144B) | pages 04h-27h | [NTAG203.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG203.pdf) rev 3.0, §8.5 Table 5 (p.10/30), §8.5.3 (p.13/30, OTP blank) | +| NTAG210 | NT2H1011 | 06h (48B) | pages 04h-0Fh | [NTAG210_212.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf) rev 3.0, §8.5.6 Table 4 (p.14/46) | +| NTAG210u | NT2L1001 / NT2H1001 | 06h (48B) | pages 04h-0Fh | [NT2L1001_NT2H1001.pdf](https://www.nxp.com/docs/en/data-sheet/NT2L1001_NT2H1001.pdf) rev 3.0, §9.5.5 Table 4 (p.11/32) | +| NTAG212 | NT2L1211 | 10h (128B) | pages 04h-23h | [NTAG210_212.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG210_212.pdf) rev 3.0, §8.5.6 Table 5 (p.14/46) | +| NTAG213 | NT2H1311 | 12h (144B) | pages 04h-27h | [NTAG213_215_216.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf) rev 3.2, §8.5.6 Table 5 (p.17/60) | +| NTAG213F | NT2H1311F | 12h (144B) | pages 04h-27h | [NTAG213F_216F.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf) rev 3.6, §8.5.6 Table 5 (p.17/55) | +| NTAG213TT | NT2H1311TT | 12h (144B) | pages 04h-27h | [NT2H1311TT.pdf](https://www.nxp.com/docs/en/data-sheet/NT2H1311TT.pdf) rev 1.1, §8.5.6 Table 5 (p.15/57) | +| NTAG213C | NT2H1311C1DTL | 12h (144B) | pages 04h-27h | none — see [NTAG213C](#ntag213c) | +| NTAG215 | NT2H1511 | 3Eh (496B) | pages 04h-81h | [NTAG213_215_216.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf) rev 3.2, §8.5.6 Table 6 (p.17/60) | +| NTAG216 | NT2H1611 | 6Dh (872B) | pages 04h-E1h | [NTAG213_215_216.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf) rev 3.2, §8.5.6 Table 7 (p.17/60) | +| NTAG216F | NT2H1611F | 6Dh (872B) | pages 04h-E1h | [NTAG213F_216F.pdf](https://www.nxp.com/docs/en/data-sheet/NTAG213F_216F.pdf) rev 3.6, §8.5.6 Table 6 (p.17/55) | + +## Lock Control TLV +^[Top](#top) + +Standards ref: NFC Forum Type 2 Tag Operation, and the Capability Container layout in the data +sheets cited above. + +NTAG212, NTAG213, NTAG213F and NTAG213TT are delivered with a 5 byte Lock Control TLV ahead of the +NDEF TLV (`01 03 ...`). The other types in the table +are not. This TLV tells an NFC device where the *dynamic* lock bytes live so it can lock the tag +read-only — on these parts the dynamic lock bytes sit just past the user memory (e.g. NTAG213 at +page 40h, right after the page 04h-27h data area), so the TLV exists purely for that use case, not +because a writer needs to avoid overwriting anything. + +`hf mfu format` copies this TLV verbatim from the factory content; it does not construct one. +`hf mfu ndefwrite` preserves any control TLV (type `01` or `02`) it finds ahead of the NDEF TLV +before overwriting the data area — see the code for the exact scan. + +## NTAG215 / NTAG216 under-reporting +^[Top](#top) + +The factory MLEN announces less than the physical user memory: NTAG215 announces 496 bytes of a +504 byte area, NTAG216 announces 872 of 888. The data sheet does not explain the 8/16 byte gap. +The NXP value is used as-is rather than corrected upward, since under-reporting can never let a +write run past the user memory while a larger value could. + +## NTAG213C +^[Top](#top) + +NXP publishes no data sheet for this part number (NT2H1311C1DTL) and none could be found anywhere +else. It was added to the client in commit `ad19f8384` (2020-09-26, "add accurate detection for +NT2H1311C1DTL") from an observed tag's `GET_VERSION` response, which differs from a plain NTAG213 +only in the minor product version byte (`01h` vs `00h`); the storage size byte — the one that +encodes the 144 byte user memory — is identical. The NTAG213 content is used on that basis. From 08cf2e430ef29adb2fd0e987bf0fb93622b566e9 Mon Sep 17 00:00:00 2001 From: YoungJules Date: Mon, 31 Aug 2026 13:14:35 +0200 Subject: [PATCH 14/22] Added possibilty to write a found stamp to a binary file. --- client/experimental_lib/KGH_TOOLS.md | 3 ++ .../example_c/legic_migrate_tool.c | 44 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/client/experimental_lib/KGH_TOOLS.md b/client/experimental_lib/KGH_TOOLS.md index 26a7c93d4..c646e2c47 100644 --- a/client/experimental_lib/KGH_TOOLS.md +++ b/client/experimental_lib/KGH_TOOLS.md @@ -9,6 +9,8 @@ Examples: ```bash ./kgh_tools COM13 read_badge_number ./kgh_tools COM13 read_info +./kgh_tools COM13 read_stamp +./kgh_tools COM13 read_stamp -o stamp.bin ./kgh_tools COM13 write_card 600001 --stamp-file stamp.bin ``` @@ -16,6 +18,7 @@ Commands: - `read_badge_number` prints the badge number only. - `read_info` prints one-line JSON. +- `read_stamp` prints the stamp as 8 hex chars, or writes raw 4 bytes with `-o/--output-file`. - `write_card (--stamp-file | --stamp-hex <8hex>)` writes the card. Notes: diff --git a/client/experimental_lib/example_c/legic_migrate_tool.c b/client/experimental_lib/example_c/legic_migrate_tool.c index 1f4d298a6..bedbcef3a 100644 --- a/client/experimental_lib/example_c/legic_migrate_tool.c +++ b/client/experimental_lib/example_c/legic_migrate_tool.c @@ -125,6 +125,17 @@ static bool load_stamp_file(const char *path, uint8_t stamp[4]) { return true; } +static bool save_stamp_file(const char *path, const uint8_t stamp[4]) { + FILE *fp = fopen(path, "wb"); + if (fp == NULL) { + return false; + } + + size_t written = fwrite(stamp, 1, 4, fp); + fclose(fp); + return written == 4; +} + static bool get_arg_value(int argc, char *argv[], const char *flag, const char **value) { for (int i = 3; i < argc - 1; ++i) { if (strcmp(argv[i], flag) == 0) { @@ -380,6 +391,15 @@ static bool decode_badge_value(const uint8_t *dump, uint16_t len, uint32_t *badg return decode_badge_bcd(&dump[31], badge_out); } +static bool extract_stamp(const uint8_t *dump, uint16_t len, uint8_t stamp[4]) { + if (len <= 30) { + return false; + } + + memcpy(stamp, dump + 27, 4); + return true; +} + static void print_json_string(const char *key, const char *value, bool last) { printf("\"%s\": \"%s\"%s", key, value, last ? "" : ","); } @@ -510,6 +530,7 @@ int main(int argc, char *argv[]) { fprintf(stderr, "Usage:\n"); fprintf(stderr, " %s read_badge_number [-v|--verbose]\n", argv[0]); fprintf(stderr, " %s read_info\n", argv[0]); + fprintf(stderr, " %s read_stamp [-o|--output-file ]\n", argv[0]); fprintf(stderr, " %s write_card (--stamp-file | --stamp-hex <8hex>)\n", argv[0]); return EXIT_FAILURE; } @@ -535,6 +556,29 @@ int main(int argc, char *argv[]) { } else if (verbose) { fprintf(stderr, "failed to read card info\n"); } + } else if (strcmp(argv[2], "read_stamp") == 0) { + const char *output_file = NULL; + bool has_output = get_arg_value(argc, argv, "-o", &output_file) || get_arg_value(argc, argv, "--output-file", &output_file); + + legic_read_result_t res; + if (read_legic_dump(&res, verbose)) { + uint8_t stamp[4] = {0}; + if (extract_stamp(res.dump, res.len, stamp)) { + if (has_output) { + if (save_stamp_file(output_file, stamp)) { + rc = EXIT_SUCCESS; + } else { + fprintf(stderr, "failed to write stamp file\n"); + } + } else { + printf("%02X%02X%02X%02X\n", stamp[0], stamp[1], stamp[2], stamp[3]); + rc = EXIT_SUCCESS; + } + } + free_legic_read_result(&res); + } else if (verbose) { + fprintf(stderr, "failed to read stamp\n"); + } } else if (strcmp(argv[2], "write_card") == 0) { if (argc < 4) { fprintf(stderr, "missing badge number\n"); From 71ca59a8ad3e4a269c32409be936e5de05dd5dea Mon Sep 17 00:00:00 2001 From: Julian Isaac Date: Fri, 4 Sep 2026 23:14:22 +0200 Subject: [PATCH 15/22] Moved the new tool to tools/kgh and renamed it legic_kgh_tool. Added some validation so we don't return random bytes from non-kgh cards. Applied some styling to the new code. Added GPL header to new source file. Cleaned up the static build. --- client/experimental_lib/CMakeLists.txt | 128 +++++++----------- tools/kgh/CMakeLists.txt | 35 +++++ .../KGH_TOOLS.md => tools/kgh/README.md | 46 +++---- .../kgh/legic_kgh_tool.c | 38 +++++- 4 files changed, 135 insertions(+), 112 deletions(-) create mode 100644 tools/kgh/CMakeLists.txt rename client/experimental_lib/KGH_TOOLS.md => tools/kgh/README.md (52%) rename client/experimental_lib/example_c/legic_migrate_tool.c => tools/kgh/legic_kgh_tool.c (92%) diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index 417dba71e..ea54e5577 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -523,26 +523,17 @@ endif(NOT SKIPREADLINE EQUAL 1) if (BZIP2_FOUND) set(ADDITIONAL_DIRS ${BZIP2_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) - if (MINGW) - set(BZIP2_LIBRARIES /mingw64/lib/libbz2.a) - endif() set(ADDITIONAL_LNK ${BZIP2_LIBRARIES} ${ADDITIONAL_LNK}) endif (BZIP2_FOUND) if (LZ4_FOUND) set(ADDITIONAL_DIRS ${LZ4_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) - if (MINGW) - set(LZ4_LIBRARIES /mingw64/lib/liblz4.a) - endif() set(ADDITIONAL_LNK ${LZ4_LIBRARIES} ${ADDITIONAL_LNK}) endif (LZ4_FOUND) if (ZLIB_FOUND) add_definitions("-DHAVE_ZLIB") set(ADDITIONAL_DIRS ${ZLIB_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) - if (MINGW) - set(ZLIB_LIBRARIES /mingw64/lib/libz.a) - endif() set(ADDITIONAL_LNK ${ZLIB_LIBRARIES} ${ADDITIONAL_LNK}) endif (ZLIB_FOUND) @@ -715,25 +706,19 @@ add_library(pm3rrg_rdv4_static STATIC ${ADDITIONAL_SRC} ) -add_executable(kgh_tools - ${PM3_ROOT}/client/experimental_lib/example_c/legic_migrate_tool.c -) - -set_target_properties(kgh_tools PROPERTIES OUTPUT_NAME "kgh_tools") -if (MINGW) - target_link_options(kgh_tools PRIVATE -static -static-libgcc) -endif() - -target_link_libraries(kgh_tools PRIVATE pm3rrg_rdv4_static) -target_include_directories(kgh_tools PRIVATE - ${PM3_ROOT}/common - ${PM3_ROOT}/client/include - ${PM3_ROOT}/client/src - ${PM3_ROOT}/include -) - -target_compile_definitions(pm3rrg_rdv4 PRIVATE LIBPM3) -target_compile_definitions(pm3rrg_rdv4_static PRIVATE LIBPM3) +set(PM3_LIBRARY_TARGETS pm3rrg_rdv4 pm3rrg_rdv4_static) +foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_compile_definitions(${target} PRIVATE LIBPM3) + target_compile_options(${target} PUBLIC -Wall -Werror -O3) + target_include_directories(${target} PRIVATE + ${PM3_ROOT}/common + ${PM3_ROOT}/common_fpga + ${PM3_ROOT}/include + ${PM3_ROOT}/client/src + ${PM3_ROOT}/client/include + ${ADDITIONAL_DIRS} + ) +endforeach() if (UNIX AND NOT APPLE) # Fail the build if a client source file is missing from TARGET_SOURCES. @@ -741,18 +726,22 @@ if (UNIX AND NOT APPLE) set_property(TARGET pm3rrg_rdv4 APPEND_STRING PROPERTY LINK_FLAGS " -Wl,--no-undefined") endif() -target_compile_options(pm3rrg_rdv4 PUBLIC -Wall -Werror -O3) -target_compile_options(pm3rrg_rdv4_static PUBLIC -Wall -Werror -O3) if (EMBED_READLINE) if (NOT SKIPREADLINE EQUAL 1) - add_dependencies(pm3rrg_rdv4 ncurses readline) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + add_dependencies(${target} ncurses readline) + endforeach() endif (NOT SKIPREADLINE EQUAL 1) endif (EMBED_READLINE) if (EMBED_BZIP2) - add_dependencies(pm3rrg_rdv4 bzip2) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + add_dependencies(${target} bzip2) + endforeach() endif (EMBED_BZIP2) if (EMBED_LZ4) - add_dependencies(pm3rrg_rdv4 lz4) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + add_dependencies(${target} lz4) + endforeach() endif (EMBED_LZ4) if (MINGW) @@ -760,7 +749,9 @@ if (MINGW) # and setting _ISOC99_SOURCE sets internally __USE_MINGW_ANSI_STDIO=1 # FTR __USE_MINGW_ANSI_STDIO seems deprecated in Mingw32 # but not Mingw64 https://fr.osdn.net/projects/mingw/lists/archive/users/2019-January/000199.html - target_compile_definitions(pm3rrg_rdv4 PRIVATE _ISOC99_SOURCE) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_compile_definitions(${target} PRIVATE _ISOC99_SOURCE) + endforeach() set(CMAKE_C_FLAGS "-mno-ms-bitfields -fexec-charset=cp850 ${CMAKE_C_FLAGS}") set(CMAKE_CXX_FLAGS "-mno-ms-bitfields -fexec-charset=cp850 ${CMAKE_CXX_FLAGS}") @@ -769,24 +760,6 @@ if (MINGW) set(ADDITIONAL_LNK ws2_32 ${ADDITIONAL_LNK}) endif (MINGW) -target_include_directories(pm3rrg_rdv4 PRIVATE - ${PM3_ROOT}/common - ${PM3_ROOT}/common_fpga - ${PM3_ROOT}/include - ${PM3_ROOT}/client/src - ${PM3_ROOT}/client/include - ${ADDITIONAL_DIRS} -) - -target_include_directories(pm3rrg_rdv4_static PRIVATE - ${PM3_ROOT}/common - ${PM3_ROOT}/common_fpga - ${PM3_ROOT}/include - ${PM3_ROOT}/client/src - ${PM3_ROOT}/client/include - ${ADDITIONAL_DIRS} -) - if (NOT APPLE) # required for Raspberry Pi, but breaks with clang (OSX). Need to be at the end of the linker line. set(ADDITIONAL_LNK ${ADDITIONAL_LNK} -Wl,--as-needed -latomic -Wl,--no-as-needed) @@ -810,37 +783,26 @@ if (NOT WHEREAMI_FOUND) set(ADDITIONAL_LNK pm3rrg_rdv4_whereami ${ADDITIONAL_LNK}) endif (NOT WHEREAMI_FOUND) -target_link_libraries(pm3rrg_rdv4 PRIVATE - m - pm3rrg_rdv4_mbedtls - pm3rrg_rdv4_cliparser - pm3rrg_rdv4_lua - pm3rrg_rdv4_tinycbor - pm3rrg_rdv4_amiibo - pm3rrg_rdv4_reveng - pm3rrg_rdv4_hardnested - pm3rrg_rdv4_id48 - pm3rrg_rdv4_mqtt - pm3rrg_rdv4_vec - ${ADDITIONAL_LNK}) - -target_link_libraries(pm3rrg_rdv4_static PRIVATE - m - pm3rrg_rdv4_mbedtls - pm3rrg_rdv4_cliparser - pm3rrg_rdv4_lua - pm3rrg_rdv4_tinycbor - pm3rrg_rdv4_amiibo - pm3rrg_rdv4_reveng - pm3rrg_rdv4_hardnested - pm3rrg_rdv4_id48 - pm3rrg_rdv4_mqtt - pm3rrg_rdv4_vec - ${ADDITIONAL_LNK}) +foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_link_libraries(${target} PRIVATE + m + pm3rrg_rdv4_mbedtls + pm3rrg_rdv4_cliparser + pm3rrg_rdv4_lua + pm3rrg_rdv4_tinycbor + pm3rrg_rdv4_amiibo + pm3rrg_rdv4_reveng + pm3rrg_rdv4_hardnested + pm3rrg_rdv4_id48 + pm3rrg_rdv4_mqtt + pm3rrg_rdv4_vec + ${ADDITIONAL_LNK}) +endforeach() if (NOT SKIPPTHREAD EQUAL 1) - target_link_libraries(pm3rrg_rdv4 PRIVATE pthread) - target_link_libraries(pm3rrg_rdv4_static PRIVATE pthread) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_link_libraries(${target} PRIVATE pthread) + endforeach() endif (NOT SKIPPTHREAD EQUAL 1) if (NOT SKIPPYTHON EQUAL 1) @@ -852,4 +814,6 @@ if (NOT SKIPPYTHON EQUAL 1) endif (PYTHON3EMBED_FOUND OR PYTHON3_FOUND) endif (NOT SKIPPYTHON EQUAL 1) -target_link_directories(pm3rrg_rdv4 PRIVATE ${ADDITIONAL_LNKDIRS}) +foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_link_directories(${target} PRIVATE ${ADDITIONAL_LNKDIRS}) +endforeach() diff --git a/tools/kgh/CMakeLists.txt b/tools/kgh/CMakeLists.txt new file mode 100644 index 000000000..27c62eb4f --- /dev/null +++ b/tools/kgh/CMakeLists.txt @@ -0,0 +1,35 @@ +#----------------------------------------------------------------------------- +# Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# See LICENSE.txt for the text of the license. +#----------------------------------------------------------------------------- + +cmake_minimum_required(VERSION 3.10) +project(legic_kgh_tool) + +set(PM3_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..) + +add_subdirectory(${PM3_ROOT}/client/experimental_lib ${CMAKE_BINARY_DIR}/experimental_lib) + +add_executable(legic_kgh_tool legic_kgh_tool.c) +target_link_libraries(legic_kgh_tool PRIVATE pm3rrg_rdv4_static) +target_include_directories(legic_kgh_tool PRIVATE + ${PM3_ROOT}/common + ${PM3_ROOT}/client/include + ${PM3_ROOT}/client/src + ${PM3_ROOT}/include +) + +if (MINGW) + target_link_options(legic_kgh_tool PRIVATE -static -static-libgcc) +endif() diff --git a/client/experimental_lib/KGH_TOOLS.md b/tools/kgh/README.md similarity index 52% rename from client/experimental_lib/KGH_TOOLS.md rename to tools/kgh/README.md index c646e2c47..d3fff500e 100644 --- a/client/experimental_lib/KGH_TOOLS.md +++ b/tools/kgh/README.md @@ -1,17 +1,18 @@ -# kgh_tools +# legic_kgh_tool ## Running -`kgh_tools` is a small CLI wrapper around the LEGIC migration helpers. +`legic_kgh_tool` reads KGH LEGIC card information, badge numbers, and stamps, +and writes the supported KGH card layout. Examples: ```bash -./kgh_tools COM13 read_badge_number -./kgh_tools COM13 read_info -./kgh_tools COM13 read_stamp -./kgh_tools COM13 read_stamp -o stamp.bin -./kgh_tools COM13 write_card 600001 --stamp-file stamp.bin +./legic_kgh_tool COM13 read_badge_number +./legic_kgh_tool COM13 read_info +./legic_kgh_tool COM13 read_stamp +./legic_kgh_tool COM13 read_stamp -o stamp.bin +./legic_kgh_tool COM13 write_card 600001 --stamp-file stamp.bin ``` Commands: @@ -19,15 +20,14 @@ Commands: - `read_badge_number` prints the badge number only. - `read_info` prints one-line JSON. - `read_stamp` prints the stamp as 8 hex chars, or writes raw 4 bytes with `-o/--output-file`. -- `write_card (--stamp-file | --stamp-hex <8hex>)` writes the card. +- `write_card (--stamp-file | --stamp-hex <8hex>)` writes the supported KGH layout. Notes: - Windows ProxSpace examples use `COM13`. - The stamp is 4 bytes and specific to your site. - It can be specified as a .bin (use .e.g hexedit to create it) - Or as a command-line option (less secure) as --stamp-hex (e.g.) 003EF417 - You can find the stamp on any card in use at your site by using read_info (see above) + It can be specified as a `.bin` file or as `--stamp-hex` (for example, `003EF417`). +- You can retrieve the stamp from a supported KGH card with `read_info` or `read_stamp`. - Linux examples usually use `/dev/ttyACM0` or similar. - `--verbose` can be useful for `read_badge_number` and `write_card`, if they fail for mysterious reasons. @@ -36,42 +36,36 @@ Notes: Do this in ProxSpace: ```bash -cd ~/proxmark3/client/experimental_lib +cd ~/proxmark3/tools/kgh rm -rf build-lite cmake -G "MSYS Makefiles" -S . -B build-lite \ -DSKIPPYTHON=1 \ -DSKIPREADLINE=1 \ - -DSKIPJANSSYSTEM=1 \ + -DSKIPJANSSONSYSTEM=1 \ -DSKIPWHEREAMISYSTEM=1 \ -DSKIPBT=1 -cmake --build build-lite --target kgh_tools -j -objdump -p build-lite/kgh_tools.exe | grep -i "DLL Name" +cmake --build build-lite --target legic_kgh_tool -j +objdump -p build-lite/legic_kgh_tool.exe | grep -i "DLL Name" ``` ## Building Linux ```bash -cd client/experimental_lib +cd tools/kgh rm -rf build-linux cmake -S . -B build-linux \ -DSKIPPYTHON=1 \ -DSKIPREADLINE=1 \ - -DSKIPJANSSYSTEM=1 \ + -DSKIPJANSSONSYSTEM=1 \ -DSKIPWHEREAMISYSTEM=1 \ -DSKIPBT=1 -cmake --build build-linux --target kgh_tools -j -ldd build-linux/kgh_tools +cmake --build build-linux --target legic_kgh_tool -j +ldd build-linux/legic_kgh_tool ``` ## Static Link Notes -- `kgh_tools` is linked against `pm3rrg_rdv4_static`. +- `legic_kgh_tool` is linked against `pm3rrg_rdv4_static`. - On MinGW, CMake adds `-static -static-libgcc` for the target. - Linux builds are not the same as the ProxSpace single-EXE deployment. - If CMakeCache paths change between ProxSpace and a native shell, delete the build dir and reconfigure. - -## Existing Helper Scripts - -- `01make_lib.sh` creates `build/`, runs `cmake ..`, then `make -j`. -- `01make_lib_continue.sh` reruns `make -j` in `build/`. -- `00make_swig.sh` regenerates the SWIG wrappers before building the library. diff --git a/client/experimental_lib/example_c/legic_migrate_tool.c b/tools/kgh/legic_kgh_tool.c similarity index 92% rename from client/experimental_lib/example_c/legic_migrate_tool.c rename to tools/kgh/legic_kgh_tool.c index bedbcef3a..429eea54a 100644 --- a/client/experimental_lib/example_c/legic_migrate_tool.c +++ b/tools/kgh/legic_kgh_tool.c @@ -1,3 +1,19 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- + #include #include #include @@ -238,6 +254,14 @@ static void free_legic_read_result(legic_read_result_t *res) { memset(&res->card, 0, sizeof(res->card)); } +static bool is_kgh_card(const uint8_t *dump, uint16_t len) { + return len >= sizeof(k_legic_template_head) && + dump[5] == 0x60 && dump[6] == 0xEA && + dump[7] == 0x9F && dump[8] == 0xFF && + dump[22] == 0x0D && dump[23] == 0xC0 && + dump[24] == 0x08 && dump[25] == 0x00; +} + static const char *classify_legic_card(const uint8_t *dump, uint16_t len) { if (len < 9) { return "unknown"; @@ -252,7 +276,7 @@ static const char *classify_legic_card(const uint8_t *dump, uint16_t len) { return "IAM"; } - if ((dump[7] & 0x0F) == 0x0F && dump[8] == 0xFF) { + if (is_kgh_card(dump, len)) { return "KGH"; } @@ -519,7 +543,11 @@ static int read_badge_from_card(uint32_t *badge_out) { dump[i] ^= crc; } - bool ok = decode_badge_bcd(&dump[31], badge_out); + bool is_kgh = is_kgh_card(dump, datalen); + bool ok = is_kgh && decode_badge_bcd(&dump[31], badge_out); + if (!is_kgh) { + fprintf(stderr, "not a supported KGH card\n"); + } free(dump); g_printAndLog = prev_print; return ok ? 0 : 1; @@ -563,7 +591,7 @@ int main(int argc, char *argv[]) { legic_read_result_t res; if (read_legic_dump(&res, verbose)) { uint8_t stamp[4] = {0}; - if (extract_stamp(res.dump, res.len, stamp)) { + if (is_kgh_card(res.dump, res.len) && extract_stamp(res.dump, res.len, stamp)) { if (has_output) { if (save_stamp_file(output_file, stamp)) { rc = EXIT_SUCCESS; @@ -574,6 +602,8 @@ int main(int argc, char *argv[]) { printf("%02X%02X%02X%02X\n", stamp[0], stamp[1], stamp[2], stamp[3]); rc = EXIT_SUCCESS; } + } else { + fprintf(stderr, "not a supported KGH card\n"); } free_legic_read_result(&res); } else if (verbose) { @@ -614,7 +644,7 @@ int main(int argc, char *argv[]) { uint8_t dump[35] = {0}; build_migration_dump(badge, stamp, dump, sizeof(dump)); - if (legic_migrate_dump(dump, sizeof(dump), true, (const uint8_t[2]){0x60, 0xEA}, true) == PM3_SUCCESS) { + if (legic_migrate_dump(dump, sizeof(dump), true, (const uint8_t[2]) {0x60, 0xEA}, true) == PM3_SUCCESS) { rc = EXIT_SUCCESS; } else { fprintf(stderr, "failed to write card\n"); From 7e2ecc0ba67b1ddb87374563a566dc867ed96418 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sat, 5 Sep 2026 05:18:36 +0800 Subject: [PATCH 16/22] rename: hf mfu format to ndefformat --- CHANGELOG.md | 2 +- client/src/cmdhfmfu.c | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc000b85..6023c5eb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +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 mfu format` - NDEF format Ultralight/NTAG tags, restores the NXP factory Capability Container for the detected type (@0x6r1an0y) +- Added `hf mfu ndefformat` - NDEF format Ultralight/NTAG tags, restores the NXP factory Capability Container for the detected type (@0x6r1an0y) - Added tools script `external_sam_read.py` enabling PM3 3 Easy and Proxmark 5 to use an external SIM/SAM reader for `hf iclass sam` and `hf seos sam` commands (@antiklesys) - Added `nfc encode` and `hf mfu ndefwrite` - build NDEF URI/Text/AAR records and write them to Ultralight tags (@0x6r1an0y) - Fixed `hf emrtd info` - the picture viewer now scales images to the window instead of pinning them at native size (@iceman1001) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 2c1a443cd..97ceb81c3 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -7866,10 +7866,10 @@ static const mfu_ndef_format_t *mfu_get_ndef_format(uint64_t tagtype) { return NULL; } -int CmdHF14AMfUFormat(const char *Cmd) { +int CmdHF14MfuNDEFFormat(const char *Cmd) { CLIParserContext *ctx; - CLIParserInit(&ctx, "hf mfu format", + CLIParserInit(&ctx, "hf mfu ndefformat", "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability\n" "Container to block 3, followed by an empty NDEF message.\n" "\n" @@ -7877,12 +7877,12 @@ int CmdHF14AMfUFormat(const char *Cmd) { "One Time Programmable; unknown types and unreachable CCs are refused.\n" "\n" "Note: the tag is re-selected and re-authenticated for each block written.", - "hf mfu format\n" - "hf mfu format -v\n" - "hf mfu format --erase\n" - "hf mfu format -k FFFFFFFF\n" - "hf mfu format -k 49454D4B41455242214E4143554F5946\n" - "hf mfu format -d E1101200 --force" + "hf mfu ndefformat\n" + "hf mfu ndefformat -v\n" + "hf mfu ndefformat --erase\n" + "hf mfu ndefformat -k FFFFFFFF\n" + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946\n" + "hf mfu ndefformat -d E1101200 --force" ); void *argtable[] = { @@ -7953,7 +7953,7 @@ int CmdHF14AMfUFormat(const char *Cmd) { PrintAndLogEx(FAILED, "Don't know the Capability Container for this tag type"); PrintAndLogEx(INFO, "Block 3 is One Time Programmable, a wrong value can not be undone,"); PrintAndLogEx(INFO, "so this command will not guess one."); - PrintAndLogEx(HINT, "Hint: supply it yourself with `" _YELLOW_("hf mfu format -d --force") "`"); + PrintAndLogEx(HINT, "Hint: supply it yourself with `" _YELLOW_("hf mfu ndefformat -d --force") "`"); return PM3_ENOTIMPL; } if (force == false) { @@ -9062,9 +9062,9 @@ static command_t CommandTable[] = { {"aesgetuid", CmdHF14AMfUAESGetUID, IfPm3Iso14443a, "Ultralight-AES - Get UID when RID in use"}, {"setkey", CmdHF14AMfUSetKey, IfPm3Iso14443a, "Ultralight C/AES - Set 3DES/AES keys"}, {"dump", CmdHF14AMfUDump, IfPm3Iso14443a, "Dump MIFARE Ultralight family tag to binary file"}, - {"format", CmdHF14AMfUFormat, IfPm3Iso14443a, "Format tag as NDEF, writes the Capability Container"}, {"incr", CmdHF14AMfUIncr, IfPm3Iso14443a, "Increments Ev1/NTAG counter"}, {"info", CmdHF14AMfUInfo, IfPm3Iso14443a, "Tag information"}, + {"ndefformat", CmdHF14MfuNDEFFormat, IfPm3Iso14443a, "Format tag as NDEF, writes the Capability Container"}, {"ndefread", CmdHF14MfuNDEFRead, IfPm3Iso14443a, "Prints NDEF records from card"}, {"ndefwrite", CmdHF14MfuNDEFWrite, IfPm3Iso14443a, "Write NDEF records to card"}, {"rdbl", CmdHF14AMfURdBl, IfPm3Iso14443a, "Read block"}, From 7bfd6b6189ed23b655c606547bb1fd60e7295e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sat, 5 Sep 2026 05:18:51 +0800 Subject: [PATCH 17/22] docs: content clean up --- doc/mfu_ndef_format_notes.md | 60 ++++++++++-------------------------- 1 file changed, 16 insertions(+), 44 deletions(-) diff --git a/doc/mfu_ndef_format_notes.md b/doc/mfu_ndef_format_notes.md index d4a79a86e..8f18917e1 100644 --- a/doc/mfu_ndef_format_notes.md +++ b/doc/mfu_ndef_format_notes.md @@ -1,8 +1,8 @@ -# Notes on `hf mfu format` +# Notes on `hf mfu ndefformat` # Table of Contents -- [Notes on hf mfu format](#notes-on-hf-mfu-format) +- [Notes on hf mfu ndefformat](#notes-on-hf-mfu-ndefformat) - [Table of Contents](#table-of-contents) - [Why the command exists](#why-the-command-exists) - [Capability Container basics](#capability-container-basics) @@ -14,40 +14,27 @@ ## Why the command exists ^[Top](#top) -`hf mfu ndefwrite` refuses a tag with no Capability Container (CC). Before this command the only -way to add one was a hand computed `hf mfu wrbl -b 3 -d ` — block 3 is One Time Programmable -(OTP), so a wrong value is permanent. +`hf mfu ndefwrite` refuses a tag with no Capability Container (CC). Before this command the only way to add one was a hand computed `hf mfu wrbl -b 3 -d ` — block 3 is One Time Programmable (OTP), so a wrong value is permanent. -`hf mfu format` writes the NXP factory delivery content (CC + an empty NDEF message) for the -detected tag type, restoring what the tag looked like before anything was written to it. +`hf mfu ndefformat` writes the NXP factory delivery content (CC + an empty NDEF message) for the detected tag type, restoring what the tag looked like before anything was written to it. ## Capability Container basics ^[Top](#top) -Page 3 (`E1 10 00`) is OTP on every type below: a WRITE is bit-wise OR'ed with the current -content, so a bit already set to 1 can never be cleared again. `MLEN * 8` is the size of the NDEF -data area in bytes. +Page 3 (`E1 10 00`) is OTP on every type below: a WRITE is bit-wise OR'ed with the current content, so a bit already set to 1 can never be cleared again. `MLEN * 8` is the size of the NDEF data area in bytes. -Consequences for the implementation, in `mfu_get_ndef_format()` / `CmdHF14AMfUFormat()` in -`client/src/cmdhfmfu.c`: +Consequences for the implementation, in `mfu_get_ndef_format()` / `CmdHF14AMfUFormat()` in `client/src/cmdhfmfu.c`: - an unknown tag type is refused rather than guessed at -- a target CC that the current OTP content cannot reach (checked with the same bit-wise OR) is - refused before anything is written -- `-d` on a *known* type is capped at that type's own MLEN unless `--force` is given, so a typo - cannot silently announce more memory than the tag holds -- `--erase`'s end block is derived from the table's MLEN, never from `-d`, so it cannot run past - the user memory into the lock bytes or configuration pages -- after writing, the command re-selects and reads blocks 3-5 back to confirm the OTP write - actually took — a tag can ACK a WRITE and still not commit the page (weak field, tearing, a lock - bit already set) +- a target CC that the current OTP content cannot reach (checked with the same bit-wise OR) is refused before anything is written +- `-d` on a *known* type is capped at that type's own MLEN unless `--force` is given, so a typo cannot silently announce more memory than the tag holds +- `--erase`'s end block is derived from the table's MLEN, never from `-d`, so it cannot run past the user memory into the lock bytes or configuration pages +- after writing, the command re-selects and reads blocks 3-5 back to confirm the OTP write actually took — a tag can ACK a WRITE and still not commit the page (weak field, tearing, a lock bit already set) ## Per-type delivery content ^[Top](#top) -Only the NTAG21x family ships with a CC at all. UL / UL-C / UL EV1 and NTAG203 leave page 3 blank -at delivery, so their CC is derived from the user memory range instead of copied from a data -sheet. +Only the NTAG21x family ships with a CC at all. UL / UL-C / UL EV1 and NTAG203 leave page 3 blank at delivery, so their CC is derived from the user memory range instead of copied from a data sheet. | Type | Part | MLEN | User memory | Data sheet | |---|---|---|---|---| @@ -70,33 +57,18 @@ sheet. ## Lock Control TLV ^[Top](#top) -Standards ref: NFC Forum Type 2 Tag Operation, and the Capability Container layout in the data -sheets cited above. +Standards ref: NFC Forum Type 2 Tag Operation, and the Capability Container layout in the data sheets cited above. -NTAG212, NTAG213, NTAG213F and NTAG213TT are delivered with a 5 byte Lock Control TLV ahead of the -NDEF TLV (`01 03 ...`). The other types in the table -are not. This TLV tells an NFC device where the *dynamic* lock bytes live so it can lock the tag -read-only — on these parts the dynamic lock bytes sit just past the user memory (e.g. NTAG213 at -page 40h, right after the page 04h-27h data area), so the TLV exists purely for that use case, not -because a writer needs to avoid overwriting anything. +NTAG212, NTAG213, NTAG213F and NTAG213TT are delivered with a 5 byte Lock Control TLV ahead of the NDEF TLV (`01 03 ...`). The other types in the table are not. This TLV tells an NFC device where the *dynamic* lock bytes live so it can lock the tag read-only — on these parts the dynamic lock bytes sit just past the user memory (e.g. NTAG213 at page 40h, right after the page 04h-27h data area), so the TLV exists purely for that use case, not because a writer needs to avoid overwriting anything. -`hf mfu format` copies this TLV verbatim from the factory content; it does not construct one. -`hf mfu ndefwrite` preserves any control TLV (type `01` or `02`) it finds ahead of the NDEF TLV -before overwriting the data area — see the code for the exact scan. +`hf mfu ndefformat` copies this TLV verbatim from the factory content; it does not construct one. `hf mfu ndefwrite` preserves any control TLV (type `01` or `02`) it finds ahead of the NDEF TLV before overwriting the data area — see the code for the exact scan. ## NTAG215 / NTAG216 under-reporting ^[Top](#top) -The factory MLEN announces less than the physical user memory: NTAG215 announces 496 bytes of a -504 byte area, NTAG216 announces 872 of 888. The data sheet does not explain the 8/16 byte gap. -The NXP value is used as-is rather than corrected upward, since under-reporting can never let a -write run past the user memory while a larger value could. +The factory MLEN announces less than the physical user memory: NTAG215 announces 496 bytes of a 504 byte area, NTAG216 announces 872 of 888. The data sheet does not explain the 8/16 byte gap. The NXP value is used as-is rather than corrected upward, since under-reporting can never let a write run past the user memory while a larger value could. ## NTAG213C ^[Top](#top) -NXP publishes no data sheet for this part number (NT2H1311C1DTL) and none could be found anywhere -else. It was added to the client in commit `ad19f8384` (2020-09-26, "add accurate detection for -NT2H1311C1DTL") from an observed tag's `GET_VERSION` response, which differs from a plain NTAG213 -only in the minor product version byte (`01h` vs `00h`); the storage size byte — the one that -encodes the 144 byte user memory — is identical. The NTAG213 content is used on that basis. +NXP publishes no data sheet for this part number (NT2H1311C1DTL) and none could be found anywhere else. It was added to the client in commit `ad19f8384` (2020-09-26, "add accurate detection for NT2H1311C1DTL") from an observed tag's `GET_VERSION` response, which differs from a plain NTAG213 only in the minor product version byte (`01h` vs `00h`); the storage size byte — the one that encodes the 144 byte user memory — is identical. The NTAG213 content is used on that basis. From 6960a6e788811a2ca2489550e30df89022e5d2d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=90=E6=AD=AA?= Date: Sat, 5 Sep 2026 05:40:45 +0800 Subject: [PATCH 18/22] fix: oops --- client/src/cmdhfmfu.h | 2 +- client/src/cmdnfc.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h index 73b92962d..e55982c57 100644 --- a/client/src/cmdhfmfu.h +++ b/client/src/cmdhfmfu.h @@ -59,7 +59,7 @@ int mfuc_test_authentication_support(void); int CmdHFMFUltra(const char *Cmd); int CmdHF14MfuNDEFRead(const char *Cmd); // used by cmdnfc.c int CmdHF14MfuNDEFWrite(const char *Cmd); // used by cmdnfc.c -int CmdHF14AMfUFormat(const char *Cmd); // used by cmdnfc.c +int CmdHF14MfuNDEFFormat(const char *Cmd); // used by cmdnfc.c int CmdHF14MfUTamper(const char *Cmd); #define MFU_TT_UNKNOWN 0x0ULL diff --git a/client/src/cmdnfc.c b/client/src/cmdnfc.c index 7b88126af..8aa531ace 100644 --- a/client/src/cmdnfc.c +++ b/client/src/cmdnfc.c @@ -392,7 +392,7 @@ static int CmdNFCType2Write(const char *Cmd) { } static int CmdNFCType2Format(const char *Cmd) { - return CmdHF14AMfUFormat(Cmd); + return CmdHF14MfuNDEFFormat(Cmd); } static int CmdNFCType2Help(const char *Cmd); From c21ddfdb74eef370d9a3d118fb5ea457795232cf Mon Sep 17 00:00:00 2001 From: dxl <64101226@qq.com> Date: Fri, 4 Sep 2026 09:54:06 +0800 Subject: [PATCH 19/22] Power consumption testing has been added for pm5. --- armsrc/at32_unit_test.c | 58 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/armsrc/at32_unit_test.c b/armsrc/at32_unit_test.c index edf589094..be0d5103c 100644 --- a/armsrc/at32_unit_test.c +++ b/armsrc/at32_unit_test.c @@ -1827,6 +1827,59 @@ void test_config_uart_tx2_to_dbgio(void) { gpio_init(GPIOA, &gpio_init_struct); // PA2_TX } +#include "fpga_loader.h" +#include "lfsampling.h" + +void test_max_power(void) { + FpgaResetComInterface(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + + SpinDelay(100); + FpgaSetup24MHzClk(); + + uint8_t data; + + // 开所有的灯 + LED_A_ON(); + LED_B_ON(); + LED_C_ON(); + LED_D_ON(); + test_i2c_rgb_simple(); + + // 0x03 DischargeCurrentControl 寄存器 + data = 0xE1; // 修改放电电流到 3A + I2C_BufferWrite(&data, 1, 0x03, 0x93); + // 0x05 ChargerTermination/TimerControl 寄存器 + data = 0x1A; // 禁用定时器,正常为了安全可能需要在MainLoop喂狗 + I2C_BufferWrite(&data, 1, 0x05, 0x93); + +#if 0 + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER); +#else + + // 开场 + // FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD + // FPGA_MAJOR_MODE_HF_READER + // FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD); + LFSetupFPGAForADC(LF_DIVISOR_125, true); + + gpio_fpga_mod_only_setup(); + Gpio_SSC_DOUT_Low(); + + // 配置低频高Q + data = 0x87; // 0x87 = 10000111: 125k + 高Q + 开启两个LED + I2C_BufferWrite(&data, 1, 0x02, 0x51 << 1); + +#endif + + // 调到最高输出电压 + FpgaSendCommand(FPGA_CMD_SET_PWR_PWM_LOW_COUNT, 4095u & 0xFFF); + + // 蜂鸣器持续响着 + test_beep(); +} + // 覆盖 UnitTestMain 实现单元测试 void UnitTestMain(void); @@ -1847,13 +1900,16 @@ void UnitTestMain(void) { // ------------------------------- 关闭所有的LED ------------------------------- LEDsoff(); + // ------------------------------- 功耗测试 ------------------------------- + // test_max_power(); + // ------------------------------- 关闭FPGA输出 ------------------------------- // 不然的话调试的时候也会很发热 SpinDelay(500); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // ------------------------------- 测试 配置UART TX2为DBGIO输出 ------------------------------- - test_config_uart_tx2_to_dbgio(); + // test_config_uart_tx2_to_dbgio(); // ------------------------------- 测试 蓝牙电池套件UART通信 ------------------------------- // test_bwm_uart(); From ea5485b4b8b499f9414b513d7effd398f4608b47 Mon Sep 17 00:00:00 2001 From: dxl <64101226@qq.com> Date: Fri, 4 Sep 2026 10:39:46 +0800 Subject: [PATCH 20/22] Rename CMD_PM5_QC_TEST to CMD_PM5_QC_TEST_HW and delete repeated def: CMD_PM5_BWM_SET_CAP --- armsrc/appmain.c | 4 ++-- client/src/cmdhw.c | 4 ++-- include/pm3_cmd.h | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index ea4896e76..7b56690c7 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -3867,13 +3867,13 @@ static void PacketReceived(PacketCommandNG *packet) { break; } #ifdef PM5 - case CMD_PM5_QC_TEST: { + case CMD_PM5_QC_TEST_HW: { uint8_t failed_item = 0; uint32_t timeout_ms = 0; if (packet->length >= sizeof(timeout_ms)) { memcpy(&timeout_ms, packet->data.asBytes, sizeof(timeout_ms)); } - reply_ng(CMD_PM5_QC_TEST, QCTestPM5(&failed_item, timeout_ms) ? PM3_SUCCESS : PM3_EFAILED, &failed_item, 1); + reply_ng(CMD_PM5_QC_TEST_HW, QCTestPM5(&failed_item, timeout_ms) ? PM3_SUCCESS : PM3_EFAILED, &failed_item, 1); break; } case CMD_PM5_RGB_SET: { diff --git a/client/src/cmdhw.c b/client/src/cmdhw.c index a30c6dd22..a222d1c8a 100644 --- a/client/src/cmdhw.c +++ b/client/src/cmdhw.c @@ -2288,11 +2288,11 @@ static int CmdPM5QCTest(const char *Cmd) { PrintAndLogEx(INFO, "Performing QC test for the PM5..."); clearCommandBuffer(); - SendCommandNG(CMD_PM5_QC_TEST, (uint8_t *)&timeout_ms, sizeof(timeout_ms)); + SendCommandNG(CMD_PM5_QC_TEST_HW, (uint8_t *)&timeout_ms, sizeof(timeout_ms)); PacketResponseNG resp; // wait a bit longer than the device side sequence timeout, with headroom for RTC drift - if (WaitForResponseTimeout(CMD_PM5_QC_TEST, &resp, timeout_ms + (timeout_ms / 5) + 1000) == false) { + if (WaitForResponseTimeout(CMD_PM5_QC_TEST_HW, &resp, timeout_ms + (timeout_ms / 5) + 1000) == false) { SendCommandNG(CMD_BREAK_LOOP, NULL, 0); PrintAndLogEx(WARNING, "command execution time out"); return PM3_ETIMEOUT; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 452a2cbc7..fdbd2c07b 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -874,12 +874,11 @@ typedef struct { #define CMD_EEPROM_FACTORY_INFO_READ 0x0172 #define CMD_EEPROM_FACTORY_INFO_WRITE 0x0173 // PM5, QC test for the hardware -#define CMD_PM5_QC_TEST 0x0177 +#define CMD_PM5_QC_TEST_HW 0x0177 // PM5, set the antenna RGB LED colour (payload: r,g,b). Used by `hf/lf tune --rgb`. #define CMD_PM5_RGB_SET 0x0178 // PM5, provision BWM fuel-gauge (BQ27427) Design Capacity. Used by `hw bwmsetcap`. #define CMD_PM5_BWM_SET_CAP 0x0179 -#define CMD_PM5_BWM_SET_CAP 0x0179 // PM5, enable/disable BWM battery charging (AW32001E CEB). Used by `hw bwmcharge`. #define CMD_PM5_BWM_CHARGE_EN 0x017A // PM5, toggle automatic power-off on USB unplug. Used by `hw bwmautooff`. From 93983ed82f847af2a3dda3af515a60b48dc3c29c Mon Sep 17 00:00:00 2001 From: dxl <64101226@qq.com> Date: Fri, 4 Sep 2026 16:13:21 +0800 Subject: [PATCH 21/22] PM5 unit test logic updated. --- armsrc/at32_unit_test.c | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/armsrc/at32_unit_test.c b/armsrc/at32_unit_test.c index be0d5103c..a4dc5bc20 100644 --- a/armsrc/at32_unit_test.c +++ b/armsrc/at32_unit_test.c @@ -1050,18 +1050,23 @@ void test_beep(void) { } } -void test_power_of_by_btn(void) { +void test_power_off_by_btn(void) { usb_enable(); SpinDelay(1000); - dxl_print_dbg("SystemStart\n"); + // dxl_print_dbg("SystemStart\n"); while (1) { + // 第一阶段,等按下 if (is_btn_pressed()) { + // 第二阶段,等抬起 + while (is_btn_pressed()) {} + // 第三阶段,等一会儿 + SpinDelay(50); // 拉低直接关机 - dxl_print_dbg("SystemOff\n"); + // dxl_print_dbg("SystemOff\n"); Gpio_ARM_Power_ON_Low(); // 拉低关机的话,还会有一段PWR电容放电时间,此时我们应当让系统进入死循环,不再处理任何事情 while (1) { - dxl_print_dbg("Waiting Power Off\n"); + // dxl_print_dbg("Waiting Power Off\n"); } } } @@ -1880,6 +1885,21 @@ void test_max_power(void) { test_beep(); } +void test_nvic_reset(void) { + LED_A_ON(); + SpinDelay(100); + LED_A_OFF(); + LED_B_ON(); + while (1) { + if (is_btn_pressed()) { + LED_B_OFF(); + LED_C_ON(); + while (is_btn_pressed()) {} + NVIC_SystemReset(); + } + } +} + // 覆盖 UnitTestMain 实现单元测试 void UnitTestMain(void); @@ -1908,6 +1928,9 @@ void UnitTestMain(void) { SpinDelay(500); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + // ------------------------------- 测试 NVIC 系统复位 ------------------------------- + // test_nvic_reset(); + // ------------------------------- 测试 配置UART TX2为DBGIO输出 ------------------------------- // test_config_uart_tx2_to_dbgio(); @@ -1942,7 +1965,7 @@ void UnitTestMain(void) { // test_i2c_ant_software(); // ------------------------------- 测试按钮关机 ------------------------------- - // test_power_of_by_btn(); + // test_power_off_by_btn(); // ------------------------------- 测试蜂鸣器 ------------------------------- // usb_enable(); From fc355df0507778e48d9beb17fa10377a6474fc38 Mon Sep 17 00:00:00 2001 From: dxl <64101226@qq.com> Date: Sat, 5 Sep 2026 13:26:13 +0800 Subject: [PATCH 22/22] Added IO test capabilities to the factory QC for PM5. --- armsrc/appmain.c | 72 +++++++++++++++++++++++++++++++++++++++- client/src/cmdhw.c | 82 ++++++++++++++++++++++++++++++++++++++++++++-- include/pm3_cmd.h | 1 + 3 files changed, 151 insertions(+), 4 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 7b56690c7..3a86b0eaa 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1143,7 +1143,7 @@ static bool QCTestPM5(uint8_t *failed_item, uint32_t timeout_ms) { // 蜂鸣器 (PB13 使能, PC9 = TMR8_CH4 调制) 由通用 buzzer 模块驱动 BuzzerSetup(); - LEDsoff(); // 在开始测试之前线关闭所有LED + LEDsoff(); // 在开始测试之前先关闭所有LED *failed_item = 2; // 在开始测试之前,如果按钮是按下的,则认为失败,有可能按钮不良卡住了 @@ -1224,6 +1224,59 @@ out: return result; } +static int8_t QCTestPM5IO(uint16_t index, uint8_t status) { + // !!! No one is allowed to modify the definition and order of this list except DXL. + // Otherwise, the PM5 factory tester will fail to check. + struct qc_io_map { + crm_periph_clock_type gpio_clk; + gpio_type *gpio_group; + uint16_t gpio_pin; + } const qc_io_map[] = { + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_14}, // SIGIN1-5x2P-SWD-CLK + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_13}, // SIGIN2-5x2P-SWD-DIO + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_3}, // SIGIN3-5x2P-UART_RX + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_2}, // SIGIN4-5x2P-UART_TX + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_7}, // SIGIN5-CEP-USB_RXP(MOSI) + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_6}, // SIGIN6-CEP-USB_RXN(MISO) + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_9}, // SIGIN7-CEP-USB_SBU(UART-1-line) + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_11}, // SIGIN8-CEP-USB_DN + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_4}, // SIGIN9-CEP-USB_TXP(CSN) + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_12}, // SIGIN10-CEP-USB_DP + {.gpio_clk = CRM_GPIOA_PERIPH_CLOCK, .gpio_group = GPIOA, .gpio_pin = GPIO_PINS_5}, // SIGIN11-CEP-USB_TXN(CLK) + }; + if (index >= ARRAYLEN(qc_io_map)) { + return PM3_EINVARG; + } + // For RXP/RXN/TXP/TXN + gpio_inter_usb_spi_role_setup(); + Gpio_Inter_USB_SPI_Role_High(); + // Enable the clock for the GPIO port and configure the pin as output + crm_periph_clock_enable(qc_io_map[index].gpio_clk, TRUE); + // Configure the GPIO pin as output or input based on the status parameter + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_pins = qc_io_map[index].gpio_pin; + gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT; + // Set the GPIO pin state or RESET to default based on the status parameter( -> Preset <- ) + if (status == 0) { + gpio_bits_reset(qc_io_map[index].gpio_group, qc_io_map[index].gpio_pin); + } else if (status == 1) { + gpio_bits_set(qc_io_map[index].gpio_group, qc_io_map[index].gpio_pin); + } else { + // Reset to Default state or MUX + if (index == 0 || index == 1) { + // SIGIN1-SWD-CLK or SIGIN2-SWD-DIO + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_pull = index == 0 ? GPIO_PULL_DOWN : GPIO_PULL_UP; + gpio_pin_mux_config(qc_io_map[index].gpio_group, qc_io_map[index].gpio_pin, GPIO_MUX_0); + } else { + gpio_init_struct.gpio_mode = GPIO_MODE_INPUT; + } + } + gpio_init(qc_io_map[index].gpio_group, &gpio_init_struct); + return PM3_SUCCESS; +} + #endif // static, not on the stack: this is 512 bytes and PacketReceived is already deep @@ -3876,6 +3929,23 @@ static void PacketReceived(PacketCommandNG *packet) { reply_ng(CMD_PM5_QC_TEST_HW, QCTestPM5(&failed_item, timeout_ms) ? PM3_SUCCESS : PM3_EFAILED, &failed_item, 1); break; } + case CMD_PM5_QC_TEST_IO: { + struct p { + uint32_t pwd; // 0xDEADBEEF + uint16_t index; // index of the IO to test + uint8_t status; // 0 = low, 1 = high, 2 = float or RESET TO DEFAULT + } PACKED; + struct p *payload = (struct p *)packet->data.asBytes; + // !!! IMPORTANT !!! + // This password must not be written in the client software. + // Users should never use this command without knowing its purpose, otherwise it may damage the device. + if (payload->pwd != 0xDEADBEEF) { + reply_ng(CMD_PM5_QC_TEST_IO, PM3_EFAILED, NULL, 0); + break; + } + reply_ng(CMD_PM5_QC_TEST_IO, QCTestPM5IO(payload->index, payload->status), NULL, 0); + break; + } case CMD_PM5_RGB_SET: { // Set the antenna RGB LED colour (used by `hf/lf tune --rgb`). struct p { diff --git a/client/src/cmdhw.c b/client/src/cmdhw.c index a222d1c8a..062cbd815 100644 --- a/client/src/cmdhw.c +++ b/client/src/cmdhw.c @@ -2267,19 +2267,95 @@ static int CmdPM5QCTest(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hw qc_pm5", "QC Test for the PM5", - "hw qc_pm5 -> run QC test with default 20 second timeout\n" - "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\n" + "hw qc_pm5 -t 3 -> run hardware QC test with a 3 second timeout\n" + "hw qc_pm5 --iolow --pwd -> drive PM5 test IO low\n" + "hw qc_pm5 --iohigh --pwd -> drive PM5 test IO high\n" + "hw qc_pm5 --ioreset --pwd -> reset PM5 test IO to default"); void *argtable[] = { arg_param_begin, arg_u64_0("t", "timeout", "", "test sequence timeout in seconds (default 20)"), + arg_u64_0(NULL, "iolow", "", "drive PM5 test IO low"), + arg_u64_0(NULL, "iohigh", "", "drive PM5 test IO high"), + arg_u64_0(NULL, "ioreset", "", "reset PM5 test IO to default"), + arg_str0(NULL, "pwd", "", "QC test password in hex (required for IO tests)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); + uint32_t timeout_ms = arg_get_u32_def(ctx, 1, 20); timeout_ms *= 1000; + + bool io_low = arg_get_u64_count(ctx, 2) > 0; + bool io_high = arg_get_u64_count(ctx, 3) > 0; + bool io_reset = arg_get_u64_count(ctx, 4) > 0; + int io_count = (io_low ? 1 : 0) + (io_high ? 1 : 0) + (io_reset ? 1 : 0); + + uint16_t io_index = 0; + uint8_t io_status = 0; + if (io_low) { + io_index = (uint16_t)arg_get_u32(ctx, 2); + io_status = 0; + } else if (io_high) { + io_index = (uint16_t)arg_get_u32(ctx, 3); + io_status = 1; + } else if (io_reset) { + io_index = (uint16_t)arg_get_u32(ctx, 4); + io_status = 2; + } + + uint8_t pwd[4]; + int dlen = 0; + int res = CLIParamHexToBuf(arg_get_str(ctx, 5), pwd, sizeof(pwd), &dlen); CLIParserFree(ctx); + if (io_count > 1) { + PrintAndLogEx(ERR, "only one of --iolow, --iohigh, --ioreset may be specified"); + return PM3_EINVARG; + } + + if (io_count == 1) { + if (res || dlen != sizeof(pwd)) { + PrintAndLogEx(ERR, "invalid password format, must be hex(8 chars)"); + return PM3_EINVARG; + } + + PrintAndLogEx(WARNING, _RED_("!!! WARNING: PM5 IO QC test drives the test IO pins directly !!!")); + PrintAndLogEx(WARNING, _RED_("!!! This can damage the device if used incorrectly !!!")); + PrintAndLogEx(WARNING, _RED_("!!! Only proceed if you know exactly what you are doing !!!")); + PrintAndLogEx(INFO, "PM5 IO QC test password: 0x%02X%02X%02X%02X", pwd[0], pwd[1], pwd[2], pwd[3]); + + struct { + uint32_t pwd; // QC password, verified by the device + uint16_t index; // index of the IO to test + uint8_t status; // 0 = low, 1 = high, 2 = float or RESET TO DEFAULT + } PACKED payload = { + .pwd = BYTES2UINT32_BE(pwd), + .index = io_index, + .status = io_status, + }; + + PrintAndLogEx(INFO, "Performing PM5 IO QC test (index %u, status %u)...", io_index, io_status); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_QC_TEST_IO, (uint8_t *)&payload, sizeof(payload)); + + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_QC_TEST_IO, &resp, 1000) == false) { + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + PrintAndLogEx(WARNING, "command execution time out"); + return PM3_ETIMEOUT; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to perform IO QC test on PM5 (wrong password?)"); + return resp.status; + } + PrintAndLogEx(INFO, "PM5 IO QC test successful."); + return PM3_SUCCESS; + } + if (timeout_ms == 0) { PrintAndLogEx(ERR, "timeout must be greater than zero"); return PM3_EINVARG; @@ -2594,7 +2670,7 @@ static command_t CommandTable[] = { {"fpga", CmdFPGA, IfPm3Present, "Fpga commands"}, {"fpgaoff", CmdFPGAOff, IfPm3Present, "Turn off FPGA on device"}, {"ant_pm5", CmdPM5Ant, IfPm5StdAnt, "Control the antennal of pm5"}, - {"qc_pm5", CmdPM5QCTest, IfPm5, "Perform QC test for the PM5"}, + {"qc_pm5", CmdPM5QCTest, IfPm5, "Perform QC test (hardware or IO) for the PM5"}, {"factorydata", CmdDeviceFactoryData, IfI2cEeprom, "Get/Set the factory data for Device"}, {"lcd", CmdLCD, IfPm3Lcd, "Send command/data to LCD"}, {"lcdreset", CmdLCDReset, IfPm3Lcd, "Hardware reset LCD"}, diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index fdbd2c07b..e1029c8cc 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -874,6 +874,7 @@ typedef struct { #define CMD_EEPROM_FACTORY_INFO_READ 0x0172 #define CMD_EEPROM_FACTORY_INFO_WRITE 0x0173 // PM5, QC test for the hardware +#define CMD_PM5_QC_TEST_IO 0x0176 #define CMD_PM5_QC_TEST_HW 0x0177 // PM5, set the antenna RGB LED colour (payload: r,g,b). Used by `hf/lf tune --rgb`. #define CMD_PM5_RGB_SET 0x0178