diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a989608a..c6b9e1ba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Added TA1=96 support via pwm to sim module `sim024.bin` - v4.66 (@antiklesys) +- Added `hf mfu ndefformat` - NDEF format Ultralight/NTAG tags, restores the NXP factory Capability Container for the detected type (@0x6r1an0y) - Changed `lf hitag` - refactoring hitag2 operations and now they work much better (@iceman1001) - Fixed `lf hitag list` - now prints in same style like the rest (@iceman1001) - Changed pathing - client now supports `~/` tilde sign in paths (@iceman1001) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 5e4551c1d..8158fb85a 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 @@ -3871,13 +3924,30 @@ 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_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: { diff --git a/armsrc/at32_unit_test.c b/armsrc/at32_unit_test.c index edf589094..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"); } } } @@ -1827,6 +1832,74 @@ 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(); +} + +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); @@ -1847,13 +1920,19 @@ void UnitTestMain(void) { // ------------------------------- 关闭所有的LED ------------------------------- LEDsoff(); + // ------------------------------- 功耗测试 ------------------------------- + // test_max_power(); + // ------------------------------- 关闭FPGA输出 ------------------------------- // 不然的话调试的时候也会很发热 SpinDelay(500); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + // ------------------------------- 测试 NVIC 系统复位 ------------------------------- + // test_nvic_reset(); + // ------------------------------- 测试 配置UART TX2为DBGIO输出 ------------------------------- - test_config_uart_tx2_to_dbgio(); + // test_config_uart_tx2_to_dbgio(); // ------------------------------- 测试 蓝牙电池套件UART通信 ------------------------------- // test_bwm_uart(); @@ -1886,7 +1965,7 @@ void UnitTestMain(void) { // test_i2c_ant_software(); // ------------------------------- 测试按钮关机 ------------------------------- - // test_power_of_by_btn(); + // test_power_off_by_btn(); // ------------------------------- 测试蜂鸣器 ------------------------------- // usb_enable(); diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index 5d2d906a1..ea54e5577 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 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) @@ -692,7 +699,26 @@ add_library(pm3rrg_rdv4 SHARED ${ADDITIONAL_SRC} ) -target_compile_definitions(pm3rrg_rdv4 PRIVATE LIBPM3) +add_library(pm3rrg_rdv4_static STATIC + ${PM3_ROOT}/client/src/proxmark3.c + ${PM3_ROOT}/client/src/guidummy.cpp + ${TARGET_SOURCES} + ${ADDITIONAL_SRC} +) + +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. @@ -700,17 +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) 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) @@ -718,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}") @@ -727,15 +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} -) - 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) @@ -759,22 +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}) +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) + foreach (target IN LISTS PM3_LIBRARY_TARGETS) + target_link_libraries(${target} PRIVATE pthread) + endforeach() endif (NOT SKIPPTHREAD EQUAL 1) if (NOT SKIPPYTHON EQUAL 1) @@ -786,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/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index 5f1780086..816a1c754 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/cmdhfmfu.c b/client/src/cmdhfmfu.c index 0ff39cef9..fc918c4d5 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) @@ -7851,6 +7852,371 @@ int CmdHF14MfuNDEFWrite(const char *Cmd) { PrintAndLogEx(NORMAL, ""); return PM3_SUCCESS; } + +// 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; + 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[] = { + { 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) { + 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 CmdHF14MfuNDEFFormat(const char *Cmd) { + + CLIParserContext *ctx; + 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" + "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.", + "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[] = { + 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 ndefformat -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) { + + // -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]); + 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: 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; + 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 + } + } + + // 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)); + } + + // 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; + } + + 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, ""); + + // 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"); + 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"); + // 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"); + 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) { @@ -8722,6 +9088,7 @@ static command_t CommandTable[] = { {"dump", CmdHF14AMfUDump, IfPm3Iso14443a, "Dump MIFARE Ultralight family tag to binary file"}, {"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"}, diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h index 1eb49488b..e55982c57 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 CmdHF14MfuNDEFFormat(const char *Cmd); // used by cmdnfc.c int CmdHF14MfUTamper(const char *Cmd); #define MFU_TT_UNKNOWN 0x0ULL diff --git a/client/src/cmdhw.c b/client/src/cmdhw.c index a30c6dd22..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; @@ -2288,11 +2364,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; @@ -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/client/src/cmdnfc.c b/client/src/cmdnfc.c index 67dfa2720..8aa531ace 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 CmdHF14MfuNDEFFormat(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") " ---------------------"}, diff --git a/doc/mfu_ndef_format_notes.md b/doc/mfu_ndef_format_notes.md new file mode 100644 index 000000000..8f18917e1 --- /dev/null +++ b/doc/mfu_ndef_format_notes.md @@ -0,0 +1,74 @@ +# Notes on `hf mfu ndefformat` + + +# Table of Contents +- [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) + - [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 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. + +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 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. + +## 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. diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index bfcc87e24..7b522d5ee 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -874,12 +874,12 @@ 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_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 // 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`. 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/tools/kgh/README.md b/tools/kgh/README.md new file mode 100644 index 000000000..d3fff500e --- /dev/null +++ b/tools/kgh/README.md @@ -0,0 +1,71 @@ +# legic_kgh_tool + +## Running + +`legic_kgh_tool` reads KGH LEGIC card information, badge numbers, and stamps, +and writes the supported KGH card layout. + +Examples: + +```bash +./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: + +- `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 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` 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. + +## Building in ProxSpace (for Windows) + +Do this in ProxSpace: + +```bash +cd ~/proxmark3/tools/kgh +rm -rf build-lite +cmake -G "MSYS Makefiles" -S . -B build-lite \ + -DSKIPPYTHON=1 \ + -DSKIPREADLINE=1 \ + -DSKIPJANSSONSYSTEM=1 \ + -DSKIPWHEREAMISYSTEM=1 \ + -DSKIPBT=1 +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 tools/kgh +rm -rf build-linux +cmake -S . -B build-linux \ + -DSKIPPYTHON=1 \ + -DSKIPREADLINE=1 \ + -DSKIPJANSSONSYSTEM=1 \ + -DSKIPWHEREAMISYSTEM=1 \ + -DSKIPBT=1 +cmake --build build-linux --target legic_kgh_tool -j +ldd build-linux/legic_kgh_tool +``` + +## Static Link Notes + +- `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. diff --git a/tools/kgh/legic_kgh_tool.c b/tools/kgh/legic_kgh_tool.c new file mode 100644 index 000000000..429eea54a --- /dev/null +++ b/tools/kgh/legic_kgh_tool.c @@ -0,0 +1,659 @@ +//----------------------------------------------------------------------------- +// 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 +#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 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) { + *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 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"; + } + + uint16_t dcf = ((uint16_t)dump[6] << 8) | dump[5]; + if (dcf == 0xFFFF) { + return "NM"; + } + + if (dcf > 60000u) { + return "IAM"; + } + + if (is_kgh_card(dump, len)) { + 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]; + bool is_last = ((dump[start + 1] & 0x08) != 0); + if (seg_len < 5 || start + seg_len > len) { + break; + } + + if (saw_first) { + return true; + } + + saw_first = true; + if (is_last) { + 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 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 ? "" : ","); +} + +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 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; +} + +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 read_stamp [-o|--output-file ]\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], "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 (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; + } 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; + } + } else { + fprintf(stderr, "not a supported KGH card\n"); + } + 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"); + } 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; +}