mdat.py 16 KB

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