-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathchameleon_cli_unit.py
3121 lines (2690 loc) · 126 KB
/
chameleon_cli_unit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import binascii
import os
import re
import subprocess
import argparse
import timeit
import sys
import time
from datetime import datetime
import serial.tools.list_ports
import threading
import struct
from multiprocessing import Pool, cpu_count
from typing import Union
from pathlib import Path
from platform import uname
from datetime import datetime
import chameleon_com
import chameleon_cmd
from chameleon_utils import ArgumentParserNoExit, ArgsParserError, UnexpectedResponseError
from chameleon_utils import CLITree
from chameleon_utils import CR, CG, CB, CC, CY, C0
from chameleon_utils import print_mem_dump
from chameleon_enum import Command, Status, SlotNumber, TagSenseType, TagSpecificType
from chameleon_enum import MifareClassicWriteMode, MifareClassicPrngType, MifareClassicDarksideStatus, MfcKeyType
from chameleon_enum import AnimationMode, ButtonPressFunction, ButtonType, MfcValueBlockOperator
from crypto1 import Crypto1
# NXP IDs based on https://www.nxp.com/docs/en/application-note/AN10833.pdf
type_id_SAK_dict = {0x00: "MIFARE Ultralight Classic/C/EV1/Nano | NTAG 2xx",
0x08: "MIFARE Classic 1K | Plus SE 1K | Plug S 2K | Plus X 2K",
0x09: "MIFARE Mini 0.3k",
0x10: "MIFARE Plus 2K",
0x11: "MIFARE Plus 4K",
0x18: "MIFARE Classic 4K | Plus S 4K | Plus X 4K",
0x19: "MIFARE Classic 2K",
0x20: "MIFARE Plus EV1/EV2 | DESFire EV1/EV2/EV3 | DESFire Light | NTAG 4xx | "
"MIFARE Plus S 2/4K | MIFARE Plus X 2/4K | MIFARE Plus SE 1K",
0x28: "SmartMX with MIFARE Classic 1K",
0x38: "SmartMX with MIFARE Classic 4K",
}
default_cwd = Path.cwd() / Path(__file__).with_name("bin")
def check_tools():
tools = ['staticnested', 'nested', 'darkside', 'mfkey32v2']
if sys.platform == "win32":
tools = [x+'.exe' for x in tools]
missing_tools = [tool for tool in tools if not (default_cwd / tool).exists()]
if len(missing_tools) > 0:
print(f'{CR}Warning, tools {", ".join(missing_tools)} not found. '
f'Corresponding commands will not work as intended.{C0}')
class BaseCLIUnit:
def __init__(self):
# new a device command transfer and receiver instance(Send cmd and receive response)
self._device_com: Union[chameleon_com.ChameleonCom, None] = None
self._device_cmd: Union[chameleon_cmd.ChameleonCMD, None] = None
@property
def device_com(self) -> chameleon_com.ChameleonCom:
assert self._device_com is not None
return self._device_com
@device_com.setter
def device_com(self, com):
self._device_com = com
self._device_cmd = chameleon_cmd.ChameleonCMD(self._device_com)
@property
def cmd(self) -> chameleon_cmd.ChameleonCMD:
assert self._device_cmd is not None
return self._device_cmd
def args_parser(self) -> ArgumentParserNoExit:
"""
CMD unit args.
:return:
"""
raise NotImplementedError("Please implement this")
def before_exec(self, args: argparse.Namespace):
"""
Call a function before exec cmd.
:return: function references
"""
return True
def on_exec(self, args: argparse.Namespace):
"""
Call a function on cmd match.
:return: function references
"""
raise NotImplementedError("Please implement this")
def after_exec(self, args: argparse.Namespace):
"""
Call a function after exec cmd.
:return: function references
"""
return True
@staticmethod
def sub_process(cmd, cwd=default_cwd):
class ShadowProcess:
def __init__(self):
self.output = ""
self.time_start = timeit.default_timer()
self._process = subprocess.Popen(cmd, cwd=cwd, shell=True, stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
threading.Thread(target=self.thread_read_output).start()
def thread_read_output(self):
while self._process.poll() is None:
assert self._process.stdout is not None
data = self._process.stdout.read(1024)
if len(data) > 0:
self.output += data.decode(encoding="utf-8")
def get_time_distance(self, ms=True):
if ms:
return round((timeit.default_timer() - self.time_start) * 1000, 2)
else:
return round(timeit.default_timer() - self.time_start, 2)
def is_running(self):
return self._process.poll() is None
def is_timeout(self, timeout_ms):
time_distance = self.get_time_distance()
if time_distance > timeout_ms:
return True
return False
def get_output_sync(self):
return self.output
def get_ret_code(self):
return self._process.poll()
def stop_process(self):
# noinspection PyBroadException
try:
self._process.kill()
except Exception:
pass
def get_process(self):
return self._process
def wait_process(self):
return self._process.wait()
return ShadowProcess()
class DeviceRequiredUnit(BaseCLIUnit):
"""
Make sure of device online
"""
def before_exec(self, args: argparse.Namespace):
ret = self.device_com.isOpen()
if ret:
return True
else:
print("Please connect to chameleon device first(use 'hw connect').")
return False
class ReaderRequiredUnit(DeviceRequiredUnit):
"""
Make sure of device enter to reader mode.
"""
def before_exec(self, args: argparse.Namespace):
if super().before_exec(args):
ret = self.cmd.is_device_reader_mode()
if ret:
return True
else:
self.cmd.set_device_reader_mode(True)
print("Switch to { Tag Reader } mode successfully.")
return True
return False
class SlotIndexArgsUnit(DeviceRequiredUnit):
@staticmethod
def add_slot_args(parser: ArgumentParserNoExit, mandatory=False):
slot_choices = [x.value for x in SlotNumber]
help_str = f"Slot Index: {slot_choices} Default: active slot"
parser.add_argument('-s', "--slot", type=int, required=mandatory, help=help_str, metavar="<1-8>",
choices=slot_choices)
return parser
class SlotIndexArgsAndGoUnit(SlotIndexArgsUnit):
def before_exec(self, args: argparse.Namespace):
if super().before_exec(args):
self.prev_slot_num = SlotNumber.from_fw(self.cmd.get_active_slot())
if args.slot is not None:
self.slot_num = args.slot
if self.slot_num != self.prev_slot_num:
self.cmd.set_active_slot(self.slot_num)
else:
self.slot_num = self.prev_slot_num
return True
return False
def after_exec(self, args: argparse.Namespace):
if self.prev_slot_num != self.slot_num:
self.cmd.set_active_slot(self.prev_slot_num)
class SenseTypeArgsUnit(DeviceRequiredUnit):
@staticmethod
def add_sense_type_args(parser: ArgumentParserNoExit):
sense_group = parser.add_mutually_exclusive_group(required=True)
sense_group.add_argument('--hf', action='store_true', help="HF type")
sense_group.add_argument('--lf', action='store_true', help="LF type")
return parser
class MF1AuthArgsUnit(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.add_argument('--blk', '--block', type=int, required=True, metavar="<dec>",
help="The block where the key of the card is known")
type_group = parser.add_mutually_exclusive_group()
type_group.add_argument('-a', '-A', action='store_true', help="Known key is A key (default)")
type_group.add_argument('-b', '-B', action='store_true', help="Known key is B key")
parser.add_argument('-k', '--key', type=str, required=True, metavar="<hex>", help="tag sector key")
return parser
def get_param(self, args):
class Param:
def __init__(self):
self.block = args.blk
self.type = MfcKeyType.B if args.b else MfcKeyType.A
key: str = args.key
if not re.match(r"^[a-fA-F0-9]{12}$", key):
raise ArgsParserError("key must include 12 HEX symbols")
self.key: bytearray = bytearray.fromhex(key)
return Param()
class HF14AAntiCollArgsUnit(DeviceRequiredUnit):
@staticmethod
def add_hf14a_anticoll_args(parser: ArgumentParserNoExit):
parser.add_argument('--uid', type=str, metavar="<hex>", help="Unique ID")
parser.add_argument('--atqa', type=str, metavar="<hex>", help="Answer To Request")
parser.add_argument('--sak', type=str, metavar="<hex>", help="Select AcKnowledge")
ats_group = parser.add_mutually_exclusive_group()
ats_group.add_argument('--ats', type=str, metavar="<hex>", help="Answer To Select")
ats_group.add_argument('--delete-ats', action='store_true', help="Delete Answer To Select")
return parser
def update_hf14a_anticoll(self, args, uid, atqa, sak, ats):
anti_coll_data_changed = False
change_requested = False
if args.uid is not None:
change_requested = True
uid_str: str = args.uid.strip()
if re.match(r"[a-fA-F0-9]+", uid_str) is not None:
new_uid = bytes.fromhex(uid_str)
if len(new_uid) not in [4, 7, 10]:
raise Exception("UID length error")
else:
raise Exception("UID must be hex")
if new_uid != uid:
uid = new_uid
anti_coll_data_changed = True
else:
print(f'{CY}Requested UID already set{C0}')
if args.atqa is not None:
change_requested = True
atqa_str: str = args.atqa.strip()
if re.match(r"[a-fA-F0-9]{4}", atqa_str) is not None:
new_atqa = bytes.fromhex(atqa_str)
else:
raise Exception("ATQA must be 4-byte hex")
if new_atqa != atqa:
atqa = new_atqa
anti_coll_data_changed = True
else:
print(f'{CY}Requested ATQA already set{C0}')
if args.sak is not None:
change_requested = True
sak_str: str = args.sak.strip()
if re.match(r"[a-fA-F0-9]{2}", sak_str) is not None:
new_sak = bytes.fromhex(sak_str)
else:
raise Exception("SAK must be 2-byte hex")
if new_sak != sak:
sak = new_sak
anti_coll_data_changed = True
else:
print(f'{CY}Requested SAK already set{C0}')
if (args.ats is not None) or args.delete_ats:
change_requested = True
if args.delete_ats:
new_ats = b''
else:
ats_str: str = args.ats.strip()
if re.match(r"[a-fA-F0-9]+", ats_str) is not None:
new_ats = bytes.fromhex(ats_str)
else:
raise Exception("ATS must be hex")
if new_ats != ats:
ats = new_ats
anti_coll_data_changed = True
else:
print(f'{CY}Requested ATS already set{C0}')
if anti_coll_data_changed:
self.cmd.hf14a_set_anti_coll_data(uid, atqa, sak, ats)
return change_requested, anti_coll_data_changed, uid, atqa, sak, ats
class MFUAuthArgsUnit(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
def key_parser(key: str) -> bytes:
try:
key = bytes.fromhex(key)
except:
raise ValueError("Key should be a hex string")
if len(key) not in [4, 16]:
raise ValueError("Key should either be 4 or 16 bytes long")
elif len(key) == 16:
raise ValueError("Ultralight-C authentication isn't supported yet")
return key
parser.add_argument(
'-k', '--key', type=key_parser, metavar="<hex>", help="Authentication key (EV1/NTAG 4 bytes)."
)
parser.add_argument('-l', action='store_true', dest='swap_endian', help="Swap endianness of the key.")
return parser
def get_param(self, args):
key = args.key
if key is not None and args.swap_endian:
key = bytearray(key)
for i in range(len(key)):
tmp = key[i]
key[i] = key[len(key) - 1 - i]
key = bytes(key)
class Param:
def __init__(self, key):
self.key = key
return Param(key)
def on_exec(self, args: argparse.Namespace):
raise NotImplementedError("Please implement this")
class LFEMIdArgsUnit(DeviceRequiredUnit):
@staticmethod
def add_card_arg(parser: ArgumentParserNoExit, required=False):
parser.add_argument("--id", type=str, required=required, help="EM410x tag id", metavar="<hex>")
return parser
def before_exec(self, args: argparse.Namespace):
if super().before_exec(args):
if args.id is not None:
if not re.match(r"^[a-fA-F0-9]{10}$", args.id):
raise ArgsParserError("ID must include 10 HEX symbols")
return True
return False
def args_parser(self) -> ArgumentParserNoExit:
raise NotImplementedError("Please implement this")
def on_exec(self, args: argparse.Namespace):
raise NotImplementedError("Please implement this")
class TagTypeArgsUnit(DeviceRequiredUnit):
@staticmethod
def add_type_args(parser: ArgumentParserNoExit):
type_names = [t.name for t in TagSpecificType.list()]
help_str = "Tag Type: " + ", ".join(type_names)
parser.add_argument('-t', "--type", type=str, required=True, metavar="TAG_TYPE",
help=help_str, choices=type_names)
return parser
def args_parser(self) -> ArgumentParserNoExit:
raise NotImplementedError()
def on_exec(self, args: argparse.Namespace):
raise NotImplementedError()
root = CLITree(root=True)
hw = root.subgroup('hw', 'Hardware-related commands')
hw_slot = hw.subgroup('slot', 'Emulation slots commands')
hw_settings = hw.subgroup('settings', 'Chameleon settings commands')
hf = root.subgroup('hf', 'High Frequency commands')
hf_14a = hf.subgroup('14a', 'ISO14443-a commands')
hf_mf = hf.subgroup('mf', 'MIFARE Classic commands')
hf_mfu = hf.subgroup('mfu', 'MIFARE Ultralight / NTAG commands')
lf = root.subgroup('lf', 'Low Frequency commands')
lf_em = lf.subgroup('em', 'EM commands')
lf_em_410x = lf_em.subgroup('410x', 'EM410x commands')
@root.command('clear')
class RootClear(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Clear screen'
return parser
def on_exec(self, args: argparse.Namespace):
os.system('clear' if os.name == 'posix' else 'cls')
@root.command('rem')
class RootRem(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Timestamped comment'
parser.add_argument('comment', nargs='*', help='Your comment')
return parser
def on_exec(self, args: argparse.Namespace):
# precision: second
# iso_timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
# precision: nanosecond (note that the comment will take some time too, ~75ns, check your system)
iso_timestamp = datetime.utcnow().isoformat() + 'Z'
comment = ' '.join(args.comment)
print(f"{iso_timestamp} remark: {comment}")
@root.command('exit')
class RootExit(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Exit client'
return parser
def on_exec(self, args: argparse.Namespace):
print("Bye, thank you. ^.^ ")
self.device_com.close()
sys.exit(996)
@root.command('dump_help')
class RootDumpHelp(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Dump available commands'
parser.add_argument('-d', '--show-desc', action='store_true', help="Dump full command description")
parser.add_argument('-g', '--show-groups', action='store_true', help="Dump command groups as well")
return parser
@staticmethod
def dump_help(cmd_node, depth=0, dump_cmd_groups=False, dump_description=False):
visual_col1_width = 28
col1_width = visual_col1_width + len(f"{CG}{C0}")
if cmd_node.cls:
p = cmd_node.cls().args_parser()
assert p is not None
if dump_description:
p.print_help()
else:
cmd_title = f"{CG}{cmd_node.fullname}{C0}"
print(f"{cmd_title}".ljust(col1_width), end="")
p.prog = " " * (visual_col1_width - len("usage: ") - 1)
usage = p.format_usage().removeprefix("usage: ").strip()
print(f"{CY}{usage}{C0}")
else:
if dump_cmd_groups and not cmd_node.root:
if dump_description:
print("=" * 80)
print(f"{CR}{cmd_node.fullname}{C0}\n")
print(f"{CC}{cmd_node.help_text}{C0}\n")
else:
print(f"{CB}== {cmd_node.fullname} =={C0}")
for child in cmd_node.children:
RootDumpHelp.dump_help(child, depth + 1, dump_cmd_groups, dump_description)
def on_exec(self, args: argparse.Namespace):
self.dump_help(root, dump_cmd_groups=args.show_groups, dump_description=args.show_desc)
@hw.command('connect')
class HWConnect(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Connect to chameleon by serial port'
parser.add_argument('-p', '--port', type=str, required=False)
return parser
def on_exec(self, args: argparse.Namespace):
try:
if args.port is None: # Chameleon auto-detect if no port is supplied
platform_name = uname().release
if 'Microsoft' in platform_name:
path = os.environ["PATH"].split(os.pathsep)
path.append("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/")
powershell_path = None
for prefix in path:
fn = os.path.join(prefix, "powershell.exe")
if not os.path.isdir(fn) and os.access(fn, os.X_OK):
powershell_path = fn
break
if powershell_path:
process = subprocess.Popen([powershell_path,
"Get-PnPDevice -Class Ports -PresentOnly |"
" where {$_.DeviceID -like '*VID_6868&PID_8686*'} |"
" Select-Object -First 1 FriendlyName |"
" % FriendlyName |"
" select-string COM\\d+ |"
"% { $_.matches.value }"], stdout=subprocess.PIPE)
res = process.communicate()[0]
_comport = res.decode('utf-8').strip()
if _comport:
args.port = _comport.replace('COM', '/dev/ttyS')
else:
# loop through all ports and find chameleon
for port in serial.tools.list_ports.comports():
if port.vid == 0x6868:
args.port = port.device
break
if args.port is None: # If no chameleon was found, exit
print("Chameleon not found, please connect the device or try connecting manually with the -p flag.")
return
self.device_com.open(args.port)
self.device_com.commands = self.cmd.get_device_capabilities()
major, minor = self.cmd.get_app_version()
model = ['Ultra', 'Lite'][self.cmd.get_device_model()]
print(f" {{ Chameleon {model} connected: v{major}.{minor} }}")
except Exception as e:
print(f"{CR}Chameleon Connect fail: {str(e)}{C0}")
self.device_com.close()
@hw.command('disconnect')
class HWDisconnect(BaseCLIUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Disconnect chameleon'
return parser
def on_exec(self, args: argparse.Namespace):
self.device_com.close()
@hw.command('mode')
class HWMode(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Get or change device mode: tag reader or tag emulator'
mode_group = parser.add_mutually_exclusive_group()
mode_group.add_argument('-r', '--reader', action='store_true', help="Set reader mode")
mode_group.add_argument('-e', '--emulator', action='store_true', help="Set emulator mode")
return parser
def on_exec(self, args: argparse.Namespace):
if args.reader:
self.cmd.set_device_reader_mode(True)
print("Switch to { Tag Reader } mode successfully.")
elif args.emulator:
self.cmd.set_device_reader_mode(False)
print("Switch to { Tag Emulator } mode successfully.")
else:
print(f"- Device Mode ( Tag {'Reader' if self.cmd.is_device_reader_mode() else 'Emulator'} )")
@hw.command('chipid')
class HWChipId(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Get device chipset ID'
return parser
def on_exec(self, args: argparse.Namespace):
print(' - Device chip ID: ' + self.cmd.get_device_chip_id())
@hw.command('address')
class HWAddress(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Get device address (used with Bluetooth)'
return parser
def on_exec(self, args: argparse.Namespace):
print(' - Device address: ' + self.cmd.get_device_address())
@hw.command('version')
class HWVersion(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Get current device firmware version'
return parser
def on_exec(self, args: argparse.Namespace):
fw_version_tuple = self.cmd.get_app_version()
fw_version = f'v{fw_version_tuple[0]}.{fw_version_tuple[1]}'
git_version = self.cmd.get_git_version()
model = ['Ultra', 'Lite'][self.cmd.get_device_model()]
print(f' - Chameleon {model}, Version: {fw_version} ({git_version})')
@hf_14a.command('scan')
class HF14AScan(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Scan 14a tag, and print basic information'
return parser
def check_mf1_nt(self):
# detect mf1 support
if self.cmd.mf1_detect_support():
# detect prng
print("- Mifare Classic technology")
prng_type = self.cmd.mf1_detect_prng()
print(f" # Prng: {MifareClassicPrngType(prng_type)}")
def sak_info(self, data_tag):
# detect the technology in use based on SAK
int_sak = data_tag['sak'][0]
if int_sak in type_id_SAK_dict:
print(f"- Guessed type(s) from SAK: {type_id_SAK_dict[int_sak]}")
def scan(self, deep=False):
resp = self.cmd.hf14a_scan()
if resp is not None:
for data_tag in resp:
print(f"- UID : {data_tag['uid'].hex().upper()}")
print(f"- ATQA : {data_tag['atqa'].hex().upper()} "
f"(0x{int.from_bytes(data_tag['atqa'], byteorder='little'):04x})")
print(f"- SAK : {data_tag['sak'].hex().upper()}")
if len(data_tag['ats']) > 0:
print(f"- ATS : {data_tag['ats'].hex().upper()}")
if deep:
self.sak_info(data_tag)
# TODO: following checks cannot be done yet if multiple cards are present
if len(resp) == 1:
self.check_mf1_nt()
# TODO: check for ATS support on 14A3 tags
else:
print("Multiple tags detected, skipping deep tests...")
else:
print("ISO14443-A Tag no found")
def on_exec(self, args: argparse.Namespace):
self.scan()
@hf_14a.command('info')
class HF14AInfo(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Scan 14a tag, and print detail information'
return parser
def on_exec(self, args: argparse.Namespace):
scan = HF14AScan()
scan.device_com = self.device_com
scan.scan(deep=True)
@hf_mf.command('nested')
class HFMFNested(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Mifare Classic nested recover key'
parser.add_argument('--blk', '--known-block', type=int, required=True, metavar="<dec>",
help="Known key block number")
srctype_group = parser.add_mutually_exclusive_group()
srctype_group.add_argument('-a', '-A', action='store_true', help="Known key is A key (default)")
srctype_group.add_argument('-b', '-B', action='store_true', help="Known key is B key")
parser.add_argument('-k', '--key', type=str, required=True, metavar="<hex>", help="Known key")
# tblk required because only single block mode is supported for now
parser.add_argument('--tblk', '--target-block', type=int, required=True, metavar="<dec>",
help="Target key block number")
dsttype_group = parser.add_mutually_exclusive_group()
dsttype_group.add_argument('--ta', '--tA', action='store_true', help="Target A key (default)")
dsttype_group.add_argument('--tb', '--tB', action='store_true', help="Target B key")
return parser
def from_nt_level_code_to_str(self, nt_level):
if nt_level == 0:
return 'StaticNested'
if nt_level == 1:
return 'Nested'
if nt_level == 2:
return 'HardNested'
def recover_a_key(self, block_known, type_known, key_known, block_target, type_target) -> Union[str, None]:
"""
recover a key from key known.
:param block_known:
:param type_known:
:param key_known:
:param block_target:
:param type_target:
:return:
"""
# check nt level, we can run static or nested auto...
nt_level = self.cmd.mf1_detect_prng()
print(f" - NT vulnerable: {CY}{ self.from_nt_level_code_to_str(nt_level) }{C0}")
if nt_level == 2:
print(" [!] HardNested has not been implemented yet.")
return None
# acquire
if nt_level == 0: # It's a staticnested tag?
nt_uid_obj = self.cmd.mf1_static_nested_acquire(
block_known, type_known, key_known, block_target, type_target)
cmd_param = f"{nt_uid_obj['uid']} {int(type_target)}"
for nt_item in nt_uid_obj['nts']:
cmd_param += f" {nt_item['nt']} {nt_item['nt_enc']}"
tool_name = "staticnested"
else:
dist_obj = self.cmd.mf1_detect_nt_dist(block_known, type_known, key_known)
nt_obj = self.cmd.mf1_nested_acquire(block_known, type_known, key_known, block_target, type_target)
# create cmd
cmd_param = f"{dist_obj['uid']} {dist_obj['dist']}"
for nt_item in nt_obj:
cmd_param += f" {nt_item['nt']} {nt_item['nt_enc']} {nt_item['par']}"
tool_name = "nested"
# Cross-platform compatibility
if sys.platform == "win32":
cmd_recover = f"{tool_name}.exe {cmd_param}"
else:
cmd_recover = f"./{tool_name} {cmd_param}"
print(f" Executing {cmd_recover}")
# start a decrypt process
process = self.sub_process(cmd_recover)
# wait end
while process.is_running():
msg = f" [ Time elapsed {process.get_time_distance()/1000:#.1f}s ]\r"
print(msg, end="")
time.sleep(0.1)
# clear \r
print()
if process.get_ret_code() == 0:
output_str = process.get_output_sync()
key_list = []
for line in output_str.split('\n'):
sea_obj = re.search(r"([a-fA-F0-9]{12})", line)
if sea_obj is not None:
key_list.append(sea_obj[1])
# Here you have to verify the password first, and then get the one that is successfully verified
# If there is no verified password, it means that the recovery failed, you can try again
print(f" - [{len(key_list)} candidate key(s) found ]")
for key in key_list:
key_bytes = bytearray.fromhex(key)
if self.cmd.mf1_auth_one_key_block(block_target, type_target, key_bytes):
return key
else:
# No keys recover, and no errors.
return None
def on_exec(self, args: argparse.Namespace):
block_known = args.blk
# default to A
type_known = MfcKeyType.B if args.b else MfcKeyType.A
key_known: str = args.key
if not re.match(r"^[a-fA-F0-9]{12}$", key_known):
print("key must include 12 HEX symbols")
return
key_known_bytes = bytes.fromhex(key_known)
block_target = args.tblk
# default to A
type_target = MfcKeyType.B if args.tb else MfcKeyType.A
if block_known == block_target and type_known == type_target:
print(f"{CR}Target key already known{C0}")
return
print(f" - {C0}Nested recover one key running...{C0}")
key = self.recover_a_key(block_known, type_known, key_known_bytes, block_target, type_target)
if key is None:
print(f"{CY}No key found, you can retry.{C0}")
else:
print(f" - Block {block_target} Type {type_target.name} Key Found: {CG}{key}{C0}")
return
@hf_mf.command('darkside')
class HFMFDarkside(ReaderRequiredUnit):
def __init__(self):
super().__init__()
self.darkside_list = []
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = 'Mifare Classic darkside recover key'
return parser
def recover_key(self, block_target, type_target):
"""
Execute darkside acquisition and decryption.
:param block_target:
:param type_target:
:return:
"""
first_recover = True
retry_count = 0
while retry_count < 0xFF:
darkside_resp = self.cmd.mf1_darkside_acquire(block_target, type_target, first_recover, 30)
first_recover = False # not first run.
if darkside_resp[0] != MifareClassicDarksideStatus.OK:
print(f"Darkside error: {MifareClassicDarksideStatus(darkside_resp[0])}")
break
darkside_obj = darkside_resp[1]
if darkside_obj['par'] != 0: # NXP tag workaround.
self.darkside_list.clear()
self.darkside_list.append(darkside_obj)
recover_params = f"{darkside_obj['uid']}"
for darkside_item in self.darkside_list:
recover_params += f" {darkside_item['nt1']} {darkside_item['ks1']} {darkside_item['par']}"
recover_params += f" {darkside_item['nr']} {darkside_item['ar']}"
if sys.platform == "win32":
cmd_recover = f"darkside.exe {recover_params}"
else:
cmd_recover = f"./darkside {recover_params}"
# subprocess.run(cmd_recover, cwd=os.path.abspath("../bin/"), shell=True)
# print(f" Executing {cmd_recover}")
# start a decrypt process
process = self.sub_process(cmd_recover)
# wait end
process.wait_process()
# get output
output_str = process.get_output_sync()
if 'key not found' in output_str:
print(f" - No key found, retrying({retry_count})...")
retry_count += 1
continue # retry
else:
key_list = []
for line in output_str.split('\n'):
sea_obj = re.search(r"([a-fA-F0-9]{12})", line)
if sea_obj is not None:
key_list.append(sea_obj[1])
# auth key
for key in key_list:
key_bytes = bytearray.fromhex(key)
if self.cmd.mf1_auth_one_key_block(block_target, type_target, key_bytes):
return key
return None
def on_exec(self, args: argparse.Namespace):
key = self.recover_key(0x03, MfcKeyType.A)
if key is not None:
print(f" - Key Found: {key}")
else:
print(" - Key recover fail.")
return
@hf_mf.command('fchk')
class HFMFFCHK(ReaderRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
mifare_type_group = parser.add_mutually_exclusive_group()
mifare_type_group.add_argument('--mini', help='MIFARE Classic Mini / S20', action='store_const', dest='maxSectors', const=5)
mifare_type_group.add_argument('--1k', help='MIFARE Classic 1k / S50 (default)', action='store_const', dest='maxSectors', const=16)
mifare_type_group.add_argument('--2k', help='MIFARE Classic/Plus 2k', action='store_const', dest='maxSectors', const=32)
mifare_type_group.add_argument('--4k', help='MIFARE Classic 4k / S70', action='store_const', dest='maxSectors', const=40)
parser.add_argument(dest='keys', help='Key (as hex[12] format)', metavar='<hex>', type=str, nargs='*')
parser.add_argument('--key', dest='import_key', type=argparse.FileType('rb'), help='Read keys from .key format file')
parser.add_argument('--dic', dest='import_dic', type=argparse.FileType('r', encoding='utf8'), help='Read keys from .dic format file')
parser.add_argument('--export-key', type=argparse.FileType('wb'), help=f'Export result as .key format, file will be {CR}OVERWRITTEN{C0} if exists')
parser.add_argument('--export-dic', type=argparse.FileType('w', encoding='utf8'), help=f'Export result as .dic format, file will be {CR}OVERWRITTEN{C0} if exists')
parser.add_argument('-m', '--mask', help='Which sectorKey to be skip, 1 bit per sectorKey. `0b1` represent to skip to check. (in hex[20] format)', type=str, default='00000000000000000000', metavar='<hex>')
parser.set_defaults(maxSectors=16)
return parser
def check_keys(self, mask: bytearray, keys: list[bytes], chunkSize=20):
sectorKeys = dict()
for i in range(0, len(keys), chunkSize):
# print("mask = {}".format(mask.hex(sep=' ', bytes_per_sep=1)))
chunkKeys = keys[i:i+chunkSize]
print(f' - progress of checking keys... {CY}{i}{C0} / {len(keys)} ({CY}{100 * i / len(keys):.1f}{C0} %)')
resp = self.cmd.mf1_check_keys_of_sectors(mask, chunkKeys)
# print(resp)
if resp["status"] != Status.HF_TAG_OK:
print(f' - check interrupted, reason: {CR}{str(Status(resp["status"]))}{C0}')
break
elif 'sectorKeys' not in resp:
print(f' - check interrupted, reason: {CG}All sectorKey is found or masked{C0}')
break
for j in range(10):
mask[j] |= resp['found'][j]
sectorKeys.update(resp['sectorKeys'])
return sectorKeys
def on_exec(self, args: argparse.Namespace):
# print(args)
keys = set()
# keys from args
for key in args.keys:
if not re.match(r'^[a-fA-F0-9]{12}$', key):
print(f' - {CR}Key should in hex[12] format, invalid key is ignored{C0}, key = "{key}"')
continue
keys.add(bytes.fromhex(key))
# read keys from key format file
if args.import_key is not None:
if not load_key_file(args.import_key, keys):
return
if args.import_dic is not None:
if not load_dic_file(args.import_dic, keys):
return
if len(keys) == 0:
print(f' - {CR}No keys{C0}')
return
print(f" - loaded {CG}{len(keys)}{C0} keys")
# mask
if not re.match(r'^[a-fA-F0-9]{1,20}$', args.mask):
print(f' - {CR}mask should in hex[20] format{C0}, mask = "{args.mask}"')
return
mask = bytearray.fromhex(f'{args.mask:0<20}')
for i in range(args.maxSectors, 40):
mask[i // 4] |= 3 << (6 - i % 4 * 2)
# check keys
startedAt = datetime.now()
sectorKeys = self.check_keys(mask, list(keys))
endedAt = datetime.now()
duration = endedAt - startedAt
print(f" - elapsed time: {CY}{duration.total_seconds():.3f}s{C0}")
if args.export_key is not None:
unknownkey = bytes(6)
for sectorNo in range(args.maxSectors):
args.export_key.write(sectorKeys.get(2 * sectorNo, unknownkey))
args.export_key.write(sectorKeys.get(2 * sectorNo + 1, unknownkey))
print(f" - result exported to: {CG}{args.export_key.name}{C0} (as .key format)")
if args.export_dic is not None:
uniq_result = set(sectorKeys.values())
for key in uniq_result:
args.export_dic.write(key.hex().upper() + '\n')
print(f" - result exported to: {CG}{args.export_dic.name}{C0} (as .dic format)")
# print sectorKeys
print(f"\n - {CG}result of key checking:{C0}\n")
print("-----+-----+--------------+---+--------------+----")
print(" Sec | Blk | key A |res| key B |res ")
print("-----+-----+--------------+---+--------------+----")
for sectorNo in range(args.maxSectors):
blk = (sectorNo * 4 + 3) if sectorNo < 32 else (sectorNo * 16 - 369)
keyA = sectorKeys.get(2 * sectorNo, None)
keyA = f"{CG}{keyA.hex().upper()}{C0} | {CG}1{C0}" if keyA else f"{CR}------------{C0} | {CR}0{C0}"
keyB = sectorKeys.get(2 * sectorNo + 1, None)
keyB = f"{CG}{keyB.hex().upper()}{C0} | {CG}1{C0}" if keyB else f"{CR}------------{C0} | {CR}0{C0}"
print(f" {CY}{sectorNo:03d}{C0} | {blk:03d} | {keyA} | {keyB} ")
print("-----+-----+--------------+---+--------------+----")
print(f"( {CR}0{C0}: Failed, {CG}1{C0}: Success )\n\n")
@hf_mf.command('rdbl')