diff --git a/CHANGELOG.md b/CHANGELOG.md index 013d969ff..d7ff24941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed PM5 tick-count reads across RTC second rollovers to prevent false receive timeouts +- Added `lf cotag sim` - simulate COTAG tag (@towelbyte) +- Added standalone mode `GDB_GATEWAY` (PM5): GDB Remote Serial Protocol server on the USB CDC link, flash and SRAM access, no probe needed (@nieldk) - Fixed weak fc/2 PSK tags (Indala, NexWatch, IDTECK, ...) misreading or failing: when the wave tracker has errors, the PSK demod falls back to `pm3_psk_demod` (@mfcarroll) - Fixed `lf t55xx detect -p` - the password is no longer sent to a tag whose PWD bit could not be confirmed, which could set it and destroy the tag's data; pass `-o` to override (@mfcarroll) - Fixed `hf mf hardnested`/`hf mf autopwn` on PM5 with hardened MIFARE Classic EV1 (#3595, #3664) (@ByteOrderMarc) @@ -293,7 +296,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Add support for parsing Finnish Helsinki Regional Transport (HRT) travel cards (@sanduuz) - Added standalone mode `HF_DOEGOX_COMMIT` - DESFire suspended commit without relay (@doegox) - Changed `hf 14b info`- now support Innovatron protocol detection (@kormax) -- Improved `lf cotag reader` and `lf cotag demod` - Reimplementation and enhancement of proxmark3 COTAG support +- Improved `lf cotag reader` and `lf cotag demod` - Reimplementation and enhancement of proxmark3 COTAG support (@towelbyte) - Added `hf felica sim` command (@kormax) - Added `mad read`, `mad write`, `mad verify`, `mad decode`, `mad encode` commands with typed struct MAD API (@AlxCzl) - Added `hf mfdes getversion` command (@kormax) diff --git a/Makefile.platform.sample b/Makefile.platform.sample index d912ce9d6..7fd7f22fa 100644 --- a/Makefile.platform.sample +++ b/Makefile.platform.sample @@ -24,6 +24,7 @@ PLATFORM=PM3RDV4 #PLATFORM_EXTRAS=BWM #PLATFORM_EXTRAS=NO_LOWBATT_SHUTDOWN #PLATFORM_EXTRAS=NO_LOWBATT_BEEP +#STANDALONE=GDB_GATEWAY # If you want more than one PLATFORM_EXTRAS option, separate them by spaces: #PLATFORM_EXTRAS=BTADDON diff --git a/armsrc/Standalone/Makefile.hal b/armsrc/Standalone/Makefile.hal index 906f68cc9..ca279d8d8 100644 --- a/armsrc/Standalone/Makefile.hal +++ b/armsrc/Standalone/Makefile.hal @@ -149,13 +149,16 @@ define KNOWN_STANDALONE_DEFINITIONS | DANKARMULTI | Load multiple standalone modes. | | | - Daniel Karling | +-----------------------------------------------------------+ +| GDB_GATEWAY | Read-only GDB server over USB CDC | +| | (PM5) | ++-----------------------------------------------------------+ endef STANDALONE_MODES := LF_SKELETON STANDALONE_MODES += LF_EM4100EMUL LF_EM4100RSWB LF_EM4100RSWW LF_EM4100RWC LF_HIDBRUTE LF_HIDFCBRUTE LF_ICEHID LF_MULTIHID LF_NEDAP_SIM LF_NEXID LF_PROXBRUTE LF_PROX2BRUTE LF_SAMYRUN LF_THAREXDE STANDALONE_MODES += HF_14ASNIFF HF_14BSNIFF HF_15SIM HF_15SNIFF HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_EMVPNG HF_ICECLASS HF_LEGIC HF_LEGIC_RDV4 HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG -STANDALONE_MODES += DANKARMULTI +STANDALONE_MODES += DANKARMULTI GDB_GATEWAY STANDALONE_MODES_REQ_BT := HF_CARDHOPPER HF_REBLAY STANDALONE_MODES_REQ_SMARTCARD := STANDALONE_MODES_REQ_FLASH := LF_HIDFCBRUTE LF_ICEHID LF_NEXID LF_THAREXDE HF_BOG HF_COLIN HF_ICECLASS HF_LEGIC_RDV4 HF_LEGICSIM HF_MFCSIM HF_ST25_TEAROFF diff --git a/armsrc/Standalone/Makefile.inc b/armsrc/Standalone/Makefile.inc index 5c05371d8..422fe878d 100644 --- a/armsrc/Standalone/Makefile.inc +++ b/armsrc/Standalone/Makefile.inc @@ -89,6 +89,10 @@ endif ifneq (,$(findstring WITH_STANDALONE_HF_15SNIFF,$(APP_CFLAGS))) SRC_STANDALONE = hf_15sniff.c endif +# WITH_STANDALONE_GDB_GATEWAY +ifneq (,$(findstring WITH_STANDALONE_GDB_GATEWAY,$(APP_CFLAGS))) + SRC_STANDALONE = gdb_gateway.c +endif # WITH_STANDALONE_HF_15SIM ifneq (,$(findstring WITH_STANDALONE_HF_15SIM,$(APP_CFLAGS))) SRC_STANDALONE = hf_15sim.c diff --git a/armsrc/Standalone/StandAloneOption.cmake b/armsrc/Standalone/StandAloneOption.cmake index 70823139b..3850465b8 100644 --- a/armsrc/Standalone/StandAloneOption.cmake +++ b/armsrc/Standalone/StandAloneOption.cmake @@ -118,6 +118,9 @@ | HF_EMVPNG | Read and emulate EMV Visa cards | | | - Davi Mikael (Penegui) | +----------------------------------------------------------+ +| GDB_GATEWAY | Read-only GDB server over USB CDC | +| | (PM5) | ++----------------------------------------------------------+ ]] # Default standalone if no standalone specified @@ -137,7 +140,7 @@ set(STANDALONE_MODES HF_14ASNIFF HF_14BSNIFF HF_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_ICECLASS HF_LEGIC HF_LEGIC_RDV4 HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY - HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG DANKARMULTI) + HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG DANKARMULTI GDB_GATEWAY) # List of modes that require bluetooth set(STANDALONE_MODES_REQ_BT HF_CARDHOPPER HF_REBLAY) # List of modes that require smartcard diff --git a/armsrc/Standalone/StandAloneSource.cmake b/armsrc/Standalone/StandAloneSource.cmake index 48ad195ef..b7fd420a4 100644 --- a/armsrc/Standalone/StandAloneSource.cmake +++ b/armsrc/Standalone/StandAloneSource.cmake @@ -76,6 +76,10 @@ if ("${APP_CFLAGS}" MATCHES "WITH_STANDALONE_HF_15SNIFF") set(SRC_STANDALONE "${DIR_STANDALONE}/hf_15sniff.c") endif () +if ("${APP_CFLAGS}" MATCHES "WITH_STANDALONE_GDB_GATEWAY") + set(SRC_STANDALONE "${DIR_STANDALONE}/gdb_gateway.c") +endif () + if ("${APP_CFLAGS}" MATCHES "WITH_STANDALONE_HF_15SIM") set(SRC_STANDALONE "${DIR_STANDALONE}/hf_15sim.c") endif () diff --git a/armsrc/Standalone/gdb_gateway.c b/armsrc/Standalone/gdb_gateway.c new file mode 100644 index 000000000..1d1b8e7a9 --- /dev/null +++ b/armsrc/Standalone/gdb_gateway.c @@ -0,0 +1,552 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- +// Standalone GDB gateway: GDB Remote Serial Protocol over the USB CDC link. +// Reads flash and SRAM, writes SRAM and flash (gdb 'load'), no execution control. +// Flash writes are limited to the space above the running image; the bootrom is +// never writable. 'monitor unlock-app' opens the app area, 'monitor lock' closes it. +// Start with 'hw standalone', quit the client, then: +// arm-none-eabi-gdb -ex 'target remote /dev/ttyACM0' +// Leave with 'monitor exit' or a button press. +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +#define GDB_PKT_MAX 0x400u // advertised PacketSize +#define GDB_MEM_MAX ((GDB_PKT_MAX - 8u) / 2u) +#define GDB_NREGS 17u // r0-r12, sp, lr, pc, xpsr + +#define GW_FLASH_BASE 0x08000000u +#define GW_FLASH_SIZE 0x00100000u +#define GW_APP_BASE 0x08004000u // bootrom below this is never writable +#define GW_SECTOR 0x800u // 1 MB part: 2 KB sectors +#define GW_SRAM_BASE 0x20000000u +#define GW_SRAM_SIZE 0x00080000u // 512K, set by Extend_SRAM() in the bootrom + +typedef struct { + void (*tx)(const uint8_t *data, size_t len); + // Copy up to len bytes from addr; return bytes copied, 0 if addr is unreadable. + size_t (*mem_read)(uint32_t addr, uint8_t *out, size_t len); + // The engine checks the address window before calling these. + bool (*ram_write)(uint32_t addr, const uint8_t *data, size_t len); + bool (*flash_erase)(uint32_t sector_addr); + bool (*flash_write)(uint32_t addr, const uint8_t *data, size_t len); + uint32_t app_end; // first sector above the running image +} gdb_ops_t; + +static const gdb_ops_t *s_ops; + +static const char TARGET_XML[] = + "" + "" + "" + "armv7e-m" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; + +static const char MEMORY_MAP_XML[] = + "" + "" + "" + "" + "0x800" + "" + ""; + +static const char HEXD[] = "0123456789abcdef"; + +typedef enum { ST_IDLE, ST_DATA, ST_CS1, ST_CS2 } rx_state_t; + +static rx_state_t s_state; +static uint8_t s_rx[GDB_PKT_MAX + 1]; +static uint16_t s_rxlen; +static uint8_t s_sum; +static int s_cs_hi; +static bool s_ovf; +static bool s_ack_pending; +static bool s_exit; +static bool s_unlocked; // app area writable + +static uint8_t s_out[GDB_PKT_MAX]; // reply payload +static uint8_t s_frame[GDB_PKT_MAX + 5]; // '+' '$' payload '#' cs cs +static uint16_t s_frame_len; +static uint16_t s_frame_off; // start of the resendable part (after any ack) + +static int hexval(uint8_t c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static bool parse_hex(const char **p, const char *end, uint32_t *v) { + uint32_t r = 0; + int n = 0; + while (*p < end && hexval((uint8_t) * *p) >= 0) { + if (n++ >= 8) return false; + r = (r << 4) | (uint32_t)hexval((uint8_t) * *p); + (*p)++; + } + *v = r; + return n > 0; +} + +static bool starts_with(const char *s, size_t len, const char *pre) { + size_t n = strlen(pre); + return len >= n && memcmp(s, pre, n) == 0; +} + +static void send_payload(const uint8_t *pl, size_t len) { + size_t j = 0; + uint8_t cs = 0; + if (len > GDB_PKT_MAX) len = GDB_PKT_MAX; + if (s_ack_pending) { + s_frame[j++] = '+'; + s_ack_pending = false; + } + s_frame_off = (uint16_t)j; + s_frame[j++] = '$'; + for (size_t i = 0; i < len; i++) { + s_frame[j++] = pl[i]; + cs = (uint8_t)(cs + pl[i]); + } + s_frame[j++] = '#'; + s_frame[j++] = (uint8_t)HEXD[cs >> 4]; + s_frame[j++] = (uint8_t)HEXD[cs & 0xF]; + s_frame_len = (uint16_t)j; + s_ops->tx(s_frame, j); +} + +static void send_str(const char *s) { + send_payload((const uint8_t *)s, strlen(s)); +} + +static void send_err(uint8_t e) { + char b[4] = { 'E', HEXD[e >> 4], HEXD[e & 0xF], 0 }; + send_str(b); +} + +static bool flash_window_ok(uint32_t addr, uint32_t len) { + uint32_t floor = s_unlocked ? GW_APP_BASE : s_ops->app_end; + uint32_t end = addr + len; + return len && addr >= floor && end > addr && end <= GW_FLASH_BASE + GW_FLASH_SIZE; +} + +static bool sram_ok(uint32_t addr, uint32_t len) { + uint32_t end = addr + len; + return len && addr >= GW_SRAM_BASE && end > addr && end <= GW_SRAM_BASE + GW_SRAM_SIZE; +} + +// Undo gdb binary escaping ('}' then byte ^ 0x20). Returns -1 on a dangling '}'. +static int unescape(const uint8_t *in, size_t n, uint8_t *out) { + size_t o = 0; + for (size_t i = 0; i < n; i++) { + if (in[i] == '}') { + if (++i >= n) return -1; + out[o++] = in[i] ^ 0x20; + } else { + out[o++] = in[i]; + } + } + return (int)o; +} + +// Serve a qXfer document slice for "OFF,LEN". +static void send_qxfer(const char *doc, const char *p, const char *end) { + uint32_t off, len; + if (!parse_hex(&p, end, &off) || p >= end || *p++ != ',' || !parse_hex(&p, end, &len)) { + send_err(0x16); + return; + } + size_t total = strlen(doc); + if (off >= total) { + send_str("l"); + return; + } + size_t n = total - off; + if (n > len) n = len; + if (n > GDB_PKT_MAX - 1u) n = GDB_PKT_MAX - 1u; + s_out[0] = (off + n < total) ? 'm' : 'l'; + memcpy(&s_out[1], doc + off, n); + send_payload(s_out, n + 1); +} + +static void do_mem_read(const char *p, const char *end) { + uint32_t addr, len; + if (!parse_hex(&p, end, &addr) || p >= end || *p++ != ',' || !parse_hex(&p, end, &len)) { + send_err(0x16); + return; + } + if (len > GDB_MEM_MAX) len = GDB_MEM_MAX; + uint8_t tmp[GDB_MEM_MAX]; + size_t n = len ? s_ops->mem_read(addr, tmp, len) : 0; + if (len && n == 0) { + send_err(0x14); // EFAULT + return; + } + for (size_t i = 0; i < n; i++) { + s_out[2 * i] = (uint8_t)HEXD[tmp[i] >> 4]; + s_out[2 * i + 1] = (uint8_t)HEXD[tmp[i] & 0xF]; + } + send_payload(s_out, 2 * n); +} + +static void do_mem_write(const char *p, const char *end) { + uint32_t addr, len; + if (!parse_hex(&p, end, &addr) || p >= end || *p++ != ',' || !parse_hex(&p, end, &len) || + p >= end || *p++ != ':' || len > GDB_MEM_MAX || (size_t)(end - p) != 2 * (size_t)len) { + send_err(0x16); + return; + } + if (len == 0) { + send_str("OK"); + return; + } + uint8_t tmp[GDB_MEM_MAX]; + for (uint32_t i = 0; i < len; i++) { + int hi = hexval((uint8_t)p[2 * i]), lo = hexval((uint8_t)p[2 * i + 1]); + if (hi < 0 || lo < 0) { + send_err(0x16); + return; + } + tmp[i] = (uint8_t)((hi << 4) | lo); + } + if (!sram_ok(addr, len)) { + send_err(0x02); // flash goes through vFlashWrite + return; + } + send_str(s_ops->ram_write(addr, tmp, len) ? "OK" : "E01"); +} + +static void do_vflash(const char *s, size_t len) { + const char *end = s + len; + uint32_t addr, n; + if (starts_with(s, len, "vFlashErase:")) { + const char *p = s + strlen("vFlashErase:"); + if (!parse_hex(&p, end, &addr) || p >= end || *p++ != ',' || !parse_hex(&p, end, &n) || + n == 0 || (addr % GW_SECTOR) || (n % GW_SECTOR)) { + send_err(0x16); + return; + } + if (!flash_window_ok(addr, n)) { + send_err(0x02); + return; + } + for (uint32_t a = addr; a < addr + n; a += GW_SECTOR) { + if (!s_ops->flash_erase(a)) { + send_err(0x01); + return; + } + } + send_str("OK"); + } else if (starts_with(s, len, "vFlashWrite:")) { + const char *p = s + strlen("vFlashWrite:"); + if (!parse_hex(&p, end, &addr) || p >= end || *p++ != ':') { + send_err(0x16); + return; + } + uint8_t data[GDB_PKT_MAX]; + int dn = unescape((const uint8_t *)p, (size_t)(end - p), data); + if (dn < 0) { + send_err(0x16); + return; + } + if (!flash_window_ok(addr, (uint32_t)dn)) { + send_err(0x02); + return; + } + send_str(dn == 0 || s_ops->flash_write(addr, data, (size_t)dn) ? "OK" : "E01"); + } else if (starts_with(s, len, "vFlashDone")) { + send_str("OK"); + } else { + send_str(""); + } +} + +// monitor : reply is the hex-encoded console text. +static void do_monitor(const char *p, const char *end) { + char cmd[24] = {0}; + size_t n = 0; + while (p + 1 < end && n < sizeof(cmd) - 1) { + int hi = hexval((uint8_t)p[0]), lo = hexval((uint8_t)p[1]); + if (hi < 0 || lo < 0) break; + cmd[n++] = (char)((hi << 4) | lo); + p += 2; + } + const char *txt; + if (strcmp(cmd, "unlock-app") == 0) { + s_unlocked = true; + txt = "app area writable; erasing the running image crashes the PM5\n"; + } else if (strcmp(cmd, "lock") == 0) { + s_unlocked = false; + txt = "writes limited to flash above the running image\n"; + } else if (strcmp(cmd, "exit") == 0) { + s_exit = true; + txt = "leaving gdb gateway\n"; + } else if (strcmp(cmd, "info") == 0) { + txt = s_unlocked ? "flash 0x08000000+1M sram 0x20000000+512K app-write on\n" + : "flash 0x08000000+1M sram 0x20000000+512K app-write off\n"; + } else if (strcmp(cmd, "help") == 0) { + txt = "monitor info | unlock-app | lock | exit\n"; + } else { + txt = "unknown command\n"; + } + size_t t = strlen(txt); + for (size_t i = 0; i < t; i++) { + s_out[2 * i] = (uint8_t)HEXD[(uint8_t)txt[i] >> 4]; + s_out[2 * i + 1] = (uint8_t)HEXD[(uint8_t)txt[i] & 0xF]; + } + send_payload(s_out, 2 * t); +} + +static void do_query(const char *s, size_t len) { + const char *end = s + len; + if (starts_with(s, len, "qSupported")) { + send_str("PacketSize=400;qXfer:features:read+;qXfer:memory-map:read+"); + } else if (starts_with(s, len, "qXfer:features:read:target.xml:")) { + send_qxfer(TARGET_XML, s + strlen("qXfer:features:read:target.xml:"), end); + } else if (starts_with(s, len, "qXfer:memory-map:read::")) { + send_qxfer(MEMORY_MAP_XML, s + strlen("qXfer:memory-map:read::"), end); + } else if (starts_with(s, len, "qRcmd,")) { + do_monitor(s + 6, end); + } else if (starts_with(s, len, "qAttached")) { + send_str("1"); + } else if (starts_with(s, len, "qfThreadInfo")) { + send_str("m1"); + } else if (starts_with(s, len, "qsThreadInfo")) { + send_str("l"); + } else if (len == 2 && starts_with(s, len, "qC")) { + send_str("QC1"); + } else { + send_str(""); + } +} + +static void handle_packet(const char *s, size_t len) { + if (len == 0) { + send_str(""); + return; + } + switch (s[0]) { + case '?': + case 'c': case 'C': case 's': case 'S': // no execution control + send_str("S05"); + break; + case 'g': // registers are not available + memset(s_out, '0', GDB_NREGS * 8); + send_payload(s_out, GDB_NREGS * 8); + break; + case 'p': + memset(s_out, '0', 8); + send_payload(s_out, 8); + break; + case 'H': case 'T': case 'D': + send_str("OK"); + break; + case 'm': + do_mem_read(s + 1, s + len); + break; + case 'M': + do_mem_write(s + 1, s + len); + break; + case 'G': case 'P': // registers are read-only + send_err(0x01); + break; + case 'v': + do_vflash(s, len); + break; + case 'q': + do_query(s, len); + break; + default: // X, Z, z, unknown + send_str(""); + break; + } +} + +static void gdb_reset(const gdb_ops_t *ops) { + s_ops = ops; + s_state = ST_IDLE; + s_rxlen = 0; + s_ack_pending = false; + s_exit = false; + s_unlocked = false; + s_frame_len = 0; + s_frame_off = 0; +} + +static void gdb_feed(uint8_t b) { + switch (s_state) { + case ST_IDLE: + if (b == '$') { + s_rxlen = 0; + s_sum = 0; + s_ovf = false; + s_state = ST_DATA; + } else if (b == '-' && s_frame_len) { + s_ops->tx(s_frame + s_frame_off, s_frame_len - s_frame_off); // resend + } else if (b == 0x03) { + send_str("S05"); // Ctrl-C, nothing to stop + } + break; + case ST_DATA: + if (b == '#') { + s_state = ST_CS1; + } else if (b == '$') { + s_rxlen = 0; + s_sum = 0; + s_ovf = false; + } else { + if (s_rxlen < GDB_PKT_MAX) s_rx[s_rxlen++] = b; + else s_ovf = true; + s_sum = (uint8_t)(s_sum + b); + } + break; + case ST_CS1: + s_cs_hi = hexval(b); + s_state = ST_CS2; + break; + case ST_CS2: { + int lo = hexval(b); + s_state = ST_IDLE; + if (s_ovf || s_cs_hi < 0 || lo < 0 || (uint8_t)((s_cs_hi << 4) | lo) != s_sum) { + s_ops->tx((const uint8_t *)"-", 1); + } else { + s_ack_pending = true; + s_rx[s_rxlen] = 0; + handle_packet((const char *)s_rx, s_rxlen); + if (s_ack_pending) { // handler sent no reply + s_ops->tx((const uint8_t *)"+", 1); + s_ack_pending = false; + } + } + break; + } + } +} + +#ifndef GDB_GATEWAY_HOST_TEST + +#include "appmain.h" +#include "dbprint.h" +#include "proxmark3_arm.h" +#include "standalone.h" +#include "ticks_apis.h" +#include "util.h" +#include "usb_cdc_apis.h" +#include "usb_read_ng.h" +#include "at32f435_437_flash.h" + +extern const char __os_size__[]; // linker: size of the OS image + +static void usb_tx(const uint8_t *data, size_t len) { + usb_write(data, len); +} + +static size_t at32_mem_read(uint32_t addr, uint8_t *out, size_t len) { + uint32_t end; + if (addr - GW_FLASH_BASE < GW_FLASH_SIZE) { + end = GW_FLASH_BASE + GW_FLASH_SIZE; + } else if (addr - GW_SRAM_BASE < GW_SRAM_SIZE) { + end = GW_SRAM_BASE + GW_SRAM_SIZE; + } else { + return 0; + } + if (len > end - addr) len = end - addr; + for (size_t i = 0; i < len; i++) { + out[i] = *(const volatile uint8_t *)(addr + i); + } + return len; +} + +static bool at32_ram_write(uint32_t addr, const uint8_t *data, size_t len) { + for (size_t i = 0; i < len; i++) { + *(volatile uint8_t *)(addr + i) = data[i]; + } + return true; +} + +static bool at32_flash_erase(uint32_t addr) { + WDT_HIT(); + flash_unlock(); + flash_status_type st = flash_sector_erase(addr); + flash_lock(); + return st == FLASH_OPERATE_DONE; +} + +// Words are merged with the current flash content, so partial words work +// on erased sectors. Read back to verify. +static bool at32_flash_write(uint32_t addr, const uint8_t *data, size_t len) { + bool ok = true; + uint32_t end = addr + (uint32_t)len; + flash_unlock(); + for (uint32_t w = addr & ~3u; w < end && ok; w += 4) { + uint32_t v = *(volatile uint32_t *)w; + for (uint32_t i = 0; i < 4; i++) { + if (w + i >= addr && w + i < end) { + v = (v & ~(0xFFu << (8 * i))) | ((uint32_t)data[w + i - addr] << (8 * i)); + } + } + if (v != *(volatile uint32_t *)w) { + ok = flash_word_program(w, v) == FLASH_OPERATE_DONE && *(volatile uint32_t *)w == v; + } + } + flash_lock(); + WDT_HIT(); + return ok; +} + +static gdb_ops_t s_at32_ops = { usb_tx, at32_mem_read, at32_ram_write, at32_flash_erase, at32_flash_write, 0 }; + +void ModInfo(void) { + DbpString(" GDB gateway, RSP over USB CDC"); +} + +// No Dbprintf here: debug frames would corrupt the RSP stream. +void RunMod(void) { + s_at32_ops.app_end = (GW_APP_BASE + (uint32_t)(uintptr_t)__os_size__ + GW_SECTOR - 1) & ~(GW_SECTOR - 1); + gdb_reset(&s_at32_ops); + LED_A_ON(); + while (!s_exit && !BUTTON_PRESS()) { + WDT_HIT(); + while (usb_read_ng_has_buffered_data() || usb_poll_validate_length()) { + uint8_t b; + if (usb_read_ng(&b, 1) != 1) break; + gdb_feed(b); + } + } + LED_A_OFF(); + while (BUTTON_PRESS()) { // keep the main loop from reading the press as power-off + WDT_HIT(); + SpinDelay(10); + } +} + +#endif // GDB_GATEWAY_HOST_TEST diff --git a/armsrc/Standalone/readme.md b/armsrc/Standalone/readme.md index e85c06cc7..178938f5f 100644 --- a/armsrc/Standalone/readme.md +++ b/armsrc/Standalone/readme.md @@ -81,6 +81,7 @@ As such the information inside may be false or hallucinated. | Mode ID | Document | Description | |---------|----------|-------------| | DANKARMULTI | [Dankarmulti Loader](../../doc/standalone/dankarmulti.md) | Combine multiple standalone modes into one firmware image | +| GDB_GATEWAY | [GDB Gateway](../../doc/standalone/gdb_gateway.md) | Read-only GDB server over USB CDC | PM5 | # Developing Standalone Modes This contains functionality for different StandAlone modes. The fullimage will be built given the correct compiler flags used. Build targets for these files are contained in `Makefile.inc` and `Makefile.hal` diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 09f06dbec..67e69c371 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1865,6 +1865,11 @@ static void PacketReceived(PacketCommandNG *packet) { Cotag(payload->mode, true); break; } + case CMD_LF_COTAG_SIMULATE: { + SimulateCotag((const lf_cotagsim_t *)packet->data.asBytes, true); + reply_ng(CMD_LF_COTAG_SIMULATE, PM3_EOPABORTED, NULL, 0); + break; + } #endif #ifdef WITH_HITAG diff --git a/armsrc/lfops.c b/armsrc/lfops.c index f06142b4f..016d91f91 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -2980,6 +2980,243 @@ void Cotag(uint32_t arg0, bool ledcontrol) { if (ledcontrol) LEDsoff(); } +#define COTAG_STEP_K 32 // samples per box of the step filter + +// a detected activation, for debug output +typedef struct { + uint32_t dt; // samples between the two rises + int32_t thr; // threshold the second rise crossed +} cotag_detect_val_t; + +// Block until the reader's activation sequence is detected. Return false on button press or USB data. +static bool cotag_activation_sequence_detect(const lf_cotagsim_t *params, cotag_detect_val_t *out) { + + // Reader's tag activation sequence: + // - ON 800 us, OFF 2200 us + // - ON ~5800 us (the tag is expected to respond in this window) + // - OFF ~16500 us (reader's pause if no tag detected, then repeat) + // + // We detect 2 rising edges between ON(800),OFF(2200),ON(5800), i.e. approx 3000us apart. + // Plus minus some tolerance, thus win_lo and win_hi. + + // Number of samples between 2 rising edges to look for an activation sequence + const uint32_t win_lo = (3000 - 300) * 12 / (LF_COTAG_DIVISOR + 1); + const uint32_t win_hi = (3000 + 300) * 12 / (LF_COTAG_DIVISOR + 1); + + // Samples ring buffer + uint8_t ring[2 * COTAG_STEP_K] = {0}; + uint8_t idx = 0; // points to the oldest sample + int32_t sum_new = 0, sum_old = 0; // sum of the newest (oldest) COTAG_STEP_K samples + + int32_t peak_recent_step = 0; // peak of step, scaled by 65536 so the decay below cannot truncate to zero + uint32_t sample_cnt = 0; + uint32_t last_rise = 0; // sample_cnt at the previous detected rising edge + bool armed = true; + uint16_t checked = 0; + + for (;;) { + WDT_HIT(); + + if (++checked >= 4000) { + checked = 0; + if (BUTTON_PRESS() || data_available()) { + return false; + } + } + + if (FPGA_SSC_RX_Ready() == false) { + continue; + } + + uint8_t sample = FPGA_SSC_RX_Value(); + + // Recalculate sum_new and sum_old. + // sample (new) added to sum_new; mid subtracted from sum_new and added to sum_old, + // ring[idx] (oldest) subtracted from sum_old and discarded. + uint8_t mid = ring[(idx + COTAG_STEP_K) % (2 * COTAG_STEP_K)]; + sum_new += sample - mid; + sum_old += mid - ring[idx]; + ring[idx] = sample; + idx = (idx + 1) % (2 * COTAG_STEP_K); + + if (++sample_cnt < 2 * COTAG_STEP_K) { + continue; // wait for the ring buffer to fill up first + } + + // Step filter + int32_t step = sum_new - sum_old; + if (step * 65536 > peak_recent_step) { + peak_recent_step = step * 65536; // attack at once + } else { + peak_recent_step -= peak_recent_step >> 13; // release slowly, tau 2^13 samples + } + + // use threshold as half the recent peak step (adapting to reader distance) + // (undo scaling by 65536 aka 2^16, then divide by 2: thus >> 17) + int32_t thr = MAX(params->thr_floor, peak_recent_step >> 17); + + // Rising edge detection: Schmitt trigger so that we get one event per rise: + // trigger once when step >= thr, then disarm, only re-arm if step falls below thr/4 + if (armed && step >= thr) { + armed = false; + uint32_t dt = sample_cnt - last_rise; // number of samples since the previous rise + + if (last_rise && dt >= win_lo && dt <= win_hi) { + // Activation sequence detected + out->dt = dt; + out->thr = thr; + return true; + } + last_rise = sample_cnt; + + } else if (step <= thr / 4) { + // step enough below the thr, re-arm Schmitt trigger + armed = true; + } + } +} + +#define COTAG_TX_HALFBIT_CYCLES (384 / 2) // Number of samples per half bit +#define COTAG_TX_SYNC_HALFBITS 4 // two leading sync 0 bits +#define COTAG_TX_MAX_HALFBITS (COTAG_TX_SYNC_HALFBITS + 2 * 8 * LF_COTAG_SIM_DATA_LEN) + +#define COTAG_SSC_STALL 100000 +#define COTAG_SETTLE_US 10000 + +// Discard count samples ("wait count samples"). Return false on error. +static bool cotag_skip_samples(uint32_t count) { + while (count--) { + uint32_t guard = 0; + while (FPGA_SSC_RX_Ready() == false) { + if (++guard > COTAG_SSC_STALL) { + return false; + } + } + (void)FPGA_SSC_RX_Value(); + } + return true; +} + +static uint16_t cotag_build_halfbits(uint8_t *half_bits, const uint8_t *data, uint8_t nbits) { + + // Two leading/sync 0 bits, manchester encoded + half_bits[0] = 0; + half_bits[1] = 1; + half_bits[2] = 0; + half_bits[3] = 1; + + uint16_t nhb = COTAG_TX_SYNC_HALFBITS; + for (uint8_t i = 0; i < nbits; i++) { + // bits in reverse order: + uint8_t src = nbits - 1 - i; + uint8_t bit = (data[src >> 3] >> (7 - (src & 7))) & 1; + // manchester encode the bit: + half_bits[nhb++] = bit; + half_bits[nhb++] = bit ^ 1; + } + return nhb; +} + +// Send COTAG frame's half bits. Return false on button press, USB data, or error. +static bool cotag_tx_frame(const uint8_t *half_bits, uint16_t nhb, uint8_t repeats, uint16_t hb_delay_us) { + + Gpio_SSC_DOUT_High(); + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_COTAG_TX_DIVISOR); + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); + + bool ok = true; + for (uint8_t r = 0; r < repeats && ok; r++) { + // Send precomputed half bits. Leading sync bits are sent only at first repetition + for (uint16_t i = (r == 0) ? 0 : COTAG_TX_SYNC_HALFBITS; i < nhb; i++) { + if (half_bits[i]) { + Gpio_SSC_DOUT_Low(); + } else { + Gpio_SSC_DOUT_High(); + } + + if (hb_delay_us) { + SpinDelayUsPrecision(hb_delay_us); + } else if (cotag_skip_samples(COTAG_TX_HALFBIT_CYCLES) == false) { + ok = false; + break; + } + + if (BUTTON_PRESS()) { + ok = false; + break; + } + } + + WDT_HIT(); + if (data_available()) { + ok = false; + break; + } + } + + Gpio_SSC_DOUT_High(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC); + Gpio_SSC_DOUT_Low(); // back to "listening" + return ok; +} + +void SimulateCotag(const lf_cotagsim_t *params, bool ledcontrol) { + + LFSetupFPGAForADC(LF_COTAG_DIVISOR, false); + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC); + gpio_fpga_mod_only_setup(); + Gpio_SSC_DOUT_Low(); + + BigBuf_free(); + BigBuf_Clear_ext(false); + + uint8_t *half_bits = BigBuf_calloc(COTAG_TX_MAX_HALFBITS); + if (half_bits == NULL) { + if (g_dbglevel >= DBG_ERROR) DbpString("SimulateCotag: failed to allocate buffer"); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + return; + } + + uint8_t nbits = MIN(params->nbits, 8 * LF_COTAG_SIM_DATA_LEN); + + // Precompute the Manchester halfbits to send + uint16_t nhb = cotag_build_halfbits(half_bits, params->data, nbits); + + const uint32_t settle = COTAG_SETTLE_US * 12 / (LF_COTAG_DIVISOR + 1); + + cotag_detect_val_t val; + + while (cotag_activation_sequence_detect(params, &val)) { + if (nbits) { + if (ledcontrol) LED_C_ON(); + + // Transmit frame + bool ok = cotag_tx_frame(half_bits, nhb, params->repeats, params->hb_delay_us); + + if (ledcontrol) LED_C_OFF(); + + if (ok == false) { + break; + } + + // Done transmitting. Back to our RX sampling divisor: + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_COTAG_DIVISOR); + + cotag_skip_samples(settle); + } + + // Debug print only after done TXing frame + if (params->verbose || nbits == 0) { + Dbprintf("COTAG reader activation sequence detected (rise-to-rise " _YELLOW_("%u") " us, threshold %d)", + val.dt * (LF_COTAG_DIVISOR + 1) / 12, val.thr); + } + } + + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + if (ledcontrol) LEDsoff(); + BigBuf_free(); +} + /* * EM4305 support */ diff --git a/armsrc/lfops.h b/armsrc/lfops.h index 6e34c7b00..e8472846a 100644 --- a/armsrc/lfops.h +++ b/armsrc/lfops.h @@ -79,6 +79,7 @@ void EM4xProtectWord(uint32_t data, uint32_t pwd, uint8_t usepwd, bool ledcontro void cotag_start_pulse(void); void Cotag(uint32_t arg0, bool ledcontrol); +void SimulateCotag(const lf_cotagsim_t *params, bool ledcontrol); void setT55xxConfig(uint8_t persist, const t55xx_configurations_t *c); t55xx_configurations_t *getT55xxConfig(void); void printT55xxConfig(void); diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c index 1983d402a..991fb22bf 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -387,6 +387,12 @@ bool cep_spi_data_available(void) { } s_last_spi_activity_tick = GetTickCount(); // FAP is still polling, valid frame or not uint16_t data_len = (len_header[1] << 8) | len_header[0]; + if (data_len == 0xFFFF) { + // FAP's reply-poll drives 0xFF dummy bytes when it has nothing to + // send (furi_hal_spi_bus_trx with a NULL tx buffer) - not a desync, + // same treatment as a CEP_SYNC_BYTE run, no resync needed. + return false; + } if (data_len > PM3_CMD_DATA_SIZE * 2) { // Same reasoning: an implausible length is itself evidence of a // desynced read, not just "no frame yet." diff --git a/client/pyscripts/niimbot_tag_patcher.py b/client/pyscripts/niimbot_tag_patcher.py new file mode 100644 index 000000000..92e3fb21c --- /dev/null +++ b/client/pyscripts/niimbot_tag_patcher.py @@ -0,0 +1,625 @@ +#!/usr/bin/env python3 +# Licensed at MIT license + +# Tool to analyze and patch Niimbot label printers RFID tags or clone them into other tags. +# Tag contents (NTAG) are encrypted are contain a security record computed from card UUID, +# therefore cloning a card contents to another one will not work and such tag will be rejected by a printer. + +# You need a Proxmark3 card dump in PM3 bin or json file. Patching will modify this dump so you need to +# upload it again to a card. + +# Note that Niimbot mobile app keeps copy of those values on their servers so resetting the tag print counter +# may not work in the long term. + + +# Usage: + +# python3 niimbot_tag_patcher.py --help +# python3 niimbot_tag_patcher.py analyze -i tag-dump.json -f pm3-json + +# Patch the print counter, set it back to 0 and write the file to patched.json +# (format of the pached file is always the same as input file) + +# python3 niimtag.py patch -i tag-dump.json -f pm3-json --print-counter 0 -w patched.json + + +# (C) 2026 PhaseLoop + +import argparse +import binascii +import json +from ctypes import c_uint32 as uint32 +from dataclasses import dataclass, field +from struct import pack, unpack +from typing import Self + +CRYPTO_KEY = bytes( + [ + 0xA1, + 0xCC, + 0x00, + 0x00, + 0xB7, + 0x72, + 0x00, + 0x00, + 0x58, + 0x67, + 0x00, + 0x00, + 0xC9, + 0x65, + 0x00, + 0x00, + ] +) + +# from Proxmark3 bin dump file format +PM3_MFU_DUMP_PREFIX_LENGTH = 56 + +# Tag research and structures based on open research here: +# https://printers.niim.blue/other/rfig-tags/ +# security check value at 0x08 presented there is computed wrong + + +# tea_decrypt and tea_encrypt shamelessly stolen from +# https://github.com/devsli/tea_cipher/tree/master +# licensed as MIT license. +# Modified to unpack/pack integers as little endian to match +# ARM architecture in printers + + +def tea_decrypt(ciphertext, key, delta=0x9E3779B9): + """ + Decrypt a ciphertext using TEA algorithm. + + ciphertext: 64 bits length bytes-like object. + key: 128 bits length bytes-like object. + + Return a 64 bits length bytes object. + """ + + v0, v1 = map(uint32, unpack("<2I", ciphertext)) + k0, k1, k2, k3 = map(uint32, unpack("<4I", key)) + sm, delta = uint32(0xC6EF3720), uint32(delta) + + for i in range(32): + v1.value -= ( + ((v0.value << 4) + k2.value) + ^ (v0.value + sm.value) + ^ ((v0.value >> 5) + k3.value) + ) + v0.value -= ( + ((v1.value << 4) + k0.value) + ^ (v1.value + sm.value) + ^ ((v1.value >> 5) + k1.value) + ) + sm.value -= delta.value + + return pack("<2I", v0.value, v1.value) + + +def tea_encrypt(plaintext, key, delta=0x9E3779B9): + """ + Encrypt a plaintext using TEA algorithm. + + plaintext: 64 bits length bytes-like object. + key: 128 bits length bytes-like object. + + Return a 64 bits length bytes object. + """ + + v0, v1 = map(uint32, unpack("<2I", plaintext)) + k0, k1, k2, k3 = map(uint32, unpack("<4I", key)) + sm, delta = uint32(0), uint32(delta) + + for i in range(32): + sm.value += delta.value + v0.value += ( + ((v1.value << 4) + k0.value) + ^ (v1.value + sm.value) + ^ ((v1.value >> 5) + k1.value) + ) + v1.value += ( + ((v0.value << 4) + k2.value) + ^ (v0.value + sm.value) + ^ ((v0.value >> 5) + k3.value) + ) + + return pack("<2I", v0.value, v1.value) + + +class CardLoadError(Exception): ... + + +class LabelValueError(Exception): ... + + +class CLIError(Exception): ... + + +@dataclass +class LabelTag: + + PRINT_COUNTER_OFFSET = 0x02 # 16 bit LE + PRINT_COUNTER_CRC32_OFFSET = 0x04 + LABEL_SECURITY_RECORD_OFFSET = 0x08 + LABEL_SECURITY_RECORD_LENGTH = 7 + + VENDOR_DATA_OFFSET = 0x14 + VENDOR_DATA_LENGTH = 0x78 + + SERIAL_OFFSET = 0x10 + SERIAL_FIELD_SIZE = 16 + + BARCODE_OFFSET = 0x28 + BARCODE_FIELD_SIZE = 13 + + NAME_OFFSET = 0x46 + NAME_FIELD_SIZE = 20 + + PAPER_WIDTH_OFFSET = 0x5A + PAPER_HEIGHT_OFFSET = 0x5B + PRINT_LIMIT_OFFSET = 0x5C + + card_data: bytearray = field( + default_factory=bytearray + ) # full NTAG card data, starting from sector 0 + encrypted_data: bytearray = field( + default_factory=bytearray + ) # encrypted data, sectors 5-34 + vendor_data: bytearray = field( + default_factory=bytearray + ) # decrypted data from sectors 5-34 + + def field_to_uint8(self, offset) -> int: + return unpack( + " None: + assert 0 <= value <= 255, "value must be between 0 and 255" + + field_value = pack(" None: + field_value = pack(" str: + text = "" + + for i in range(max_size): + char_byte = self.vendor_data[offset + i] + if char_byte == 0x00: # end of string + break + else: + text += bytes([char_byte]).decode("utf-8") + return text + + def text_to_field(self, offset: int, max_size: int, value: str) -> None: + encoded_text = value.encode("utf-8") + # cut text to match max_size - 1 byte to keep \0 termination + encoded_text = bytes(encoded_text[0 : max_size - 1]) + + # zeroed buffer is filled with encoded text minus one so string is always terminated with \0 + # it will probably break unicode if it gets cut in the middle of a 16/32 bit value + buffer = bytearray(max_size) + buffer[0 : len(encoded_text)] = encoded_text + + self.vendor_data[offset:offset+max_size] = buffer + + @property + def barcode(self) -> str: + barcode_text = "" + for i in range(self.BARCODE_FIELD_SIZE): + char_byte = self.vendor_data[self.BARCODE_OFFSET + i] + if char_byte == 0x00: # end of string + break + else: + barcode_text += bytes([char_byte]).decode("utf-8") + + return barcode_text + + @property + def name(self) -> str: + return self.field_to_text(self.NAME_OFFSET, self.NAME_FIELD_SIZE) + + @name.setter + def name(self, value) -> None: + self.text_to_field(self.NAME_OFFSET, self.NAME_FIELD_SIZE, value) + + @property + def paper_width(self) -> int: + return self.field_to_uint8(self.PAPER_WIDTH_OFFSET) + + @paper_width.setter + def paper_width(self, value: int) -> None: + self.uint8_to_field(self.PAPER_WIDTH_OFFSET, value) + + @property + def paper_height(self) -> int: + return self.field_to_uint8(self.PAPER_HEIGHT_OFFSET) + + @paper_height.setter + def paper_height(self, value: int) -> None: + self.uint8_to_field(self.PAPER_HEIGHT_OFFSET, value) + + @property + def print_counter(self) -> int: + print_count = unpack( + " int: + print_counter_crc32 = unpack( + " int: + print_limit = unpack( + " bytes: + # reencrypt card data using current "vendor_data" buffer which may have been + # modified by us + + buffer = bytearray() + + # encrypt self.vendor_data in 8 byte increments (because that's how TEA works) + for vendor_block in ( + self.vendor_data[pos : pos + 8] + for pos in range(0, len(self.encrypted_data), 8) + ): + buffer += bytearray(tea_encrypt(vendor_block, CRYPTO_KEY)) + + assert len(buffer) == len( + self.vendor_data + ), f"Internal error - vendor data len {len(buffer)} != ciphertext len ({len(self.vendor_data)})" + + return bytes(buffer) + + @property + def security_record(self) -> bytes: + return bytes( + self.vendor_data[ + self.LABEL_SECURITY_RECORD_OFFSET : self.LABEL_SECURITY_RECORD_OFFSET + + self.LABEL_SECURITY_RECORD_LENGTH + ] + ) + + @security_record.setter + def security_record(self, value: bytes) -> None: + assert len(value) == self.LABEL_SECURITY_RECORD_LENGTH + self.vendor_data[ + self.LABEL_SECURITY_RECORD_OFFSET : self.LABEL_SECURITY_RECORD_OFFSET + + self.LABEL_SECURITY_RECORD_LENGTH + ] = bytearray(value) + + @property + def serial(self) -> str: + return self.field_to_text(self.SERIAL_OFFSET, self.SERIAL_FIELD_SIZE) + + @property + def uuid(self) -> str: + return bytes(self.card_data[0:8]).hex().upper() + + def compute_security_record(self, card_uuid: bytes | None = None) -> bytes: + # note that UUID byte with index 3 is skipped + + record_uuid = card_uuid or bytes(self.card_data[0:7]) + + return bytes( + [ + 0x88, + record_uuid[0], + record_uuid[1], + record_uuid[2], + record_uuid[4], + record_uuid[5], + record_uuid[6], + ] + ) + + def compute_print_counter_crc32(self) -> int: + data = self.vendor_data[ + 0:4 + ] # CRC32 is computed over first 4 bytes of a card - unknown field and a 16 bit print counter + return binascii.crc32(data) + + def process_card_data(self): + # copy vendor data to encrypted_data array + self.encrypted_data = self.card_data[ + self.VENDOR_DATA_OFFSET : self.VENDOR_DATA_OFFSET + self.VENDOR_DATA_LENGTH + ] + + # decrypt encrypted_data into vendor_data in 8 byte increments (because that's how TEA works) + for encrypted_block in ( + self.encrypted_data[pos : pos + 8] + for pos in range(0, len(self.encrypted_data), 8) + ): + self.vendor_data += bytearray(tea_decrypt(encrypted_block, CRYPTO_KEY)) + + assert len(self.vendor_data) == len( + self.encrypted_data + ), "Internal error - vendor data len != ciphertext len" + + @classmethod + def validate_pm3json_dump(cls, dump: dict): + if not "Created" in dump and not "blocks" in dump: + raise CardLoadError( + "File does not look like Proxmark3-compatible json dump" + ) + + if dump.get("FileType") != "mfu": + raise CardLoadError("File is not an mfu card dump") + + if not isinstance(dump["blocks"], dict): + raise CardLoadError( + "'blocks' object in file is not a list, probably wrong file format" + ) + + if len(dump["blocks"]) < int( + (cls.VENDOR_DATA_LENGTH + cls.VENDOR_DATA_OFFSET) / 4 + ): + raise CardLoadError( + "card dump does not look like Niimbot RFID card - size too small" + ) + + @classmethod + def from_pm3json(cls, input: str) -> Self: + dump = json.loads(input) + cls.validate_pm3json_dump(dump) + tag = cls() + + for block_num in range(35): + block_hex = dump["blocks"].get(f"{block_num}") + + if block_hex is None: + raise CardLoadError(f"No block {block_num} found in loaded card dump") + + block = bytes.fromhex(block_hex) + tag.card_data += bytearray(block) + + tag.process_card_data() + return tag + + def patch_pm3json(self, input: str) -> str: + # we can't really generate PM3 dump from scratch so we just load the same dump + # and replace vendor sectors with updated ones + dump = json.loads(input) + self.validate_pm3json_dump(dump) + + start_block = int(self.VENDOR_DATA_OFFSET / 4) + number_of_blocks = int(self.VENDOR_DATA_LENGTH / 4) + + encrypted_data = self.reencrypted_data + + for block_num in range(start_block, start_block + number_of_blocks): + # beginning of encrypted data is block 5 in a card dump so when accessing it by block_num we need to offset that + new_block = bytes(encrypted_data[(block_num-start_block) * 4 : ((block_num-start_block) * 4) + 4]).hex().upper() + dump["blocks"][str(block_num)] = new_block + + return json.dumps(dump, indent=2) + + @classmethod + def from_pm3bin(cls, input: bytes) -> Self: + + if len(input) < PM3_MFU_DUMP_PREFIX_LENGTH + ( + cls.VENDOR_DATA_LENGTH + cls.VENDOR_DATA_OFFSET + ): + raise CardLoadError( + "card dump does not look like Niimbot RFID card - size too small" + ) + + tag = cls() + tag.card_data = bytearray(input[PM3_MFU_DUMP_PREFIX_LENGTH:]) + tag.process_card_data() + return tag + + +def load_tag(args: argparse.Namespace) -> LabelTag: + open_mode = "r" + + if args.file_format == "pm3-bin": + open_mode += "b" + + tag_contents = None + + with open(args.input_file, open_mode) as tag_file: + tag_contents = tag_file.read() + + if args.file_format == "pm3-json": + return LabelTag.from_pm3json(tag_contents) + elif args.file_format == "pm3-bin": + return LabelTag.from_pm3bin(tag_contents) + else: + raise CLIError("Unknown file format specified") + + +def save_tag(args: argparse.Namespace, tag: LabelTag) -> None: + open_mode_read = "r" + open_mode_write = "w" + + if args.file_format == "pm3-bin": + open_mode_read += "b" + open_mode_write += "b" + + with open(args.input_file, open_mode_read) as input_tag_file: + tag_contents = input_tag_file.read() + + if args.file_format == "pm3-json": + patched_tag = tag.patch_pm3json(tag_contents) + elif args.file_format == "pm3-bin": + raise CLIError("bin not yet supported for patching") + else: + raise CLIError("Unknown file format specified") + + with open(args.write_file, open_mode_write) as output_tag_file: + output_tag_file.write(patched_tag) + + +def tag_analyze(args: argparse.Namespace) -> None: + + tag = load_tag(args) + + print("==== Decoded RFID tag contents: ====") + print(f"Card UUID: {tag.uuid}") + print(f"Tag name: {tag.name}") + print(f"Label print counter: {tag.print_counter}") + print(f"Label paper width: {tag.paper_width}") + print(f"Label paper width: {tag.paper_height}") + print(f"Label print limit: {tag.print_limit}") + print(f"Label serial number: {tag.serial}") + print(f"Label barcode: {tag.barcode}") + + print() + + if tag.compute_security_record() == tag.security_record: + print("Security record value valid") + else: + print("Security record value INVALID") + + print( + f"Security record field value computed for current card UUID: {tag.compute_security_record().hex()}" + ) + print(f"Security record field retrieved from dump: {tag.security_record.hex()}") + + if tag.compute_print_counter_crc32() == tag.print_counter_crc32: + print("Print counter CRC32 checksum valid") + else: + print("Print counter CRC32 checksum INVALID") + + +def tag_patch(args: argparse.Namespace) -> None: + + if not args.write_file: + raise CLIError("You need specify a file to write the patched RFID dump.") + + tag = load_tag(args) + + if args.name is not None: + tag.name = args.name + + if args.width is not None: + if args.width < 0 or args.width > 255: + raise LabelValueError("Paper width must be between 0 and 255 mm") + tag.paper_width = args.width + + if args.height is not None: + if args.height < 0 or args.height > 255: + raise LabelValueError("Paper height must be between 0 and 255 mm") + tag.paper_heigth = args.height + + if args.print_counter is not None: + tag.print_counter = args.print_counter + tag.print_counter_crc32 = tag.compute_print_counter_crc32() + + if args.fix_security_record: + card_uuid = bytes.fromhex(args.uuid) if args.uuid else None + tag.security_record = tag.compute_security_record(card_uuid=card_uuid) + + save_tag(args, tag) + + +def main(): + parser = argparse.ArgumentParser( + prog="ProgramName", description="Analyze and patch Niimbot label RFID chips" + ) + + parser.add_argument( + "-i", "--input-file", help="RFID dump file to read", required=True + ) + parser.add_argument( + "-f", + "--file-format", + help="RFID dump file format", + choices=["pm3-json", "pm3-bin"], + required=True, + ) + parser.add_argument( + "-w", "--write-file", help="RFID dump file to write (same format as input)" + ) + + parser.add_argument("--name", "--name", help="set roll name") + + parser.add_argument("--width", "--width", help="set paper width (in mm)", type=int) + + parser.add_argument( + "--height", "--height", help="set paper height (in mm)", type=int + ) + + parser.add_argument( + "--print-counter", + "--print-counter", + help="set label print counter (counter of already printed labels) <0, 255>", + type=int, + ) + + parser.add_argument( + "--print-limit", + "--print-limit", + help="set label print limit <0, 255>", + type=int, + ) + + parser.add_argument( + "--fix-security-record", + "--fix-security-record", + help="fix security record to match card UUID", + action='store_true', + ) + parser.add_argument( + "--uuid", + "--uuid", + help="use this card UUID instead of one in dump file to calculate security check", + type=str, + ) + + parser.add_argument( + "command", help="Command to execute", choices=["analyze", "patch"] + ) + + args = parser.parse_args() + if args.command == "analyze": + return tag_analyze(args) + elif args.command == "patch": + return tag_patch(args) + else: + print(f"Unknown command: {args.command}") + + +if __name__ == "__main__": + main() diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 5d0925370..0638d888c 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9680,7 +9680,7 @@ static int gdm_write_config(uint8_t wakeup, uint8_t auth_cmd, const uint8_t *key } if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write config. Status: %d", resp.status); - return PM3_EFAILED; + return resp.status; } return PM3_SUCCESS; } @@ -10052,10 +10052,12 @@ static int CmdHF14AGen4_GDM_SetCfg(const char *Cmd) { if (resp.status == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Write ( " _GREEN_("ok") " )"); PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mf gdmgetcfg") "` to verify"); + } else if (resp.status == PM3_ETEAROFF) { + PrintAndLogEx(INFO, "Tear off triggered"); } else { PrintAndLogEx(FAILED, "Write ( " _RED_("fail") " )"); } - return PM3_SUCCESS; + return resp.status; } // Config flag mode @@ -10128,8 +10130,9 @@ static int CmdHF14AGen4_GDM_SetCfg(const char *Cmd) { } // Step 2: Write config - if (gdm_write_config(wakeup_type, auth_cmd, key, config) != PM3_SUCCESS) { - return PM3_EFAILED; + int res = gdm_write_config(wakeup_type, auth_cmd, key, config); + if (res != PM3_SUCCESS) { + return res; } PrintAndLogEx(SUCCESS, "Config updated successfully"); @@ -10234,7 +10237,7 @@ static int CmdHF14AGen4_GDM_SetBlk(const char *Cmd) { } else { PrintAndLogEx(FAILED, "Write ( " _RED_("fail") " )"); } - return PM3_SUCCESS; + return resp.status; } static int CmdHF14AGen4_GDM_SetHidBlk(const char *Cmd) { @@ -10379,7 +10382,7 @@ static int CmdHF14AGen4_GDM_SetHidBlk(const char *Cmd) { } else { PrintAndLogEx(FAILED, "Write ( " _RED_("fail") " )"); } - return PM3_SUCCESS; + return resp.status; } // Shared worker for gdmgetblk / gdmgethidblk: reads a single block (--blk) or a @@ -10631,8 +10634,9 @@ static int CmdHF14AGen4_GDM_SetUid(const char *Cmd) { // Step 3: Write config if needed if (update_config) { - if (gdm_write_config(wakeup_type, auth_cmd, key, config) != PM3_SUCCESS) { - return PM3_EFAILED; + int res = gdm_write_config(wakeup_type, auth_cmd, key, config); + if (res != PM3_SUCCESS) { + return res; } PrintAndLogEx(SUCCESS, "Config updated successfully"); } @@ -10647,7 +10651,7 @@ static int CmdHF14AGen4_GDM_SetUid(const char *Cmd) { } if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write hidden block 0. Status: %d", resp.status); - return PM3_EFAILED; + return resp.status; } PrintAndLogEx(SUCCESS, "Hidden block 0 updated successfully"); } @@ -10661,18 +10665,73 @@ static int CmdHF14AGen4_GDM_SetUid(const char *Cmd) { } if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write real block %d. Status: %d", write_payload.block_no, resp.status); - return PM3_EFAILED; + return resp.status; } PrintAndLogEx(SUCCESS, "Real block %d updated successfully", write_payload.block_no); return PM3_SUCCESS; } +static int gdm_wipe_write_block(const gdm_wakeup_t *w, uint8_t write_cmd, uint8_t block_no, const uint8_t *data) { + mf_writeblock_ex_t payload = { + .wakeup = w->wakeup_type, + .auth_cmd = w->auth_cmd, + .write_cmd = write_cmd, + .block_no = block_no + }; + memcpy(payload.key, w->key, sizeof(payload.key)); + memcpy(payload.block_data, data, sizeof(payload.block_data)); + + clearCommandBuffer(); + SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&payload, sizeof(payload)); + + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false) { + PrintAndLogEx(FAILED, "Block %u write timed out", block_no); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Block %u write failed. Status: %d", block_no, resp.status); + return resp.status; + } + return PM3_SUCCESS; +} + +static int gdm_wipe_verify_uid(const uint8_t *expected_uid) { + clearCommandBuffer(); + SendIso14aReader(ISO14A_CONNECT | ISO14A_CLEARTRACE | ISO14A_NO_DISCONNECT, NULL, 0); + + PacketResponseNG resp; + uint8_t select_status = 0; + if (WaitForIso14aReply(&resp, 2500, NULL, &select_status) == false) { + DropField(); + PrintAndLogEx(FAILED, "Could not select the card after writing the clean config"); + return PM3_ETIMEOUT; + } + + iso14a_card_select_t card; + memcpy(&card, resp.data.asBytes, sizeof(card)); + DropField(); + + if (select_status == 0 || card.uidlen != 4 || memcmp(card.uid, expected_uid, 4) != 0) { + PrintAndLogEx(FAILED, "Clean UID verification failed"); + if (select_status != 0) { + PrintAndLogEx(INFO, "Expected UID: %s", sprint_hex(expected_uid, 4)); + PrintAndLogEx(INFO, "Selected UID: %s", sprint_hex(card.uid, card.uidlen)); + } + return PM3_EFAILED; + } + + PrintAndLogEx(SUCCESS, "Selected clean UID: %s", sprint_hex(card.uid, card.uidlen)); + return PM3_SUCCESS; +} + static int CmdHF14AGen4_GDM_Wipe(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mf gdmwipe", - "Wipe a GDM card to factory defaults.\n" - "With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", + "Wipe a GDM card to a known clean 4-byte template.\n" + "Sets UID to 11223344, clears real and hidden data blocks, and sets sector trailers to default values.\n" + "With no wakeup flag it auto-detects a backdoor; a WUPA-only card is rejected.", "hf mf gdmwipe --gdm" ); void *argtable[] = { @@ -10706,51 +10765,49 @@ static int CmdHF14AGen4_GDM_Wipe(const char *Cmd) { if (wres != PM3_SUCCESS) { return wres; } + if (gw.wakeup_type == MF_WAKE_WUPA) { + PrintAndLogEx(WARNING, "hf mf gdmwipe needs a gen1a/gdm backdoor; WUPA magic auth is insufficient"); + PrintAndLogEx(HINT, "Hint: enable one first: " _YELLOW_("hf mf gdmsetcfg --wakestyle gen1a --wupa -k ")); + return PM3_EFAILED; + } uint8_t wakeup_type = gw.wakeup_type; uint8_t auth_cmd = gw.auth_cmd; memcpy(key, gw.key, sizeof(key)); - // Step 1: Write Config (gen1a + wupa + 4B UID) - uint8_t standard_config[MFBLOCK_SIZE] = {0x7A, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0x00, 0x00, 0x00, 0x08}; + uint8_t clean_config[MFBLOCK_SIZE] = {0x7A, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0x00, 0x00, 0x00, 0x08}; uint8_t cur_config[MFBLOCK_SIZE] = {0}; - if (gdm_read_config(wakeup_type, auth_cmd, key, cur_config) == PM3_SUCCESS) { - standard_config[2] = cur_config[2]; + if (gdm_read_config(wakeup_type, auth_cmd, key, cur_config) != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Cannot preserve the current wakeup style; no data was changed"); + return PM3_EFAILED; + } + if (cur_config[2] == 0x00 || cur_config[2] == 0x85) { + clean_config[2] = cur_config[2]; } else { - PrintAndLogEx(WARNING, "Could not read current config, keeping the default wakeup style"); + clean_config[2] = (wakeup_type == MF_WAKE_GDM_ALT) ? 0x85 : 0x00; + PrintAndLogEx(WARNING, "Unknown wakeup style %02X; using %s", cur_config[2], + clean_config[2] == 0x85 ? "gdm alt (20/23)" : "gen1a (40/43)"); } - mf_writeblock_ex_t config_payload = { - .wakeup = wakeup_type, - .auth_cmd = auth_cmd, - .write_cmd = MIFARE_MAGIC_GDM_WRITE_CFG, // 0xE1 - .block_no = 0 - }; - memcpy(config_payload.key, key, 6); - memcpy(config_payload.block_data, standard_config, MFBLOCK_SIZE); - - clearCommandBuffer(); - SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&config_payload, sizeof(config_payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "Failed to write standard config. Status: %d", resp.status); - } else { - PrintAndLogEx(SUCCESS, "Standard config written"); - } - - // Step 2: Wipe sectors int max_sector = wipe_4k ? 40 : 16; uint8_t default_data[MFBLOCK_SIZE] = {0}; - uint8_t default_trailer[MFBLOCK_SIZE] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - uint8_t block0_data[MFBLOCK_SIZE] = {0xDE, 0x77, 0x15, 0xB8, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - - mf_writeblock_ex_t write_payload = { - .wakeup = wakeup_type, - .auth_cmd = auth_cmd - }; - memcpy(write_payload.key, key, 6); + uint8_t default_trailer[MFBLOCK_SIZE] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + uint8_t block0_data[MFBLOCK_SIZE] = {0x11, 0x22, 0x33, 0x44, 0x44, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; int failed_blocks = 0; int total_blocks = 0; + uint8_t verify_data[MFBLOCK_SIZE] = {0}; + + // Stage a valid 4-byte UID before changing the active UID source. + if (gdm_wipe_write_block(&gw, ISO14443A_CMD_WRITEBLOCK, 0, block0_data) != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Could not stage the clean block 0; config was not changed"); + return PM3_EFAILED; + } + if (gdm_try_read(ISO14443A_CMD_READBLOCK, 0, &gw, verify_data) != PM3_SUCCESS || + memcmp(verify_data, block0_data, MFBLOCK_SIZE) != 0) { + PrintAndLogEx(FAILED, "Clean block 0 readback failed; config was not changed"); + return PM3_EPARTIAL; + } + total_blocks++; for (int sec = 0; sec < max_sector; sec++) { int first_blk = mfFirstBlockOfSector(sec); @@ -10761,49 +10818,56 @@ static int CmdHF14AGen4_GDM_Wipe(const char *Cmd) { bool is_trailer = (blk == trailer_blk); uint8_t *data_to_write = is_trailer ? default_trailer : default_data; - // Real block writes - write_payload.write_cmd = ISO14443A_CMD_WRITEBLOCK; // 0xA0 - write_payload.block_no = blk; - if (blk == 0) { - memcpy(write_payload.block_data, block0_data, MFBLOCK_SIZE); - } else { - memcpy(write_payload.block_data, data_to_write, MFBLOCK_SIZE); + if (blk != 0) { + if (gdm_wipe_write_block(&gw, ISO14443A_CMD_WRITEBLOCK, blk, data_to_write) != PM3_SUCCESS) { + failed_blocks++; + } + total_blocks++; } - clearCommandBuffer(); - SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&write_payload, sizeof(write_payload)); - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { - failed_blocks++; + // Hidden blocks 0 and 1 can still hold the active 7-byte/F3 UID. + if (blk > 1) { + const uint8_t *hidden_data = (blk == 7) ? MF_SIGNATURE_KEYS : data_to_write; + if (gdm_wipe_write_block(&gw, MIFARE_MAGIC_GDM_WRITEBLOCK, blk, hidden_data) != PM3_SUCCESS) { + failed_blocks++; + } + total_blocks++; } - - // Hidden block writes - write_payload.write_cmd = MIFARE_MAGIC_GDM_WRITEBLOCK; // 0xA8 - if (blk == 7) { - memcpy(write_payload.block_data, MF_SIGNATURE_KEYS, MFBLOCK_SIZE); - } - - clearCommandBuffer(); - SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&write_payload, sizeof(write_payload)); - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { - failed_blocks++; - } - total_blocks += 2; } PrintAndLogEx(INFO, "Wiping sector %d...", sec); } - // report write failures instead of always printing "Wipe completed!" - if (failed_blocks == 0) { - PrintAndLogEx(SUCCESS, "Wipe completed!"); - return PM3_SUCCESS; + if (failed_blocks != 0) { + PrintAndLogEx(FAILED, "Wipe incomplete - " _RED_("%d") " of %d pre-commit block writes failed", failed_blocks, total_blocks); + PrintAndLogEx(HINT, "Hint: config and active UID mode were left unchanged"); + return PM3_EPARTIAL; } - PrintAndLogEx(FAILED, "Wipe incomplete - " _RED_("%d") " of %d block writes failed", failed_blocks, total_blocks); - if (failed_blocks == total_blocks) { - PrintAndLogEx(HINT, "Hint: the card did not accept any data write. Check that the wakeup still matches"); - PrintAndLogEx(HINT, " the card's config (`" _YELLOW_("hf mf gdmgetcfg") "`), then retry"); + // Commit the 4-byte personality only after its UID source is valid. + if (gdm_write_config(wakeup_type, auth_cmd, key, clean_config) != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Clean config was not committed; the card was partially wiped"); + return PM3_EPARTIAL; } - return PM3_EFAILED; + PrintAndLogEx(SUCCESS, "Clean config written"); + + if (gdm_wipe_verify_uid(block0_data) != PM3_SUCCESS) { + PrintAndLogEx(HINT, "Hint: the magic wakeup remains enabled for recovery"); + return PM3_EPARTIAL; + } + + // The clean 4-byte personality no longer uses hidden UID data. + for (uint8_t blk = 0; blk <= 1; blk++) { + if (gdm_wipe_write_block(&gw, MIFARE_MAGIC_GDM_WRITEBLOCK, blk, default_data) != PM3_SUCCESS) { + failed_blocks++; + } + } + if (failed_blocks != 0) { + PrintAndLogEx(FAILED, "Clean 4-byte mode is active, but hidden UID cleanup failed"); + return PM3_EPARTIAL; + } + + PrintAndLogEx(SUCCESS, "Wipe completed using the clean 4-byte template"); + return PM3_SUCCESS; } static int CmdHF14AGen4_GDM_SetSig(const char *Cmd) { @@ -10867,9 +10931,13 @@ static int CmdHF14AGen4_GDM_SetSig(const char *Cmd) { clearCommandBuffer(); SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&write_payload, sizeof(write_payload)); PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { + if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false) { + PrintAndLogEx(FAILED, "Failed to write signature part 1 (block 5): timeout"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write signature part 1 (block 5). Status: %d", resp.status); - return PM3_EFAILED; + return resp.status; } PrintAndLogEx(SUCCESS, "Signature part 1 written to block 5"); @@ -10879,9 +10947,13 @@ static int CmdHF14AGen4_GDM_SetSig(const char *Cmd) { clearCommandBuffer(); SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&write_payload, sizeof(write_payload)); - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { + if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false) { + PrintAndLogEx(FAILED, "Failed to write signature part 2 (block 6): timeout"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write signature part 2 (block 6). Status: %d", resp.status); - return PM3_EFAILED; + return resp.status; } PrintAndLogEx(SUCCESS, "Signature part 2 written to block 6"); @@ -10893,8 +10965,9 @@ static int CmdHF14AGen4_GDM_SetSig(const char *Cmd) { if (config[13] != 0x5A) { config[13] = 0x5A; - if (gdm_write_config(wakeup_type, auth_cmd, key, config) != PM3_SUCCESS) { - return PM3_EFAILED; + int res = gdm_write_config(wakeup_type, auth_cmd, key, config); + if (res != PM3_SUCCESS) { + return res; } PrintAndLogEx(SUCCESS, "Enabled signature sector in config (config[13] = 0x5A)"); } else { @@ -10913,9 +10986,13 @@ static int CmdHF14AGen4_GDM_SetSig(const char *Cmd) { clearCommandBuffer(); SendCommandNG(CMD_HF_MIFARE_WRITEBL_EX, (uint8_t *)&trailer_payload, sizeof(trailer_payload)); - if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false || resp.status != PM3_SUCCESS) { + if (WaitForResponseTimeout(CMD_HF_MIFARE_WRITEBL_EX, &resp, 1500) == false) { + PrintAndLogEx(FAILED, "Failed to write signature sector trailer (hidden block 7): timeout"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Failed to write signature sector trailer (hidden block 7). Status: %d", resp.status); - return PM3_EFAILED; + return resp.status; } PrintAndLogEx(SUCCESS, "Signature sector trailer written to hidden block 7"); @@ -12345,7 +12422,7 @@ static command_t CommandTable[] = { {"gdmgethidblk", CmdHF14AGen4_GDM_GetHidBlk, IfPm3Iso14443a, "Read hidden block from GDM card"}, {"gdmsethidblk", CmdHF14AGen4_GDM_SetHidBlk, IfPm3Iso14443a, "Write hidden block to GDM card"}, {"gdmsetuid", CmdHF14AGen4_GDM_SetUid, IfPm3Iso14443a, "Set UID on GDM card"}, - {"gdmwipe", CmdHF14AGen4_GDM_Wipe, IfPm3Iso14443a, "Wipe GDM card to factory defaults"}, + {"gdmwipe", CmdHF14AGen4_GDM_Wipe, IfPm3Iso14443a, "Wipe GDM card to a clean template"}, {"gdmsetsig", CmdHF14AGen4_GDM_SetSig, IfPm3Iso14443a, "Set MFC EV1 signature on GDM card"}, {"-----------", CmdHelp, IfPm3Iso14443a, "----------------------- " _CYAN_("ndef") " -----------------------"}, {"ndefformat", CmdHFMFNDEFFormat, IfPm3Iso14443a, "Format MIFARE Classic Tag as NFC Tag"}, diff --git a/client/src/cmdlfcotag.c b/client/src/cmdlfcotag.c index 4b1b25822..0703836ff 100644 --- a/client/src/cmdlfcotag.c +++ b/client/src/cmdlfcotag.c @@ -38,12 +38,15 @@ #define XSTR(x) #x #define STR(x) XSTR(x) -#define LF_COTAG_DIVISOR 90 // 132 kHz #define LF_COTAG_CLOCK 768 #define LF_COTAG_DATA_LEN 128 #define LF_COTAG_DEF_SAMPLES_READ 500000 +#define LF_COTAG_SIM_FLOOR 128 +#define LF_COTAG_SIM_MIN_BYTES 8 +#define LF_COTAG_SIM_MAX_REPEATS 16 + static int CmdHelp(const char *Cmd); static int demod_cotag(int32_t *samples, int num_samples, int clock, int clock_start, double threshold, bool verbose); @@ -540,10 +543,85 @@ static int CmdCOTAGReader(const char *Cmd) { return ret; } +static int CmdCOTAGSim(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf cotag sim", + "Enables simulation of a COTAG tag.\n" + "Simulation runs until the button is pressed or another USB command is issued.\n" + "Without " _YELLOW_("`-r`") _CYAN_(" it only reports detected reader activation sequence.\n") + _CYAN_("Note: COTAG tag full repeating sequence is 128 bits, but readers seem to care about LSB 64 bits only."), + "lf cotag sim --> only detect the reader\n" + "lf cotag sim -r A37E0D37000C1337 --> send 64 bits\n" + "lf cotag sim -r 0000000000000002A37E0D37000C1337\n" + "lf cotag sim --floor 32 --> more sensitive, for a reader further away\n" + "lf cotag sim -r A37E0D37000C1337 --hb_delay_us 2909 --> time the half bit instead of counting cycles\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("r", "raw", "", "raw data to answer with, " STR(LF_COTAG_SIM_MIN_BYTES) " to " STR(LF_COTAG_SIM_DATA_LEN) " bytes (64-128 bits)"), + arg_int0("n", "repeat", "<1-" STR(LF_COTAG_SIM_MAX_REPEATS) ">", "repeat data frame this many times per answer (def 1)"), + arg_int0(NULL, "floor", "<16-65535>", "minimum rise threshold (def " STR(LF_COTAG_SIM_FLOOR) ")"), + arg_int0(NULL, "hb_delay_us", "<2900-2918>", "custom half bit delay [us] (should be around 2909)"), + arg_lit0("v", "verbose", "report detected reader activation sequence while answering"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + uint8_t data[LF_COTAG_SIM_DATA_LEN] = {0}; + int dlen = 0; + CLIGetHexWithReturn(ctx, 1, data, &dlen); + int repeats = arg_get_int_def(ctx, 2, 1); + int thr_floor = arg_get_int_def(ctx, 3, LF_COTAG_SIM_FLOOR); + int hb_delay = arg_get_int_def(ctx, 4, 0); + bool verbose = arg_get_lit(ctx, 5); + CLIParserFree(ctx); + + if (dlen && (dlen < LF_COTAG_SIM_MIN_BYTES || dlen > LF_COTAG_SIM_DATA_LEN)) { + PrintAndLogEx(ERR, "data must be %d to %d bytes (64 to 128 bits), got %d" + , LF_COTAG_SIM_MIN_BYTES, LF_COTAG_SIM_DATA_LEN, dlen); + return PM3_EINVARG; + } + + if (repeats < 1 || repeats > LF_COTAG_SIM_MAX_REPEATS) { + PrintAndLogEx(ERR, "repeat must be between 1 and %d", LF_COTAG_SIM_MAX_REPEATS); + return PM3_EINVARG; + } + + if (thr_floor < 16 || thr_floor > 0xFFFF) { + PrintAndLogEx(ERR, "floor must be between 16 and 65535"); + return PM3_EINVARG; + } + + if (hb_delay && (hb_delay < 2900 || hb_delay > 2918)) { + PrintAndLogEx(ERR, "hb_delay_us must be between 2900 and 2918 us"); + return PM3_EINVARG; + } + + lf_cotagsim_t payload = { + .thr_floor = (uint16_t)thr_floor, + .hb_delay_us = (uint16_t)hb_delay, + .nbits = (uint8_t)(dlen * 8), + .repeats = (uint8_t)repeats, + .verbose = verbose, + }; + memcpy(payload.data, data, dlen); + + PrintAndLogEx(INFO, "Simulating COTAG tag"); + if (dlen == 0) { + PrintAndLogEx(INFO, "No " _YELLOW_("`-r`") " given, detecting reader activation sequence only"); + } + + clearCommandBuffer(); + SendCommandNG(CMD_LF_COTAG_SIMULATE, (uint8_t *)&payload, sizeof(payload)); + return lfsim_wait_check(CMD_LF_COTAG_SIMULATE); +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"demod", CmdCOTAGDemod, AlwaysAvailable, "demodulate a COTAG tag"}, {"reader", CmdCOTAGReader, IfPm3Lf, "attempt to read and extract tag data"}, + {"sim", CmdCOTAGSim, IfPm3Lf, "simulate a COTAG tag"}, {NULL, NULL, NULL, NULL} }; diff --git a/common_arm/ticks/ticks_hw_at32.c b/common_arm/ticks/ticks_hw_at32.c index b3fda5982..6275b4157 100644 --- a/common_arm/ticks/ticks_hw_at32.c +++ b/common_arm/ticks/ticks_hw_at32.c @@ -148,6 +148,8 @@ void StartTickCount(void) { // Get the current count. uint32_t RAMFUNC GetTickCount(void) { ertc_time_type time; + // Read SBS first to latch TIME/DATE until the calendar getter reads DATE. + uint32_t subsecond = ERTC->sbs; ertc_calendar_get(&time); return mktime_utc_fast( // time.year is short length, not full, so 2025 is 25. @@ -156,7 +158,7 @@ uint32_t RAMFUNC GetTickCount(void) { time.month, time.day, time.hour, time.min, time.sec, // this ms is from 0 -> 1000 of second, not timestamp value // ms = ((divb + 1) - subsecond * 1000) / (divb + 1) - (3125 - ertc_sub_second_get()) * 1000 / 3125) - tick_start_val; // current - start = tick + (3125 - subsecond) * 1000 / 3125) - tick_start_val; // current - start = tick } // ------------------------------------------------------------------------- diff --git a/doc/commands.json b/doc/commands.json index c9d10014f..d542b76df 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -6393,7 +6393,7 @@ }, "hf mf gdmwipe": { "command": "hf mf gdmwipe", - "description": "Wipe a GDM card to factory defaults. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", + "description": "Wipe a GDM card to a known clean 4-byte template. Sets UID to 11223344, clears real and hidden data blocks, and sets sector trailers to default values. With no wakeup flag it auto-detects a backdoor; a WUPA-only card is rejected.", "notes": [ "hf mf gdmwipe --gdm" ], @@ -11760,6 +11760,27 @@ ], "usage": "lf cotag reader [-hv@] [-s ] [--divisor <19-255>]" }, + "lf cotag sim": { + "command": "lf cotag sim", + "description": "Enables simulation of a COTAG tag. Simulation runs until the button is pressed or another USB command is issued. Without `-r` it only reports detected reader activation sequence. Note: COTAG tag full repeating sequence is 128 bits, but readers seem to care about LSB 64 bits only.", + "notes": [ + "lf cotag sim -> only detect the reader", + "lf cotag sim -r A37E0D37000C1337 -> send 64 bits", + "lf cotag sim -r 0000000000000002A37E0D37000C1337", + "lf cotag sim --floor 32 -> more sensitive, for a reader further away", + "lf cotag sim -r A37E0D37000C1337 --hb_delay_us 2909 -> time the half bit instead of counting cycles" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-r, --raw raw data to answer with, 8 to 16 bytes (64-128 bits)", + "-n, --repeat <1-16> repeat data frame this many times per answer (def 1)", + "--floor <16-65535> minimum rise threshold (def 128)", + "--hb_delay_us <2900-2918> custom half bit delay [us] (should be around 2909)", + "-v, --verbose report detected reader activation sequence while answering" + ], + "usage": "lf cotag sim [-hv] [-r ] [-n <1-16>] [--floor <16-65535>] [--hb_delay_us <2900-2918>]" + }, "lf destron clone": { "command": "lf destron clone", "description": "clone a Destron tag to a T55x7, Q5/T5555 or EM4305/4469 tag.", @@ -16785,8 +16806,8 @@ } }, "metadata": { - "commands_extracted": 935, + "commands_extracted": 936, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-27T19:09:12+00:00" + "extracted_on": "2026-10-14T15:56:50+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 5fb6c6f9d..2c4e28201 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -698,7 +698,7 @@ Check column "offline" for their availability. |`hf mf gdmgethidblk `|N |`Read hidden block from GDM card` |`hf mf gdmsethidblk `|N |`Write hidden block to GDM card` |`hf mf gdmsetuid `|N |`Set UID on GDM card` -|`hf mf gdmwipe `|N |`Wipe GDM card to factory defaults` +|`hf mf gdmwipe `|N |`Wipe GDM card to a clean template` |`hf mf gdmsetsig `|N |`Set MFC EV1 signature on GDM card` |`hf mf ndefformat `|N |`Format MIFARE Classic Tag as NFC Tag` |`hf mf ndefread `|N |`Read and print NDEF records from card` @@ -1119,6 +1119,7 @@ Check column "offline" for their availability. |`lf cotag help `|Y |`This help` |`lf cotag demod `|Y |`demodulate a COTAG tag` |`lf cotag reader `|N |`attempt to read and extract tag data` +|`lf cotag sim `|N |`simulate a COTAG tag` ### lf destron diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 09a9ee771..76dbe9e55 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -1171,7 +1171,7 @@ Sectors 2-15 | `gdmgethidblk` | Read hidden block | | `gdmsethidblk` | Write a hidden block | | `gdmsetuid` | Set 4-byte / 7-byte UID, or F3 perso (`--f3d`) | -| `gdmwipe` | Restore card to factory defaults (`-a` for 4K) | +| `gdmwipe` | Wipe to a known clean 4-byte template (`-a` for 4K) | | `gdmsetsig` | Write EV1 signature (hidden blocks 5/6), enable sigsec, write default signature key sector | ### libnfc commands diff --git a/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md index f8801f7de..bdf701079 100644 --- a/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md +++ b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md @@ -42,6 +42,9 @@ Build as usual, CEP is available by default. (`SKIP_CEP=1` to remove CEP support - `hf`/`lf` reads in general, same as over USB, once the device's one-time FPGA bitstream step is done (see `Getting_Started_With_PM5.md`) — CEP itself doesn't block RF. +- The link survives idle periods cleanly — the FAP's idle dummy-poll bytes + (`0xFFFF` length header, no data pending) no longer trigger a false SPI + resync. ## What doesn't (yet) @@ -49,6 +52,10 @@ Build as usual, CEP is available by default. (`SKIP_CEP=1` to remove CEP support replies `PM3_EFAILED` with stale cached UID data, even though the same reader succeeds moments later over plain USB against the same tag. Firmware-side, root cause open, out of scope for the CEP transport itself. +- `CMD_MAIN_CHIP_UNIQUEID` intermittently times out on its first attempt + (Hardware Status page, occasionally slow/incomplete on first load), + always recovers on the FAP's retry. PM5 handler and FAP cache both + confirmed clean — likely a transport/timing-layer race, root cause open. --- @@ -70,3 +77,6 @@ Build as usual, CEP is available by default. (`SKIP_CEP=1` to remove CEP support - CEP uses its own reply-routing flag (`g_reply_via_cep`). - SPI bit-order/clock-phase settings are confirmed correct against real Flipper traffic (logic analyzer): MSB-first, mode 0, CS active-low. +- FAP-side: a short fast-poll window after sending a command, and blocking + deep-sleep for the life of the RX thread (fixes unreliable reads on + battery), both merged in the FAP's own repo. diff --git a/doc/standalone/gdb_gateway.md b/doc/standalone/gdb_gateway.md new file mode 100644 index 000000000..ebb296109 --- /dev/null +++ b/doc/standalone/gdb_gateway.md @@ -0,0 +1,61 @@ +# GDB_GATEWAY + +GDB Remote Serial Protocol server on the USB CDC link (PM5). +No probe or extra wiring. Reads flash and SRAM, writes SRAM and flash. No breakpoints, no step. + +## Build + +``` +PLATFORM=PM5 +STANDALONE=GDB_GATEWAY +``` + +## Use + +``` +pm3 --> hw standalone +``` + +Quit the client (the port stays up), then: + +``` +arm-none-eabi-gdb -ex 'target remote /dev/ttyACM0' +(gdb) x/16xw 0x08000000 +(gdb) dump memory flash.bin 0x08000000 0x08100000 +(gdb) monitor info +(gdb) load patch.elf # flash above the running image +(gdb) monitor unlock-app # allow writes to the app area +(gdb) monitor lock +(gdb) monitor exit +``` + +Leave with `monitor exit` or a button press. + +## Readable ranges + +| Range | Size | +|-------|------| +| `0x08000000` | 1 MB flash | +| `0x20000000` | 512 KB SRAM | + +Other addresses return `E14`. Peripheral space is not exposed. + +## Writes + +| Target | Allowed | +|--------|---------| +| SRAM (`M`) | always | +| Flash above the running image (`load`, `vFlashErase`/`vFlashWrite`) | always | +| Flash from `0x08004000` (app area) | after `monitor unlock-app` | +| Bootrom, `0x08000000`-`0x08003fff` | never | + +Refused writes return `E02`. `monitor lock` restores the default; the gateway starts locked. +Erasing the running image crashes the PM5, recover it through the bootrom. + +## Notes + +- Flash is erased in 2 KB sectors. +- Register reads return zeros, the core is not halted. +- `c`/`s` return an immediate stop reply; nothing is executed. +- Debug output is off while running, it would corrupt the RSP stream. +- Set `remotetimeout 60` in gdb for large dumps. diff --git a/fpga/pm5/fpga_pm5_top.v b/fpga/pm5/fpga_pm5_top.v index a3b14e9fb..15aa55df8 100644 --- a/fpga/pm5/fpga_pm5_top.v +++ b/fpga/pm5/fpga_pm5_top.v @@ -1,3 +1,20 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- + + module fpga_top ( input ck_1356meg, input ck_1356meg_b, // B is for close range wiring diff --git a/fpga/pm5/gowin_rpll.v b/fpga/pm5/gowin_rpll.v index 00895111a..e2a4d3d24 100644 --- a/fpga/pm5/gowin_rpll.v +++ b/fpga/pm5/gowin_rpll.v @@ -1,11 +1,18 @@ -//Copyright (C)2014-2023 Gowin Semiconductor Corporation. -//All rights reserved. -//File Title: IP file -//Tool Version: V1.9.9 (64-bit) -//Part Number: GW1N-UV4QN48C6/I5 -//Device: GW1N-4 -//Device Version: D -//Created Time: Mon Jul 6 18:07:08 2026 +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- module Gowin_rPLL (clkout, clkin); diff --git a/fpga/pm5/run.ys b/fpga/pm5/run.ys index fbf60070d..d6e8c423b 100644 --- a/fpga/pm5/run.ys +++ b/fpga/pm5/run.ys @@ -1,11 +1,11 @@ -# 手动综合脚本,等价于 proxmark5_fpga.mk 自动生成的步骤。 -# 在 fpga 目录下运行:yosys -s pm5/run.ys (构建时请用 make pm5) +# Manual synthesis script, equivalent to the steps automatically generated by proxmark5_fpga.mk. +# Run in the fpga directory: yosys -s pm5/run.ys (use make pm5 for building) -# 1. 读取源代码和宏定义 +# 1. Read source code and macro definitions read_verilog -D PM5 -D WITH_TIMODE -D WITH_HF_15 -D WITH_FELICA_PROBE common/define.v common/mux8.v common/clk_divider.v common/lp20khz_1MSa_iir_filter.v common/min_max_tracker.v common/hi_flite.v common/hi_get_trace.v common/hi_iso14443a.v common/hi_reader.v common/hi_simulate.v common/hi_sniffer.v common/lf_edge_detect.v common/lo_adc.v common/lo_edge_detect.v common/lo_passthru.v common/lo_read.v pm5/gowin_rpll.v pm5/fpga_pm5_hf.v pm5/fpga_pm5_lf.v pm5/fpga_pm5_top.v -# 2. 检查并强制指定顶层 +# 2. Check and explicitly specify the top level hierarchy -top fpga_top -# 3. 进行综合 +# 3. Perform synthesis synth_gowin -nolutram -json output.json diff --git a/fpga/requirements.txt b/fpga/requirements.txt new file mode 100644 index 000000000..3c7a36d15 --- /dev/null +++ b/fpga/requirements.txt @@ -0,0 +1,13 @@ +# Python packages the fpga/ scripts import. +# +# fs2bin.py is the only one the build needs, and it normally runs under the +# python bundled in oss-cad-suite, which already ships apycula - so this file +# matters when building with an external interpreter instead. apycula owns the +# .fs bitstream format and its CRC; gowin_devid.py re-derives one of those CRCs +# and fails loudly if the format ever changes, so bump deliberately. +apycula>=0.34 + +# tests/plot_edgedetect.py, the offline plot helper for the edge detect +# testbenches. Not needed to build an image. +numpy +matplotlib diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index b1dbf03de..541d3b857 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -380,6 +380,20 @@ typedef struct { uint8_t data[]; } PACKED lf_hitag_t; +#define LF_COTAG_DIVISOR 90 +#define LF_COTAG_TX_DIVISOR 181 + +// For CMD_LF_COTAG_SIMULATE +#define LF_COTAG_SIM_DATA_LEN 16 // 128 bits, the longest repeating COTAG frame +typedef struct { + uint16_t thr_floor; // minimum rise threshold + uint16_t hb_delay_us; // optional custom half bit delay [us] + uint8_t repeats; // repeat data frame this many times per answer + bool verbose; + uint8_t nbits; // number of data bits + uint8_t data[LF_COTAG_SIM_DATA_LEN]; +} PACKED lf_cotagsim_t; + // For CMD_LF_SNIFF_RAW_ADC and CMD_LF_ACQ_RAW_ADC #define LF_SAMPLES_BITS 30 #define MAX_LF_SAMPLES ((((uint32_t)1u) << LF_SAMPLES_BITS) - 1) @@ -1092,6 +1106,7 @@ typedef struct { #define CMD_LF_VIKING_CLONE 0x0222 #define CMD_LF_T55XX_WAKEUP 0x0224 #define CMD_LF_COTAG_READ 0x0225 +#define CMD_LF_COTAG_SIMULATE 0x022B #define CMD_LF_T55XX_SET_CONFIG 0x0226 #define CMD_LF_SAMPLING_PRINT_CONFIG 0x0227 #define CMD_LF_SAMPLING_GET_CONFIG 0x0228 diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index c3e89457c..36f8a102b 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -298,6 +298,7 @@ while true; do if ! CheckExecute "findbits test" "$PYTHON tools/findbits.py 73 0110010101110011" "Match at bit 9: 011001010"; then break; fi if ! CheckExecute "findbits_test test" "$PYTHON tools/findbits_test.py 2>&1" "OK"; then break; fi if ! CheckExecute "dfc_converter test" "$PYTHON tools/dfc_converter_test.py 2>&1" "OK"; then break; fi + if ! CheckExecute "PM5 RTC tick test" "$PYTHON tools/pm5_rtc_tick_test.py 2>&1" "RTC tick snapshot test: OK"; then break; fi if ! CheckExecute "pm3_eml_mfd test" "$PYTHON tools/mfc/pm3_eml_mfd_test.py 2>&1" "OK"; then break; fi if ! CheckExecute "recover_pk test" "$PYTHON tools/recover_pk.py selftests 2>&1" "Tests:.*\(.*ok.*"; then break; fi if ! CheckExecute "mkversion create test" "tools/mkversion.sh --short" 'Iceman/'; then break; fi diff --git a/tools/pm5_rtc_tick_test.py b/tools/pm5_rtc_tick_test.py new file mode 100644 index 000000000..29b24b1e2 --- /dev/null +++ b/tools/pm5_rtc_tick_test.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +# 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. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +"""Test the actual PM5 tick getter with the AN0047 section 2.4 shadow-lock model.""" + +import argparse +import os +from pathlib import Path +import shlex +import subprocess +import tempfile + + +PREAMBLE = r''' +#include +#include +#include +#define RAMFUNC + +typedef struct { int year, month, day, hour, min, sec; } ertc_time_type; +typedef struct { volatile uint32_t sbs; } fake_ertc_t; +static fake_ertc_t registers; +static ertc_time_type live_calendar, frozen_calendar, next_calendar; +static uint32_t live_sbs; +static bool locked; +static volatile uint64_t tick_start_val; +static unsigned sbs_reads, time_reads, date_reads; +static int rollover; +enum { NEVER, AFTER_SBS, AFTER_TIME, AFTER_DATE }; + +static void advance(int position) { + if (rollover == position) { + live_calendar = next_calendar; + live_sbs = 3124; + rollover = NEVER; + } +} + +static void read_date(void) { + date_reads++; + locked = false; + advance(AFTER_DATE); +} + +fake_ertc_t *read_subsecond(void) { + sbs_reads++; + registers.sbs = live_sbs; + if (!locked) frozen_calendar = live_calendar; + locked = true; + advance(AFTER_SBS); + return ®isters; +} +#define ERTC read_subsecond() + +void ertc_calendar_get(ertc_time_type *time) { + time_reads++; + if (!locked) frozen_calendar = live_calendar; + locked = true; + *time = frozen_calendar; + advance(AFTER_TIME); + read_date(); +} + +uint32_t ertc_sub_second_get(void) { + uint32_t value = ERTC->sbs; + read_date(); // Vendor helper releases the shadow lock before returning. + return value; +} +''' + +TEST = r''' +typedef struct { + const char *name; + ertc_time_type before, after; +} transition_t; + +static const transition_t transitions[] = { + {"second", {25, 8, 15, 13, 0, 0}, {25, 8, 15, 13, 0, 1}}, + {"minute", {25, 8, 15, 13, 0, 59}, {25, 8, 15, 13, 1, 0}}, + {"hour", {25, 8, 15, 13, 59, 59}, {25, 8, 15, 14, 0, 0}}, + {"day", {25, 8, 15, 23, 59, 59}, {25, 8, 16, 0, 0, 0}}, + {"month", {25, 8, 31, 23, 59, 59}, {25, 9, 1, 0, 0, 0}}, + {"year", {25, 12, 31, 23, 59, 59}, {26, 1, 1, 0, 0, 0}}, + {"leap-day-start", {28, 2, 28, 23, 59, 59}, {28, 2, 29, 0, 0, 0}}, + {"leap-day-end", {28, 2, 29, 23, 59, 59}, {28, 3, 1, 0, 0, 0}}, +}; + +static void setup(const transition_t *transition, uint32_t sbs, int position) { + live_calendar = transition->before; + next_calendar = transition->after; + live_sbs = sbs; + locked = false; + rollover = position; + sbs_reads = time_reads = date_reads = 0; + ertc_time_type t = transition->before; + tick_start_val = mktime_utc_fast(t.year + 2000, t.month, t.day, t.hour, t.min, t.sec, 0); +} + +static int test_transition(const transition_t *transition, int position) { + setup(transition, 0, NEVER); + uint32_t before = GetTickCount(); + rollover = position; + uint32_t after = GetTickCount(); + + setup(transition, 0, position); + uint32_t delta = GetTickCountDelta(before); + // Existing rounding maps the final subsecond tick to 1000 ms. + if (before != 1000 || after != 1000 || delta != 0 || locked) { + printf("RED %s position=%d before=%u after=%u delta=%u\n", + transition->name, position, before, after, delta); + return 1; + } + return 0; +} + +int main(void) { + int failures = 0; + unsigned cases = 0; + for (unsigned i = 0; i < sizeof(transitions) / sizeof(transitions[0]); i++) { + for (int position = AFTER_SBS; position <= AFTER_DATE; position++) { + failures += test_transition(&transitions[i], position); + cases++; + } + } + + for (uint32_t sbs = 0; sbs <= 3124; sbs++) { + setup(&transitions[0], sbs, NEVER); + uint32_t count = GetTickCount(); + uint32_t expected = (3125 - sbs) * 1000 / 3125; + if (count != expected || locked) failures++; + } + + setup(&transitions[0], 2500, NEVER); + uint32_t before = GetTickCount(); + live_sbs = 2497; + uint32_t after = GetTickCount(); + if (after < before || after - before > 1) failures++; + + // A coherent snapshot needs one read of each register, ending with DATE. + setup(&transitions[0], 1000, NEVER); + (void)GetTickCount(); + if (sbs_reads != 1 || time_reads != 1 || date_reads != 1 || locked) { + printf("RED register reads SBS=%u TIME=%u DATE=%u\n", sbs_reads, time_reads, date_reads); + failures++; + } + printf("RTC tick snapshot test: %s; %u rollover cases, 3125 subsecond values\n", + failures ? "RED" : "OK", cases); + return failures ? 1 : 0; +} +''' + + +def function(text, marker): + start = text.index(marker) + brace = text.index("{", start) + depth = 1 + end = brace + 1 + while depth: + if text[end] == "{": + depth += 1 + elif text[end] == "}": + depth -= 1 + end += 1 + return text[start:end] + "\n" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, help="alternate getter source for a negative control") + parser.add_argument("--optimization", choices=("0", "2", "s"), default="2") + args = parser.parse_args() + root = Path(__file__).resolve().parent.parent + hardware = (args.source or root / "common_arm/ticks/ticks_hw_at32.c").read_text() + core = (root / "common_arm/ticks/ticks_core.c").read_text() + calendar_math = function(hardware, "static uint64_t mktime_utc_fast(") + getter = function(hardware, "uint32_t RAMFUNC GetTickCount(void)") + delta = function(core, "uint32_t RAMFUNC GetTickCountDelta(") + with tempfile.TemporaryDirectory(prefix="rtc-tick-test-") as directory: + executable = Path(directory) / ("rtc_tick_test.exe" if os.name == "nt" else "rtc_tick_test") + command = shlex.split(os.environ.get("CC", "cc")) + ["-std=c99", "-O" + args.optimization, "-Wall", "-Wextra", "-Werror", "-x", "c", "-", "-o", str(executable)] + subprocess.run(command, input=PREAMBLE + calendar_math + getter + delta + TEST, text=True, check=True) + result = subprocess.run([str(executable)]) + raise SystemExit(result.returncode) + + +if __name__ == "__main__": + main()