This repository was archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagtool.py
More file actions
634 lines (550 loc) · 23.6 KB
/
tagtool.py
File metadata and controls
634 lines (550 loc) · 23.6 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
#!/usr/bin/env python
# -*- coding: latin-1 -*-
# -----------------------------------------------------------------------------
# Copyright 2010, 2017 Stephen Tiedemann <stephen.tiedemann@gmail.com>
#
# Licensed under the EUPL, Version 1.1 or - as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# You may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# https://joinup.ec.europa.eu/software/page/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
# -----------------------------------------------------------------------------
from __future__ import print_function
import argparse
import binascii
import logging
import hashlib
import struct
import ndef
import hmac
import cli
import sys
if sys.version_info.major < 3:
sys.exit("This script requires Python 3")
log = logging.getLogger('main')
def parse_version(string):
try:
major_version, minor_version = map(int, string.split('.'))
except (ValueError, AttributeError):
msg = "%r is not a version string, expecting <int>.<int>"
raise argparse.ArgumentTypeError(msg % string)
if major_version < 0 or major_version > 15:
msg = "major version %r is out of range, expecting 0...15"
raise argparse.ArgumentTypeError(msg % major_version)
if minor_version < 0 or minor_version > 15:
msg = "minor version %r is out of range, expecting 0...15"
raise argparse.ArgumentTypeError(msg % minor_version)
return major_version << 4 | minor_version
def parse_uint8(string):
for base in (10, 16):
try:
value = int(string, base)
if 0 <= value <= 0xff:
return value
except ValueError:
pass
else:
msg = "%r can not be read as an 8-bit unsigned integer"
raise argparse.ArgumentTypeError(msg % string)
def parse_uint16(string):
for base in (10, 16):
try:
value = int(string, base)
if 0 <= value <= 0xffff:
return value
except ValueError:
pass
else:
msg = "%r can not be read as a 16-bit unsigned integer"
raise argparse.ArgumentTypeError(msg % string)
def parse_uint24(string):
for base in (10, 16):
try:
value = int(string, base)
if 0 <= value <= 0xffffff:
return value
except ValueError:
pass
else:
msg = "%r can not be read as a 24-bit unsigned integer"
raise argparse.ArgumentTypeError(msg % string)
#
# command parsers
#
def add_show_parser(parser):
pass
def add_dump_parser(parser):
parser.add_argument(
"-o", dest="output", metavar="FILE",
type=argparse.FileType('wb'), default="-",
help="save ndef to FILE (writes binary data)")
def add_load_parser(parser):
parser.add_argument(
"input", metavar="FILE", type=argparse.FileType('rb'),
help="ndef data file ('-' reads from stdin)")
def add_format_parser(parser):
parser.add_argument(
"--wipe", metavar="BYTE", type=int, default=None,
help="overwrite all data with BYTE")
parser.add_argument(
"--version", metavar="x.y", type=parse_version,
help="ndef mapping version, default is latest")
subparsers = parser.add_subparsers(
title="tag type subcommands", metavar='{tt1,tt2,tt3}',
dest="tagtype", help="tag type specific arguments")
subparsers.required = True
subparsers.add_parser('any')
description = (
"The tag type specific arguments are intended to give full "
"control over the format creation. Arguments provided here "
"are written to the tag regardless of whether they will "
"create a valid configuration. It is thus possible to create "
"formats that may confuse a reader, as useful for testing.")
add_format_tt1_parser(subparsers.add_parser(
'tt1', description=description))
add_format_tt2_parser(subparsers.add_parser(
'tt2', description=description))
add_format_tt3_parser(subparsers.add_parser(
'tt3', description=description))
def add_format_tt1_parser(parser):
parser.add_argument(
"--magic", metavar="BYTE", type=parse_uint8,
help="value to use as ndef magic byte")
parser.add_argument(
"--ver", metavar="x.y", type=parse_version,
help="ndef mapping major and minor version")
parser.add_argument(
"--tms", metavar="BYTE", type=parse_uint8,
help="tag memory size, 8*(tms+1)")
parser.add_argument(
"--rwa", metavar="BYTE", type=parse_uint8,
help="read write access byte")
def add_format_tt2_parser(parser):
pass
def add_format_tt3_parser(parser):
parser.add_argument(
"--ver", metavar="x.y", type=parse_version,
help="ndef mapping major and minor version")
parser.add_argument(
"--nbr", metavar="BYTE", type=parse_uint8,
help="number of blocks that can be written at once")
parser.add_argument(
"--nbw", metavar="BYTE", type=parse_uint8,
help="number of blocks that can be read at once")
parser.add_argument(
"--max", metavar="SHORT", type=parse_uint16,
help="maximum number of blocks (nmaxb)")
parser.add_argument(
"--rfu", metavar="BYTE", type=parse_uint8,
help="value to set for reserved bytes")
parser.add_argument(
"--wf", metavar="BYTE", type=parse_uint8,
help="write-flag attribute value")
parser.add_argument(
"--rw", metavar="BYTE", type=parse_uint8,
help="read-write flag attribute value")
parser.add_argument(
"--len", metavar="INT", type=parse_uint24,
help="ndef length attribute value")
parser.add_argument(
"--crc", metavar="INT", type=parse_uint16,
help="checksum attribute value")
def add_emulate_parser(parser):
parser.description = "Emulate an ndef tag."
parser.add_argument(
"-l", "--loop", action="store_true",
help="continue (restart) after tag release")
parser.add_argument(
"-k", "--keep", action="store_true",
help="keep tag memory (when --loop is set)")
parser.add_argument(
"-s", dest="size", type=int, default="1024",
help="minimum ndef data area size (default: %(default)s)")
parser.add_argument(
"-p", dest="preserve", metavar="FILE",
type=argparse.FileType('wb'),
help="preserve tag memory when released")
parser.add_argument(
"input", metavar="FILE", type=argparse.FileType('rb'),
nargs="?", default=None,
help="ndef message to serve ('-' reads from stdin)")
subparsers = parser.add_subparsers(title="Tag Types", dest="tagtype")
subparsers.required = True
add_emulate_tt3_parser(subparsers.add_parser(
'tt3', help='emulate a type 3 tag'))
def add_emulate_tt3_parser(parser):
parser.add_argument(
"--idm", metavar="HEX", default="03FEFFE011223344",
help="manufacture identifier (default: %(default)s)")
parser.add_argument(
"--pmm", metavar="HEX", default="01E0000000FFFF00",
help="manufacture parameter (default: %(default)s)")
parser.add_argument(
"--sys", "--sc", metavar="HEX", default="12FC",
help="system code (default: %(default)s)")
parser.add_argument(
"--bitrate", choices=["212", "424"], default="212",
help="bitrate to listen (default: %(default)s)")
parser.add_argument(
"--ver", metavar="x.y", type=parse_version, default="1.0",
help="ndef mapping version number (default: %(default)s)")
parser.add_argument(
"--nbr", metavar="INT", type=int, default=1,
help="max read blocks at once (default: %(default)s)")
parser.add_argument(
"--nbw", metavar="INT", type=int, default=1,
help="max write blocks at once (default: %(default)s)")
parser.add_argument(
"--max", metavar="INT", type=int,
help="maximum number of blocks (default: computed)")
parser.add_argument(
"--rfu", metavar="INT", type=int, default=0,
help="value to set for reserved bytes (default: %(default)s)")
parser.add_argument(
"--wf", metavar="INT", type=int, default=0,
help="write-flag attribute value (default: %(default)s)")
parser.add_argument(
"--rw", metavar="INT", type=int, default=1,
help="read-write flag attribute value (default: %(default)s)")
parser.add_argument(
"--crc", metavar="INT", type=int,
help="checksum attribute value (default: computed)")
def add_protect_parser(parser):
parser.add_argument(
"-p", dest="password",
help="protect with password if possible")
parser.add_argument(
"--from", metavar="BLOCK", dest="protect_from", type=int,
default=0,
help="first block to protect (default: %(default)s)")
parser.add_argument(
"--unreadable", action="store_true",
help="make tag unreadable without password")
class TagTool(cli.CommandLineInterface):
def __init__(self):
parser = ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="")
parser.add_argument(
"-p", dest="authenticate", metavar="PASSWORD",
help="unlock with password if supported")
subparsers = parser.add_subparsers(
title="commands", dest="command")
subparsers.required = True
add_show_parser(subparsers.add_parser(
'show', help='pretty print ndef data'))
add_dump_parser(subparsers.add_parser(
'dump', help='read ndef data from tag'))
add_load_parser(subparsers.add_parser(
'load', help='write ndef data to tag'))
add_format_parser(subparsers.add_parser(
'format', help='format ndef tag'))
add_protect_parser(subparsers.add_parser(
'protect', help='write protect a tag'))
add_emulate_parser(subparsers.add_parser(
'emulate', help='emulate an ndef tag'))
self.rdwr_commands = {"show": self.show_tag,
"dump": self.dump_tag,
"load": self.load_tag,
"format": self.format_tag,
"protect": self.protect_tag, }
super(TagTool, self).__init__(parser, groups="rdwr card dbg clf")
def on_rdwr_startup(self, targets):
if self.options.command in self.rdwr_commands.keys():
print("** waiting for a tag **", file=sys.stderr)
return targets
def on_rdwr_connect(self, tag):
if self.options.authenticate is not None:
if len(self.options.authenticate) > 0:
key, msg = self.options.authenticate, tag.identifier
password = hmac.new(key, msg, hashlib.sha256).digest()
else:
password = "" # use factory default password
result = tag.authenticate(password)
if result is False:
print("I'm sorry, but authentication failed.")
return False
if result is None:
print(tag)
print("I don't know how to authenticate this tag.")
return False
self.rdwr_commands[self.options.command](tag)
return self.options.wait or self.options.loop
def on_card_startup(self, target):
if self.options.command == "emulate":
target = self.prepare_tag(target)
print("** waiting for a reader **", file=sys.stderr)
return target
def on_card_connect(self, tag):
log.info("tag activated")
return self.emulate_tag_start(tag)
def on_card_release(self, tag):
log.info("tag released")
self.emulate_tag_stop(tag)
return True
def show_tag(self, tag):
print(tag)
if tag.ndef:
print("NDEF Capabilities:")
print(" readable = %s" % ("no", "yes")[tag.ndef.is_readable])
print(" writeable = %s" % ("no", "yes")[tag.ndef.is_writeable])
print(" capacity = %d byte" % tag.ndef.capacity)
print(" message = %d byte" % tag.ndef.length)
if tag.ndef.length > 0:
print("NDEF Message:")
for i, record in enumerate(tag.ndef.records):
print("record", i + 1)
print(" type =", repr(record.type))
print(" name =", repr(record.name))
print(" data =", repr(record.data))
if self.options.verbose:
print("Memory Dump:")
print(' ' + '\n '.join(tag.dump()))
def dump_tag(self, tag):
if tag.ndef:
data = tag.ndef.octets
if self.options.output.name == "<stdout>":
self.options.output.write(binascii.hexlify(data).decode())
if self.options.loop:
self.options.output.write('\n')
else:
self.options.output.flush()
else:
self.options.output.write(data)
def load_tag(self, tag):
try:
self.options.data
except AttributeError:
try:
self.options.data = self.options.input.buffer.read()
except AttributeError:
self.options.data = self.options.input.read()
try:
self.options.data = binascii.unhexlify(self.options.data)
except binascii.Error:
pass
if tag.ndef is None:
print("This is not an NDEF Tag.")
return
if not tag.ndef.is_writeable:
print("This Tag is not writeable.")
return
if self.options.data == tag.ndef.octets:
print("The Tag already contains the message to write.")
return
if len(self.options.data) > tag.ndef.capacity:
print("The new message exceeds the Tag's capacity.")
return
if tag.ndef.length > 0:
print("Old NDEF Message:")
for i, record in enumerate(tag.ndef.records):
print("record", i + 1)
print(" type =", repr(record.type))
print(" name =", repr(record.name))
print(" data =", repr(record.data))
tag.ndef.records = list(ndef.message_decoder(self.options.data))
if tag.ndef.length > 0:
print("New NDEF Message:")
for i, record in enumerate(tag.ndef.records):
print("record", i + 1)
print(" type =", repr(record.type))
print(" name =", repr(record.name))
print(" data =", repr(record.data))
def format_tag(self, tag):
if not self.options.tagtype == "any":
if not self.options.tagtype[2] == tag.type[4]:
print("This is not a Type {0} Tag but you said so."
.format(self.options.tagtype[2]))
return
if self.options.version is None:
version = {'Type1Tag': 0x12, 'Type2Tag': 0x12,
'Type3Tag': 0x10, 'Type4Tag': 0x30}[tag.type]
else:
version = self.options.version
formatted = tag.format(version=version, wipe=self.options.wipe)
if formatted is True:
{'tt1': self.format_tt1_tag, 'tt2': self.format_tt2_tag,
'tt3': self.format_tt3_tag, 'tt4': self.format_tt4_tag,
'any': lambda t: None}[self.options.tagtype](tag)
print("Formatted %s" % tag)
if tag.ndef:
print(" readable = %s" % ("no", "yes")[tag.ndef.is_readable])
print(" writable = %s" % ("no", "yes")[tag.ndef.is_writeable])
print(" capacity = %d byte" % tag.ndef.capacity)
print(" message = %d byte" % tag.ndef.length)
elif formatted is None:
print("Sorry, this tag can not be formatted.")
else:
print("Sorry, I could not format this tag.")
def format_tt1_tag(self, tag):
if self.options.magic is not None:
tag.write_byte(8, self.options.magic)
if self.options.ver is not None:
tag.write_byte(9, self.options.ver)
if self.options.tms is not None:
tag.write_byte(10, self.options.tms)
if self.options.rwa is not None:
tag.write_byte(11, self.options.rwa)
def format_tt2_tag(self, tag):
pass
def format_tt3_tag(self, tag):
attribute_data = tag.read_from_ndef_service(0)
if self.options.ver is not None:
attribute_data[0] = self.options.ver
if self.options.nbr is not None:
attribute_data[1] = self.options.nbr
if self.options.nbw is not None:
attribute_data[2] = self.options.nbw
if self.options.max is not None:
attribute_data[3:5] = struct.pack(">H", self.options.max)
if self.options.rfu is not None:
attribute_data[5:9] = 4 * [self.options.rfu]
if self.options.wf is not None:
attribute_data[9] = self.options.wf
if self.options.rw is not None:
attribute_data[10] = self.options.rw
if self.options.len is not None:
attribute_data[11:14] = struct.pack(">I", self.options.len)[1:]
if self.options.crc is not None:
attribute_data[14:16] = struct.pack(">H", self.options.crc)
else:
checksum = sum(attribute_data[:14])
attribute_data[14:16] = struct.pack(">H", checksum)
tag.write_to_ndef_service(attribute_data, 0)
def format_tt4_tag(self, tag):
pass
def protect_tag(self, tag):
print(tag)
if self.options.password is not None:
if len(self.options.password) >= 8:
print("generating diversified key from password")
key, msg = self.options.password, tag.identifier
password = hmac.new(key, msg, hashlib.sha256).digest()
elif len(self.options.password) == 0:
print("using factory default key for password")
password = ""
else:
print("A password should be at least 8 characters.")
return
else:
password = None
result = tag.protect(password, self.options.unreadable,
self.options.protect_from)
if result is True:
print("This tag is now protected.")
elif result is False:
print("Failed to protect this tag.")
elif result is None:
print("Sorry, but this tag can not be protected.")
def prepare_tag(self, target):
if self.options.tagtype == "tt3":
return self.prepare_tt3_tag(target)
def prepare_tt3_tag(self, target):
if self.options.size % 16 != 0:
self.options.size = ((self.options.size + 15) // 16) * 16
log.warning("tt3 ndef data area size rounded to {0}"
.format(self.options.size))
try:
self.options.data
except AttributeError:
if self.options.input:
try:
self.options.data = self.options.input.buffer.read()
except AttributeError:
self.options.data = self.options.input.read()
try:
self.options.data = binascii.unhexlify(self.options.data)
except binascii.Error:
pass
else:
self.options.data = ""
if not (hasattr(self.options, "tt3_data") and self.options.keep):
if self.options.input:
ndef_data_size = len(self.options.data)
ndef_area_size = ((ndef_data_size + 15) // 16) * 16
ndef_area_size = max(ndef_area_size, self.options.size)
ndef_data_area = bytearray(self.options.data) \
+ bytearray(ndef_area_size - ndef_data_size)
else:
ndef_data_area = bytearray(self.options.size)
# create attribute data
attribute_data = bytearray(16)
attribute_data[0] = self.options.ver
attribute_data[1] = self.options.nbr
attribute_data[2] = self.options.nbw
if self.options.max is None:
nmaxb = len(ndef_data_area) // 16
else:
nmaxb = self.options.max
attribute_data[3:5] = struct.pack(">H", nmaxb)
attribute_data[5:9] = 4 * [self.options.rfu]
attribute_data[9] = self.options.wf
attribute_data[10:14] = struct.pack(">I", len(self.options.data))
attribute_data[10] = self.options.rw
attribute_data[14:16] = struct.pack(">H", sum(attribute_data[:14]))
self.options.tt3_data = attribute_data + ndef_data_area
idm = bytes.fromhex(self.options.idm)
pmm = bytes.fromhex(self.options.pmm)
_sys = bytes.fromhex(self.options.sys)
target.brty = self.options.bitrate + "F"
target.sensf_res = b"\x01" + idm + pmm + _sys
return target
def emulate_tag_start(self, tag):
if self.options.tagtype == "tt3":
return self.emulate_tt3_tag(tag)
def emulate_tag_stop(self, tag):
if self.options.preserve:
self.options.preserve.seek(0)
self.options.preserve.write(self.options.tt3_data)
log.info("wrote tag memory to file '{0}'"
.format(self.options.preserve.name))
def emulate_tt3_tag(self, tag):
def ndef_read(block_number, rb, re):
log.debug("tt3 read block #{0}".format(block_number))
if block_number < len(self.options.tt3_data) / 16:
first, last = block_number * 16, (block_number + 1) * 16
block_data = self.options.tt3_data[first:last]
return block_data
def ndef_write(block_number, block_data, wb, we):
log.debug("tt3 write block #{0}".format(block_number))
if block_number < len(self.options.tt3_data) / 16:
first, last = block_number * 16, (block_number + 1) * 16
self.options.tt3_data[first:last] = block_data
return True
tag.add_service(0x0009, ndef_read, ndef_write)
tag.add_service(0x000B, ndef_read, lambda: False)
return True
class ArgparseError(SystemExit):
def __init__(self, prog, message):
super(ArgparseError, self).__init__(2, prog, message)
def __str__(self):
return '{0}: {1}'.format(self.args[1], self.args[2])
class ArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ArgparseError(self.prog, message)
if __name__ == '__main__':
try:
TagTool().run()
except ArgparseError as e:
_prog = e.args[1].split()
else:
sys.exit(0)
if len(_prog) == 1:
sys.argv = sys.argv + ['show']
elif _prog[-1] == "format":
sys.argv = sys.argv + ['any']
try:
TagTool().run()
except ArgparseError as e:
print(e, file=sys.stderr)