mdat.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. #!/usr/bin/env python3
  2. """
  3. Miflare Dump Analyse Tool (1K/4K)
  4. A command-line utility for analyzing and manipulating MIFARE Classic dumps.
  5. Main Features:
  6. - Load and display .bin dumps of 1K (16 sectors) or 4K (64 sectors) MIFARE Classic cards
  7. - Optional bit-level view with --bits (-b)
  8. - Visual highlight of UID, BCC, ATQA, and SAK in sector 0, block 0
  9. - Visual parsing of trailer blocks: Key A, Access Bits, User Data, and Key B
  10. - Detect MIFARE tag type and manufacturer
  11. - Calculate and verify BCC for custom UIDs (--calc-bcc)
  12. - Decode access bits (--calc-access) or generate them interactively (--gen-access)
  13. - Compare two dumps with optional diff-only mode (--compare, --diff-only)
  14. - Multilingual support: English (default) and Russian (--lang ru)
  15. Example Usage:
  16. ./mdat.py dump.bin --bits
  17. ./mdat.py --calc-bcc B7 52 3D 22
  18. ./mdat.py --calc-access FF 07 08
  19. ./mdat.py --gen-access
  20. ./mdat.py --compare dump1.bin dump2.bin --diff-only
  21. --
  22. Copyright (c) 2025 te4gh0st
  23. """
  24. import argparse
  25. import sys
  26. # ANSI escape codes for colors
  27. RESET = "\033[0m"
  28. RED = "\033[31m"
  29. GREEN = "\033[32m"
  30. YELLOW = "\033[33m"
  31. CYAN = "\033[36m"
  32. MAGENTA = "\033[35m"
  33. GRAY = "\033[90m"
  34. LANG_TEXT = {
  35. 'en': {
  36. 'sector': 'Sector', 'block': 'Block', 'uid': 'UID', 'bcc': 'BCC',
  37. 'atqa': 'ATQA', 'sak': 'SAK', 'type': 'Tag type', 'mf': 'Manufacturer',
  38. 'access': 'Access', 'calc_bcc': 'Calculated BCC',
  39. 'access_calc': 'Access bits calculation',
  40. 'access_block': 'Access Block',
  41. 'read_write': 'Key A/B read & write (insecure)',
  42. 'read_only': 'Key A read only',
  43. 'read_allow_write_never': 'Read with Key A, writing not allowed',
  44. 'read_write_key_b': 'Read/Write with Key B',
  45. 'read_key_b_write_never': 'Read with Key B, writing not allowed',
  46. 'no_access': 'No access',
  47. 'custom': 'Custom', 'trailer': 'Trailer',
  48. 'compare': 'Comparing dumps',
  49. 'diff_only': 'Differences only',
  50. 'trailer_details': {
  51. (0, 0, 0): 'Key A/B can be read/written, access bits are changeable (INSECURE)',
  52. (0, 1, 0): 'Key B can be read/written with Key A, access bits are changeable',
  53. (1, 0, 0): 'Key B can be read with Key A, access bits are changeable',
  54. (1, 1, 0): 'Key B can be read with Key A, access bits are changeable (requires Key B)',
  55. (1, 0, 1): 'Access bits readable with Key A/B, write only with Key B. Keys cannot be read.',
  56. (0, 0, 1): 'Transport configuration: access only via Key A, keys are not readable.',
  57. (0, 1, 1): 'Read/write via Key B, partially via Key A.',
  58. (1, 1, 1): 'Access blocked. Authentication only.',
  59. },
  60. 'gen_access': '=== Access Bytes Generator ===\nSelect access bits for each block:',
  61. 'input_prompt': 'Choose option [1-8] for block {i}: ',
  62. 'user_data_prompt': 'UserData byte (hex, e.g. 69) [00]: ',
  63. 'invalid_choice': 'Invalid choice. Please enter a number from 1 to 8.',
  64. 'invalid_hex': 'Invalid hex input. Defaulting to 00.',
  65. 'result': 'Result:',
  66. 'no_description': 'No description available.',
  67. 'access_bytes': 'Access Bytes',
  68. 'byte': 'Byte',
  69. 'differences': 'Total differences'
  70. },
  71. 'ru': {
  72. 'sector': 'Сектор', 'block': 'Блок', 'uid': 'UID', 'bcc': 'BCC',
  73. 'atqa': 'ATQA', 'sak': 'SAK', 'type': 'Тип метки', 'mf': 'Производитель',
  74. 'access': 'Права', 'calc_bcc': 'Вычисленный BCC',
  75. 'access_calc': 'Калькулятор бит доступа',
  76. 'access_block': 'Блок доступа',
  77. 'custom': 'Пользовательские', 'trailer': 'Трейлер',
  78. 'read_write': 'Чтение/запись с ключом A/B (небезопасно)',
  79. 'read_only': 'Только чтение с ключом A',
  80. 'read_allow_write_never': 'Чтение с ключом A, запись невозможна',
  81. 'read_write_key_b': 'Чтение/запись с ключом B',
  82. 'read_key_b_write_never': 'Чтение с ключом B, запись невозможна',
  83. 'no_access': 'Нет доступа',
  84. 'compare': 'Сравнение дампов',
  85. 'diff_only': 'Только различия',
  86. 'trailer_details': {
  87. (0, 0, 0): 'Ключи A/B доступны для чтения/записи, биты доступа изменяемы (НЕБЕЗОПАСНО)',
  88. (0, 1, 0): 'Ключ B доступен для чтения/записи с Key A, биты доступа изменяемы',
  89. (1, 0, 0): 'Ключ B доступен для чтения с Key A, биты доступа изменяемы',
  90. (1, 1, 0): 'Ключ B доступен для чтения с Key A, биты доступа изменяемы (требуется Key B)',
  91. (1, 0, 1): 'Для чтения битов доступа нужен Key A/B, запись только с Key B. Ключи недоступны для чтения.',
  92. (0, 0, 1): 'Транспортная конфигурация: доступ только через Key A, ключи не читаются.',
  93. (0, 1, 1): 'Чтение и запись через Key B, частично через Key A.',
  94. (1, 1, 1): 'Доступ заблокирован. Только аутентификация.',
  95. },
  96. 'gen_access': '=== Генератор байтов доступа ===\nВыберите биты доступа для каждого блока:',
  97. 'input_prompt': 'Выберите вариант [1-8] для блока {i}: ',
  98. 'user_data_prompt': 'Байт UserData (в hex, напр. 69) [00]: ',
  99. 'invalid_choice': 'Неверный выбор. Введите число от 1 до 8.',
  100. 'invalid_hex': 'Неверный формат hex. Используется значение по умолчанию: 00.',
  101. 'result': 'Результат:',
  102. 'no_description': 'Описание недоступно.',
  103. 'access_bytes': 'Байты доступа',
  104. 'byte': 'Байт',
  105. 'differences': 'Всего отличий'
  106. }
  107. }
  108. access_map = {
  109. (0, 0, 0): ('read_write', None),
  110. (1, 0, 0): ('read_only', None),
  111. (0, 1, 0): ('read_allow_write_never', None),
  112. (0, 0, 1): ('read_write_key_b', None),
  113. (0, 1, 1): ('read_write_key_b', None),
  114. (1, 0, 1): ('read_key_b_write_never', None),
  115. (1, 1, 0): ('read_write_key_b', None),
  116. (1, 1, 1): ('no_access', None),
  117. }
  118. TAG_TYPES = {
  119. (0x0004, 0x08): ('MIFARE Classic 1K', 'NXP'),
  120. (0x0002, 0x18): ('MIFARE Classic 4K', 'NXP'),
  121. (0x0344, 0x38): ('MIFARE Ultralight', 'NXP'),
  122. (0x0044, 0x20): ('MIFARE DESFire EV1/EV2', 'NXP'),
  123. (0x0400, 0x88): ('Cascade Tag (7-byte UID)', 'NXP'),
  124. (0x4400, 0x98): ('MIFARE Classic 4K with 7-byte UID', 'NXP'),
  125. }
  126. def color_bits(val, mask=None, color=YELLOW):
  127. bits = ''.join(str((val >> i) & 1) for i in reversed(range(8)))
  128. if mask is None:
  129. return bits
  130. mask_bits = ''.join(str((mask >> i) & 1) for i in reversed(range(8)))
  131. out = []
  132. for b, m in zip(bits, mask_bits):
  133. out.append((color + b + RESET) if m == '1' else b)
  134. return ''.join(out)
  135. def calc_bcc(uid_bytes):
  136. b = 0
  137. for x in uid_bytes:
  138. b ^= x
  139. return b
  140. def parse_access(byte6, byte7, byte8):
  141. """
  142. Парсит access bits из трёх байт (byte6, byte7, byte8),
  143. проверяет корректность по контрольным битам,
  144. и возвращает матрицу [блок][C1, C2, C3] и флаг валидности.
  145. """
  146. def get_bit(value, bit):
  147. return (value >> bit) & 1
  148. # C1: из byte7, биты 4–7
  149. c1 = [get_bit(byte7, 4 + i) for i in range(4)]
  150. # C1': из byte6, биты 0–3
  151. c1_inv = [get_bit(byte6, i) for i in range(4)]
  152. # C2: из byte8, биты 0–3
  153. c2 = [get_bit(byte8, i) for i in range(4)]
  154. # C2': из byte6, биты 4–7
  155. c2_inv = [get_bit(byte6, 4 + i) for i in range(4)]
  156. # C3: из byte8, биты 4–7
  157. c3 = [get_bit(byte8, 4 + i) for i in range(4)]
  158. # C3': из byte7, биты 0–3
  159. c3_inv = [get_bit(byte7, i) for i in range(4)]
  160. # Проверка валидности контрольных битов
  161. valid = all(
  162. (c1[i] ^ c1_inv[i]) == 1 and
  163. (c2[i] ^ c2_inv[i]) == 1 and
  164. (c3[i] ^ c3_inv[i]) == 1
  165. for i in range(4)
  166. )
  167. # Формируем матрицу [блок][C1, C2, C3]
  168. matrix = [
  169. [c1[0], c2[0], c3[0]],
  170. [c1[1], c2[1], c3[1]],
  171. [c1[2], c2[2], c3[2]],
  172. [c1[3], c2[3], c3[3]],
  173. ]
  174. return matrix, valid
  175. def describe_access(bits_matrix, valid, lang):
  176. t = LANG_TEXT[lang]
  177. desc = {}
  178. for i, (c1, c2, c3) in enumerate(bits_matrix):
  179. if i < 3:
  180. entry = access_map.get((c1, c2, c3))
  181. d = t[entry[0]] if entry else f"{t['custom']} ({c1},{c2},{c3})"
  182. else:
  183. d = t['trailer_details'].get((c1, c2, c3), t['trailer'])
  184. desc[i] = d
  185. return {
  186. "valid": valid,
  187. "description": desc
  188. }
  189. def hexdump(b): return ' '.join(f"{x:02X}" for x in b)
  190. def show_sector(sec, idx, args, txt):
  191. print(CYAN + f"{txt['sector']} {idx}" + RESET)
  192. for i, blk in enumerate(sec):
  193. header = f" {txt['block']} {i}: {hexdump(blk)}"
  194. print(header)
  195. if args.bits:
  196. bits_str = ' '.join(color_bits(x, mask=0xFF) for x in blk)
  197. print(f" Bits : {bits_str}")
  198. # UID block
  199. if idx == 0 and i == 0:
  200. uid = blk[:4]
  201. bcc_byte = blk[4]
  202. sak = blk[5]
  203. atqa = (blk[7] << 8) | blk[6]
  204. calc = calc_bcc(uid)
  205. ok = calc == bcc_byte
  206. print(f" {txt['uid']}: " + ' '.join(MAGENTA + f"{x:02X}" + RESET for x in uid))
  207. print(f" {txt['bcc']}: {YELLOW}{bcc_byte:02X}{RESET} ({txt['calc_bcc']}: {calc:02X}) → " +
  208. (GREEN + "OK" + RESET if ok else RED + "FAIL" + RESET))
  209. print(f" {txt['atqa']}: {atqa:04X}, {txt['sak']}: {sak:02X}")
  210. # Trailer block with Key A, Access Bits, User Data, Key B
  211. if i == 3:
  212. key_a = blk[0:6]
  213. ab6, ab7, ab8 = blk[6], blk[7], blk[8]
  214. user_data = blk[9]
  215. key_b = blk[10:16]
  216. # Colored segments
  217. ka_str = ' '.join(MAGENTA + f"{x:02X}" + RESET for x in key_a)
  218. ab_str = ' '.join(YELLOW + f"{x:02X}" + RESET for x in (ab6, ab7, ab8))
  219. ud_str = CYAN + f"{user_data:02X}" + RESET
  220. kb_str = ' '.join(GREEN + f"{x:02X}" + RESET for x in key_b)
  221. print(f" Key A : {ka_str}")
  222. print(f" Access bits : {ab_str} UserData: {ud_str}")
  223. print(f" Key B : {kb_str}")
  224. # decode access
  225. bits, valid = parse_access(ab6, ab7, ab8)
  226. result = describe_access(bits, valid, args.lang)
  227. desc = result["description"]
  228. t = LANG_TEXT[args.lang]
  229. for block in sorted(desc):
  230. print(f" {t['access_block']} {block}: {MAGENTA}{desc[block]}{RESET}")
  231. # Добавим вывод информации о корректности access bits
  232. if valid:
  233. print(
  234. f" {GREEN}{txt['valid_access_bits'] if 'valid_access_bits' in txt else 'Access bits are valid.'}{RESET}")
  235. else:
  236. print(
  237. f" {RED}{txt['invalid_access_bits'] if 'invalid_access_bits' in txt else 'Access bits are INVALID!'}{RESET}")
  238. def load(path):
  239. d = open(path, 'rb').read()
  240. if len(d) not in (1024, 4096):
  241. sys.exit("Bad dump size")
  242. bl = [d[i:i+16] for i in range(0, len(d), 16)]
  243. return [bl[i*4:(i+1)*4] for i in range(len(bl)//4)]
  244. def generate_access_interactive(lang):
  245. t = LANG_TEXT[lang]
  246. print(f"{CYAN}{t['gen_access']}{RESET}")
  247. specs = {}
  248. options = list(access_map.items())
  249. for i in range(4):
  250. print(f"\n{YELLOW}Block {i}:{RESET}")
  251. for idx, (bits, (key, _)) in enumerate(options, 1):
  252. print(f" {idx}. C1,C2,C3 = {bits} — {t.get(key, key)}")
  253. while True:
  254. choice = input(t['input_prompt'].format(i=i, max=len(options)))
  255. if choice.isdigit() and 1 <= int(choice) <= len(access_map):
  256. bits = options[int(choice)-1][0]
  257. specs[i] = bits
  258. print(f"{MAGENTA}Выбрано: C1={bits[0]}, C2={bits[1]}, C3={bits[2]}{RESET}")
  259. break
  260. else:
  261. print(f"{RED}{t['invalid_choice']}{RESET}")
  262. # UserData input
  263. ud_in = input(f"{CYAN}{t['user_data_prompt']}{RESET}") or "00"
  264. try:
  265. ud = int(ud_in, 16)
  266. except ValueError:
  267. print(f"{RED}{t['invalid_hex']}{RESET}")
  268. ud = 0x00
  269. ab6 = sum((specs[i][2] << i) for i in range(4))
  270. ab7 = sum(((specs[i][0] ^ 1) << i) for i in range(4))
  271. ab8 = sum(((specs[i][1] ^ 1) << i) for i in range(4))
  272. print(f"\n{GREEN}{t['result']}{RESET}")
  273. print(f"Access bytes: {ab6:02X} {ab7:02X} {ab8:02X} UserData: {ud:02X}")
  274. sys.exit(0)
  275. def highlight_diff_bytes(b1: bytes, b2: bytes) -> tuple[str, str]:
  276. """Подсвечивает отличающиеся байты красным, совпадающие серым"""
  277. h1 = []
  278. h2 = []
  279. for byte1, byte2 in zip(b1, b2):
  280. hex1 = f"{byte1:02X}"
  281. hex2 = f"{byte2:02X}"
  282. if byte1 != byte2:
  283. h1.append(f"{RED}{hex1}{RESET}")
  284. h2.append(f"{RED}{hex2}{RESET}")
  285. else:
  286. h1.append(f"{GRAY}{hex1}{RESET}")
  287. h2.append(f"{GRAY}{hex2}{RESET}")
  288. return ' '.join(h1), ' '.join(h2)
  289. def compare_dumps(path1, path2, args, txt):
  290. d1 = load(path1)
  291. d2 = load(path2)
  292. print(f"{CYAN}{txt['compare']}{RESET}")
  293. diffs = 0
  294. for si, (s1, s2) in enumerate(zip(d1, d2)):
  295. for bi, (b1, b2) in enumerate(zip(s1, s2)):
  296. if args.diff_only:
  297. if b1 != b2:
  298. diffs += 1
  299. print(f"{YELLOW}{txt['sector']} {si} {txt['block']} {bi}:{RESET}")
  300. h1, h2 = highlight_diff_bytes(b1, b2)
  301. print(f" A: {h1}")
  302. print(f" B: {h2}")
  303. else:
  304. marker = GREEN + '==' + RESET if b1 == b2 else RED + '!=' + RESET
  305. h1, h2 = highlight_diff_bytes(b1, b2)
  306. print(f"{txt['sector']} {si:<2} {txt['block']} {bi}: {h1} {marker} {h2}")
  307. if b1 != b2:
  308. diffs += 1
  309. print(f"\n{MAGENTA}{txt['differences']}: {diffs}{RESET}")
  310. sys.exit(0)
  311. def main():
  312. p = argparse.ArgumentParser(
  313. description='Miflare Dump Analyse Tool\nCopyright (c) 2025 te4gh0st',
  314. formatter_class=argparse.RawTextHelpFormatter)
  315. p.add_argument('dump', nargs='?', help='.bin dump file')
  316. p.add_argument('--bits', '-b', action='store_true', help='Show bits view (Показать биты)')
  317. p.add_argument('--lang', choices=['en', 'ru'], default='en', help='Language / Язык')
  318. p.add_argument('--calc-bcc', nargs='+', metavar='BYTE',
  319. help='Calculate BCC for UID bytes (Вычислить BCC для байт UID)')
  320. p.add_argument('--calc-access', nargs=3, metavar='HEX',
  321. help='Decode access bytes FF 07 08 (Декодировать байты доступа FF 07 08)')
  322. p.add_argument('--gen-access', action='store_true', help='Generate access bytes interactively (Интерактивная генерация бит доступа)')
  323. p.add_argument('--compare', nargs=2, metavar=('DUMP1','DUMP2'),
  324. help='Compare two dumps (Сравнить два дампа)')
  325. p.add_argument('--diff-only', action='store_true', help='Show only differences when comparing (Только различия)')
  326. args = p.parse_args()
  327. txt = LANG_TEXT[args.lang]
  328. if args.calc_bcc:
  329. uid = [int(x, 16) for x in args.calc_bcc]
  330. print(f"{txt['uid']}: {' '.join(f"{x:02X}" for x in uid)} → {txt['bcc']}: {calc_bcc(uid):02X}")
  331. sys.exit(0)
  332. if args.calc_access:
  333. ab6, ab7, ab8 = [int(x, 16) for x in args.calc_access]
  334. bits, valid = parse_access(ab6, ab7, ab8)
  335. result = describe_access(bits, valid, args.lang)
  336. desc = result["description"]
  337. t = LANG_TEXT[args.lang]
  338. print(f"{CYAN}{t['access_calc']}{RESET}")
  339. print(f"{YELLOW}{'Access Matrix:':<20}{RESET}")
  340. for block, (c1, c2, c3) in enumerate(bits):
  341. print(f" Block {block:<2}: C1={c1} C2={c2} C3={c3}")
  342. print(f"\n{YELLOW}{'Descriptions:' if args.lang == 'en' else 'Пояснения:'}{RESET}")
  343. for block in sorted(desc):
  344. print(f" {t['access_block']} {block}: {MAGENTA}{desc[block]}{RESET}")
  345. print(f"\n{GREEN}{t['access_bytes']}:{RESET} [{t['byte']} 6] = {RED}{ab6:02X}{RESET} "
  346. f"[{t['byte']} 7] = {RED}{ab7:02X}{RESET} [{t['byte']} 8] = {RED}{ab8:02X}{RESET}")
  347. # Вывод флага корректности
  348. if valid: # todo: translate
  349. print(f"\n{GREEN}Access bits are valid.{RESET}")
  350. else:
  351. print(f"\n{RED}Access bits are INVALID!{RESET}")
  352. sys.exit(0)
  353. if args.gen_access:
  354. generate_access_interactive(args.lang)
  355. if args.compare:
  356. compare_dumps(args.compare[0], args.compare[1], args, txt)
  357. if not args.dump:
  358. p.print_help()
  359. sys.exit(1)
  360. secs = load(args.dump)
  361. # Display tag type and manufacturer
  362. if secs and secs[0] and secs[0][0]:
  363. block0 = secs[0][0]
  364. sak = block0[5]
  365. atqa = (block0[7] << 8) | block0[6]
  366. tag_type, manufacturer = TAG_TYPES.get((atqa, sak), ('Unknown', 'Unknown'))
  367. print(f"{txt['type']}: {MAGENTA}{tag_type}{RESET}\n{txt['mf']}: {MAGENTA}{manufacturer}{RESET}\n")
  368. for i, sec in enumerate(secs):
  369. show_sector(sec, i, args, txt)
  370. if __name__ == '__main__':
  371. main()