Merge remote-tracking branch 'upstream/master' into fix/psk-fc2-bandpass

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Matthew Carroll committed 2026-10-17 23:47:19 -07:00
commit 1bc32bff15
28 files changed
+2057 -109

No files matched your search

+625
View File
@@ -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(
"<B",
bytes(self.vendor_data[offset : offset + 1]),
)[0]
def uint8_to_field(self, offset, value: int) -> None:
assert 0 <= value <= 255, "value must be between 0 and 255"
field_value = pack("<B", value)
self.vendor_data[offset : offset + 1] = field_value
def uint32_to_field(self, offset, value: int) -> None:
field_value = pack("<I", value)
self.vendor_data[offset : offset + 4] = field_value
def field_to_text(self, offset, max_size) -> 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(
"<H",
bytes(
self.vendor_data[
self.PRINT_COUNTER_OFFSET : self.PRINT_COUNTER_OFFSET + 2
]
),
)
return print_count[0]
@print_counter.setter
def print_counter(self, value:int):
self.uint8_to_field(self.PRINT_COUNTER_OFFSET, value)
@property
def print_counter_crc32(self) -> int:
print_counter_crc32 = unpack(
"<I",
bytes(
self.vendor_data[
self.PRINT_COUNTER_CRC32_OFFSET : self.PRINT_COUNTER_CRC32_OFFSET
+ 4
]
),
)
return print_counter_crc32[0]
@print_counter_crc32.setter
def print_counter_crc32(self, value:int):
return self.uint32_to_field(self.PRINT_COUNTER_CRC32_OFFSET, value)
@property
def print_limit(self) -> int:
print_limit = unpack(
"<B",
bytes(
self.vendor_data[self.PRINT_LIMIT_OFFSET : self.PRINT_LIMIT_OFFSET + 1]
),
)
return print_limit[0]
@property
def reencrypted_data(self) -> 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()
+163 -86
View File
@@ -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 <key>"));
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"},
+79 -1
View File
@@ -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", "<hex>", "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}
};