-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpn532_cli_unit.py
More file actions
2321 lines (2114 loc) · 80.4 KB
/
pn532_cli_unit.py
File metadata and controls
2321 lines (2114 loc) · 80.4 KB
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 json
import threading
import struct
from unit.calc import str_to_bytes
from unit.calc import is_hex
from unit.preset import FactoryPreset
from unit.mifare_classic import get_block_size_by_sector, get_block_index_by_sector, is_trailer_block
from multiprocessing import Pool, cpu_count
from typing import Union
from pathlib import Path
from platform import uname
from datetime import datetime
from pn532_enum import MfcKeyType, MifareCommand
from pn532_utils import CLITree
from pn532_utils import ArgumentParserNoExit, ArgsParserError, CG, CR, C0, CY, CM
import pn532_com
import pn532_cmd
# 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",
}
block_size_dict = {
0x08: 64,
0x09: 20,
0x18: 256,
0x19: 128,
}
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}"
)
root = CLITree(root=True)
hw = root.subgroup("hw", "Hardware-related commands")
hw_mode = hw.subgroup("mode", "Mode-related commands")
hf = root.subgroup("hf", "High-frequency commands")
hf_14a = hf.subgroup("14a", "ISO 14443-A commands")
hf_mf = hf.subgroup("mf", "MIFARE Classic commands")
hf_mfu = hf.subgroup("mfu", "MIFARE Ultralight commands")
hf_sniff = hf.subgroup("sniff", "Sniffer commands")
hf_14b = hf.subgroup("14b", "ISO 14443-B commands")
hf_15 = hf.subgroup("15", "ISO 15693 commands")
lf = root.subgroup("lf", "Low Frequency commands")
lf_em = lf.subgroup("em", "EM commands")
lf_em_410x = lf_em.subgroup("410x", "EM410x commands")
ntag = root.subgroup("ntag", "NTAG commands")
class BaseCLIUnit:
def __init__(self):
# new a device command transfer and receiver instance(Send cmd and receive response)
self._device_com: Union[pn532_com.Pn532Com, None] = None
self._device_cmd: Union[pn532_cmd.Pn532CMD, None] = None
@property
def device_com(self) -> pn532_com.Pn532Com:
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 = pn532_cmd.Pn532CMD(self._device_com)
@property
def cmd(self) -> pn532_cmd.Pn532CMD:
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):
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:
if not self.device_com.is_support_cmd(self.__class__.__name__):
print(
f"{CR}{self.__class__.__name__} not support by {self.device_com.get_device_name()}{C0}"
)
return False
return True
else:
print("Please connect to pn532 device first(use 'hw connect').")
return False
class MF1AuthArgsUnit(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.add_argument(
"--blk",
"--block",
type=int,
required=False,
default=0,
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", action="store_true", help="Known key is A key (default)"
)
type_group.add_argument("-b", action="store_true", help="Known key is B key")
parser.add_argument(
"-k",
"--key",
type=str,
required=False,
default="FFFFFFFFFFFF",
metavar="<hex>",
help="Mifare Sector key (12 HEX symbols)",
)
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 MF1WriteBlockArgsUnit(MF1AuthArgsUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = super().args_parser()
parser.add_argument(
"-d", "--data", type=str, required=False, help="32 HEX symbols to write"
)
return parser
def get_param(self, args):
param = super().get_param(args)
param.data = bytearray.fromhex(args.data)
return param
@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")
@hw_mode.command("r")
class HWModeReader(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set device to reader mode"
return parser
def on_exec(self, args: argparse.Namespace):
self.device_com.set_work_mode()
print("Switch to { Tag Reader } mode successfully.")
@hw_mode.command("e")
class HWModeEmulator(DeviceRequiredUnit):
# support -type m14b1k, 15693, em4100 and -slot 1-8
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set device to emulator mode"
parser.add_argument(
"-t",
"--type",
default=1,
type=int,
required=False,
help="1 - 4B1K, 3 - 15693, 4 - EM4100",
)
parser.add_argument(
"-s", "--slot", default=1, type=int, help="Emulator slot(1-8)"
)
return parser
def on_exec(self, args: argparse.Namespace):
type = args.type
slot = args.slot
self.device_com.set_work_mode(2, type, slot - 1)
print("Switch to { Emulator } mode successfully.")
@hw_mode.command("s")
class HWModeSniffer(DeviceRequiredUnit):
# support -type for 14a with tag, 14a without tag, 15
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set device to sniffer mode"
parser.add_argument(
"-t",
"--type",
default=0,
type=int,
required=False,
help="0 - Without tag, 1 - With tag",
)
return parser
def on_exec(self, args: argparse.Namespace):
self.device_com.set_work_mode(3, 1, args.type)
print("Switch to { Sniffer } mode successfully.")
@hw.command("raw")
class HWRaw(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Send raw data to device"
parser.add_argument(
"-d",
"--data",
type=str,
required=False,
help="Hex data to send",
default="00",
)
return parser
def on_exec(self, args: argparse.Namespace):
if args.data is None:
print("usage: hw raw [-h] [-d DATA]")
print("hw raw: error: the following arguments are required: -d")
return
data = args.data
if not re.match(r"^[0-9a-fA-F]+$", data):
print("Data must be a HEX string")
return
if len(data) % 2 != 0:
data = "0" + data
data_bytes = bytes.fromhex(data)
resp = self.device_com.send_raw(data_bytes)
print(f"Response: {' '.join(f'{byte:02X}' for byte in resp)}")
@hf_14a.command("scan")
class HF14AScan(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Scan 14a tag, and print basic information"
return parser
def sak_info(self, data_tag):
int_sak = data_tag["sak"]
if int_sak in type_id_SAK_dict:
print(f"- Guessed type(s) from SAK: {type_id_SAK_dict[int_sak]}")
def scan(self):
resp = self.cmd.hf_14a_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()}")
self.sak_info(data_tag)
if "ats" in data_tag and len(data_tag["ats"]) > 0:
print(f"- ATS: {data_tag['ats'].hex().upper()}")
else:
print("ISO14443-A Tag no found")
def on_exec(self, args: argparse.Namespace):
self.scan()
@hf_14a.command("raw")
class HF14ARaw(DeviceRequiredUnit):
def bool_to_bit(self, value):
return 1 if value else 0
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.description = "Send iso1444a raw command"
parser.add_argument(
"-a",
"--activate-rf",
help="Active signal field ON without select",
action="store_true",
default=False,
)
parser.add_argument(
"-s",
"--select-tag",
help="Active signal field ON with select",
action="store_true",
default=False,
)
parser.add_argument(
"-d", type=str, metavar="<hex>", required=False, help="Hex data to be sent"
)
parser.add_argument(
"-b",
type=int,
metavar="<dec>",
help="Number of bits to send. Useful for send partial byte",
)
parser.add_argument(
"-c",
"--crc",
help="Calculate and append CRC",
action="store_true",
default=False,
)
parser.add_argument(
"-r",
"--no-response",
help="Do not read response",
action="store_true",
default=False,
)
parser.add_argument(
"-cc",
"--crc-clear",
help="Verify and clear CRC of received data",
action="store_true",
default=False,
)
parser.add_argument(
"-k",
"--keep-rf",
help="Keep signal field ON after receive",
action="store_true",
default=False,
)
parser.add_argument(
"-t", type=int, metavar="<dec>", help="Timeout in ms", default=100
)
parser.epilog = (
parser.epilog
) = """
examples/notes:
hf 14a raw -a -k -b 7 -d 40
hf 14a raw -d 43 -k
hf 14a raw -d 3000 -c
hf 14a raw -sc -d 6000
"""
return parser
def on_exec(self, args: argparse.Namespace):
if args.d is None:
print("usage: hf 14a raw [-h] -d <hex> [-c] [-sc] [-r]")
print("hf 14a raw: error: the following arguments are required: -d")
return
options = {
"activate_rf_field": self.bool_to_bit(args.activate_rf),
"wait_response": self.bool_to_bit(not args.no_response),
"append_crc": self.bool_to_bit(args.crc),
"auto_select": self.bool_to_bit(args.select_tag),
"keep_rf_field": self.bool_to_bit(args.keep_rf),
"check_response_crc": self.bool_to_bit(args.crc_clear),
# 'auto_type3_select': self.bool_to_bit(args.type3-select-tag),
}
data: str = args.d
if data is not None:
data = data.replace(" ", "")
if re.match(r"^[0-9a-fA-F]+$", data):
if len(data) % 2 != 0:
print(
f" [!] {CR}The length of the data must be an integer multiple of 2.{C0}"
)
return
else:
data_bytes = bytes.fromhex(data)
else:
print(f" [!] {CR}The data must be a HEX string{C0}")
return
else:
data_bytes = []
if args.b is not None and args.crc:
print(f" [!] {CR}--bits and --crc are mutually exclusive{C0}")
return
resp = self.cmd.hf14a_raw(options, args.t, data_bytes, args.b)
if len(resp) > 0:
print(
" - "
+ " ".join(
[hex(byte).replace("0x", "").rjust(2, "0").upper() for byte in resp]
)
)
else:
print(f" [*] {CY}No response{C0}")
@hf_15.command("scan")
class HF15Scan(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Scan ISO15693 tag, and print basic information"
return parser
def scan(self):
resp = self.cmd.hf_15_scan()
if resp is not None:
for data_tag in resp:
print(f"- UID: {data_tag['uid'].upper()}")
else:
print("ISO15693 Tag no found")
def on_exec(self, args: argparse.Namespace):
self.scan()
@hf_15.command("info")
class HF15Info(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Get ISO15693 tag information"
return parser
def on_exec(self, args: argparse.Namespace):
resp = self.cmd.hf_15_scan()
if resp is None:
print("ISO15693 Tag no found")
return
resp = self.cmd.hf_15_info()
if resp is not None:
print(f"UID: {resp['uid'].hex().upper()}")
print(f"AFI: 0x{resp['afi']:02X}")
print(f"DSFID: 0x{resp['dsfid']:02X}")
print(f"IC Reference: 0x{resp['ic_reference']:02X}")
print(f"Block size: {resp['block_size']}")
else:
print("Get ISO15693 tag information failed")
@hf_15.command("rdbl")
class HF15Rdbl(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Read block data from ISO15693 tag"
parser.add_argument(
"-b",
"--block",
type=int,
required=False,
default=0,
metavar="<dec>",
help="Block to read",
)
return parser
def on_exec(self, args: argparse.Namespace):
resp = self.cmd.hf_15_scan()
if resp is None:
print("ISO15693 Tag no found")
return
block = args.block
resp = self.cmd.hf_15_read_block(block)
if resp is not None:
print(f"Block {block}: {resp.hex().upper()}")
else:
print(f"Read block {block} failed")
@hf_15.command("wrbl")
class HF15Wrbl(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Write block data to ISO15693 tag"
parser.add_argument(
"-b",
"--block",
type=int,
required=False,
default=0,
metavar="<dec>",
help="Block to write",
)
parser.add_argument(
"-d",
"--data",
type=str,
required=False,
default="00000000",
metavar="<hex>",
help="Data to write (4 bytes)",
)
return parser
def on_exec(self, args: argparse.Namespace):
resp = self.cmd.hf_15_scan()
if resp is None:
print("ISO15693 Tag no found")
return
block = args.block
data = args.data
if not re.match(r"^[a-fA-F0-9]{8}$", data):
print("Data must be 4 bytes hex")
return
resp = self.cmd.hf_15_write_block(block, bytes.fromhex(data))
print(f"Write block {block} {CY}{'Success' if resp else 'Fail'}{C0}")
# scan, get info, and read block. if add --json, save as json, if add --bin, save as bin
@hf_15.command("dump")
class HF15Dump(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Dump ISO15693 tag data"
parser.add_argument(
"--json", action="store_true", help="Save to json file"
)
parser.add_argument(
"--bin", action="store_true", help="Save to bin file"
)
return parser
def on_exec(self, args: argparse.Namespace):
resp = self.cmd.hf_15_scan()
if resp is None:
print("ISO15693 Tag no found")
return
resp_info = self.cmd.hf_15_info()
if resp_info is None:
print("Get ISO15693 tag information failed")
return
else:
print(f"UID: {resp_info['uid'].hex().upper()}")
print(f"AFI: 0x{resp_info['afi']:02X}")
print(f"DSFID: 0x{resp_info['dsfid']:02X}")
print(f"IC Reference: 0x{resp_info['ic_reference']:02X}")
print(f"Block size: {resp_info['block_size']}")
data = {}
for block in range(0, resp_info["block_size"]):
resp = self.cmd.hf_15_read_block(block)
if resp is not None:
data[block] = resp.hex().upper()
print(f"Block {block}: {data[block]}")
else:
data[block]
print(f"Block {block}: Failed to read")
if args.json:
dump_data = {}
dump_data["Card"] = resp_info
dump_data["blocks"] = data
file_name = "hf_15_" + resp_info['uid'].hex().upper() + ".json"
with open(file_name, "w") as f:
json.dump(dump_data, f)
print("Dump saved to " + file_name)
if args.bin:
file_name = "hf_15_" + resp_info['uid'].hex().upper() + ".bin"
with open(file_name, "wb") as f:
for block in range(0, len(data)):
if block in data:
f.write(data[block].encode())
else:
f.write(b'\x00\x00\x00\x00')
print("Dump saved to " + file_name)
@hf_15.command("raw")
class HF15Raw(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.description = "Send iso15693 raw command"
parser.add_argument(
"-d", type=str, metavar="<hex>", required=False, help="Hex data to be sent"
)
# add crc
parser.add_argument(
"-c",
"--crc",
help="Calculate and append CRC",
action="store_true",
default=False,
),
parser.add_argument(
"-r",
"--no-response",
help="Do not read response",
action="store_true",
default=True,
),
# add select_tag
parser.add_argument(
"-sc",
"--select-tag",
help="Active signal field ON with select",
action="store_true",
default=False,
)
return parser
def on_exec(self, args: argparse.Namespace):
if args.d is None:
print("usage: hf 15 raw [-h] -d <hex> [-c] [-sc] [-r]")
print("hf 15 raw: error: the following arguments are required: -d")
return
data: str = args.d
if data is not None:
data = data.replace(" ", "")
if re.match(r"^[0-9a-fA-F]+$", data):
if len(data) % 2 != 0:
print(
f" [!] {CR}The length of the data must be an integer multiple of 2.{C0}"
)
return
else:
data_bytes = bytes.fromhex(data)
else:
print(f" [!] {CR}The data must be a HEX string{C0}")
return
else:
data_bytes = []
options = {"append_crc": 0, "no_check_response": 0}
if args.select_tag:
options["select_tag"] = 1
if args.crc:
options["append_crc"] = 1
if args.no_response:
options["no_check_response"] = 1
resp = self.cmd.hf_15_raw(options, data=data_bytes)
if args.no_response:
print(f" [*] {CY}No response{C0}")
else:
print(
" - "
+ " ".join(
[
hex(byte).replace("0x", "").rjust(2, "0").upper()
for byte in resp.data
]
)
)
@hf_15.command("gen1uid")
class HF15Gen1Uid(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set UID of Gen1 Magic ISO15693 tag"
parser.add_argument(
"-u",
type=str,
required=False,
help="UID to set (8 bytes, start with E0)",
)
return parser
def on_exec(self, args: argparse.Namespace):
if args.u is None:
print("usage: hf 15 gen1uid [-h] -u <hex>")
print("hf 15 gen1uid: error: the following arguments are required: -u")
return
uid = args.u
if not re.match(r"^[a-fA-F0-9]{16}$", uid):
print("UID must be 8 bytes hex")
return
if uid[0:2].lower() != "e0":
print("UID must start with E0")
return
resp_scan = self.cmd.hf_15_scan()
if resp_scan is None:
print("ISO15693 Tag no found")
return
resp_info = self.cmd.hf_15_info()
block_size = resp_info["block_size"]
resp = self.cmd.hf_15_set_gen1_uid(bytes.fromhex(uid), block_size)
print(f"Set UID to {uid} {CY}{'Success' if resp else 'Fail'}{C0}")
@hf_15.command("gen2uid")
class HF15Gen2Uid(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set UID of Gen2 Magic ISO15693 tag"
parser.add_argument(
"-u",
type=str,
required=False,
help="UID to set (8 bytes, start with E0)",
)
return parser
def on_exec(self, args: argparse.Namespace):
if args.u is None:
print("usage: hf 15 gen2uid [-h] -u <hex>")
print("hf 15 gen2uid: error: the following arguments are required: -u")
return
resp_scan = self.cmd.hf_15_scan()
if resp_scan is None:
print("ISO15693 Tag no found")
return
uid = args.u
if not re.match(r"^[a-fA-F0-9]{16}$", uid):
print("UID must be 8 bytes hex")
return
if uid[0:2].lower() != "e0":
print("UID must start with E0")
return
resp = self.cmd.hf_15_set_gen2_uid(bytes.fromhex(uid))
print(f"Set UID to {uid} {CY}{'Success' if resp else 'Fail'}{C0}")
@hf_15.command("gen2config")
class HF15Gen2Config(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set block size of Gen2 Magic ISO15693 tag"
parser.add_argument(
"-s",
"--size",
default=64,
type=int,
required=True,
metavar="<dec>",
help="Block size to set",
)
parser.add_argument(
"-a",
"--afi",
default="00",
type=str,
required=False,
metavar="<hex>",
help="AFI on hex value",
)
parser.add_argument(
"-d",
"--dsfid",
default="00",
type=str,
required=False,
metavar="<hex>",
help="DSFID on hex value",
)
parser.add_argument(
"-i",
"--ic",
default="00",
type=str,
required=False,
metavar="<hex>",
help="IC on hex value",
)
return parser
def on_exec(self, args: argparse.Namespace):
resp_scan = self.cmd.hf_15_scan()
if resp_scan is None:
print("ISO15693 Tag no found")
return
# block size must between 4 to 256
if args.size < 0 or args.size > 256:
print("Block size must between 0 to 256")
return
if args.afi is not None:
if not re.match(r"^[a-fA-F0-9]{2}$", args.afi):
print("AFI must be 1 byte hex")
return
args.afi = int(args.afi, 16) if args.afi is not None else 0
if args.dsfid is not None:
if not re.match(r"^[a-fA-F0-9]{2}$", args.dsfid):
print("DSFID must be 1 byte hex")
return
args.dsfid = int(args.dsfid, 16) if args.dsfid is not None else 0
if args.ic is not None:
if not re.match(r"^[a-fA-F0-9]{2}$", args.ic):
print("IC must be 1 byte hex")
return
args.ic = int(args.ic, 16) if args.ic is not None else 0
resp = self.cmd.hf_15_set_gen2_config(args.size, args.afi, args.dsfid, args.ic)
print(f"Config Gen2 Magic ISO15693 tag {CY}{'Success' if resp else 'Fail'}{C0}")
@hf_15.command("eSetUid")
class HF15ESetUid(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set UID of ISO15693 Emulation"
parser.add_argument(
"-u",
type=str,
metavar="<hex>",
required=False,
help="UID to set (8 bytes)",
)
parser.add_argument(
"-s", "--slot", default=1, type=int, help="Emulator slot(1-8)"
)
return parser
def on_exec(self, args: argparse.Namespace):
if args.u is None:
print("usage: hf 15 eSetUid [-h] -u <hex> [-s SLOT]")
print("hf 15 eSetUid: error: the following arguments are required: -u")
return
uid = args.u
if not re.match(r"^[a-fA-F0-9]{16}$", uid):
print("UID must be 8 bytes hex")
return
# if not start with e0 or E0
if uid[0:2].lower() != "e0":
print("UID must start with E0")
return
resp = self.cmd.hf_15_eset_uid(args.slot - 1, bytes.fromhex(uid))
print(
f"Set Slot {args.slot} UID to {uid} {CY}{'Success' if resp else 'Fail'}{C0}"
)
@hf_15.command("eSetBlock")
class HF15ESetBlock(DeviceRequiredUnit):
# add parameter -b <hex> to set block data(4 bytes)
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set block data of ISO15693 Emulation"
parser.add_argument(
"-b",
type=int,
metavar="<dec>",
help="Block to set",
)
parser.add_argument(
"-s", "--slot", default=1, type=int, help="Emulator slot(1-8)"
)
# add data block
parser.add_argument(
"-d",
"--data",
metavar="<hex>",
type=str,
required=False,
help="Data block (4 bytes)",
)
return parser
def on_exec(self, args: argparse.Namespace):
block = args.data
if not re.match(r"^[a-fA-F0-9]{8}$", block):
print("Block must be 4 bytes hex")
return
resp = self.cmd.hf_15_eset_block(args.slot - 1, args.b, bytes.fromhex(block))
print(
f"Set Slot {args.slot} block {args.b} to {block} {CY}{'Success' if resp else 'Fail'}{C0}"
)
@hf_15.command("eSetDump")
class HF15ESetDump(DeviceRequiredUnit):
def args_parser(self) -> ArgumentParserNoExit:
parser = ArgumentParserNoExit()
parser.description = "Set dump data of ISO15693 Emulation"
parser.add_argument(
"--json",
type=str,
required=False,
metavar="<file>",
help="JSON file to load dump data",
)
parser.add_argument(
"--bin",
type=str,
required=False,
metavar="<file>",
help="BIN file to load dump data",