-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrfid.py
executable file
·626 lines (468 loc) · 17.3 KB
/
rfid.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
#!/usr/bin/env python
import time
import smartcard
from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver
from smartcard.util import toHexString, toASCIIString, toASCIIBytes
from smartcard.ATR import ATR
from smartcard.Exceptions import SmartcardException, NoReadersException, CardConnectionException, NoCardException
# Try to use pyscard exceptions so it's easier to catch
class UnsupportedReaderException(SmartcardException):
pass
class ReaderException(SmartcardException):
pass
class PN532Exception(SmartcardException):
pass
class SAMException(SmartcardException):
pass
DEBUG = True
DEBUG = False
"""
Sources:
http://www.proxmark.org/files/Documents/NFC/ACS_API_ACR122.pdf
http://www.acs.com.hk/drivers/chi/API-ACR122USAM-2.01.pdf
http://www.nxp.com/documents/user_manual/141520.pdf
https://code.google.com/p/nfcip-java/source/browse/trunk/nfcip-java/doc/ACR122_PN53x.txt
https://code.google.com/p/understand/wiki/SmartCards
http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-340%201st%20edition%20December%202002.pdf
pyscard's Session() is a bit broken, so we define our own interface here.
You can either poll Pcsc.readers(), or call Pcsc.reader(), which defaults to the first.
"""
class Pcsc(object):
@classmethod
def wrapreader(self, reader):
if reader.name.startswith('ACS'):
return AcsReader(reader)
return LowLevelChipReader(reader)
@classmethod
def readers(self):
readers = list(map(self.wrapreader, smartcard.System.readers()))
return readers
@classmethod
def reader(self, readernum=None):
readers = self.readers()
if not readers:
raise NoReadersException()
if readernum is None:
readers = [r for r in readers if not isinstance(r, UnsupportedReader)]
readernum = 0
return readers[readernum]
class PcscReader(object):
def __init__(self, reader):
self.reader = reader
self.name = reader.name
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.name)
def open(self):
self.conn = self.reader.createConnection()
self.conn.connect()
if DEBUG:
observer = ConsoleCardConnectionObserver()
self.conn.addObserver(observer)
def close(self):
# PCSCCardConnection.__del__ calls disconnect, but
# let's do it in case someone's taken a reference
self.conn.disconnect()
self.conn = None
self.reader = None
def __enter__(self):
self.open()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
class UnsupportedReader(PcscReader):
def open(self):
raise UnsupportedReaderException(self.name)
def close(self):
pass
class APDU(object):
def __init__(self, cls, ins, p1=0, p2=0, lc=None, data=None, le=None):
self.cls = cls
self.ins = ins
self.p1 = p1
self.p2 = p2
if data is None:
data = []
self.data = data
if lc is None:
lc = len(data)
self.lc = lc
self.le = []
if le is not None:
self.le = [le]
@property
def bytes(self):
if len(self.data) > 255:
raise ValueError('APDU payload too long')
return [self.cls, self.ins, self.p1, self.p2, self.lc] + self.data + self.le
def __iter__(self):
return iter(self.bytes)
@classmethod
def frombytes(self, bytes):
args = bytes[:5]
lc = bytes[4]
if 5 + lc != len(bytes):
raise ValueError('Length %s is incorrect for APDU length %s' % (5 + lc, len(bytes)))
args.append(bytes[5:])
return APDU(*args)
class BasicChipReader(PcscReader):
def open(self):
PcscReader.open(self)
# We could pass this into connect, but this is clearer
self.atr = ATR(self.conn.getATR())
if DEBUG:
print('ATR: %s' % self.atr)
try:
self.atr.dump()
except TypeError as e:
print('Exception %r dumping ATR' % e)
if self.atr.isT1Supported():
# will raise NoCardException if no card is present
resp, sw1, sw2 = self.send_to_tag(None, APDU(0xff, 0xca), protocol=smartcard.scard.SCARD_PROTOCOL_T1)
uid = ''.join('%02x' % ord(c) for c in resp)
else:
uid = None
self.tag = Tag(self, None, None, None)
self.tag.uid = uid
self.tag.ats = self.atr.bytes
@property
def tags(self):
return [self.tag]
def send_to_tag(self, tag, apdu):
if tag is not None:
raise ValueError('Multiple tags not supported')
resp, sw1, sw2 = self.conn.transmit(list(apdu))
if sw1 == 0x61: # More data
apdu2 = APDU(0, 0xc0, lc=sw2)
resp, sw1, sw2 = self.conn.transmit(list(apdu2))
return [sw1, sw2] + resp
class HResultException(Exception):
pass
def HResult(vals):
if not isinstance(vals, (tuple, list)):
vals = (vals,)
hresult = vals[0]
if hresult < 0:
raise HResultException('hResult was 0x%08x' % hresult)
if len(vals) == 1:
return None
if len(vals) == 2:
return vals[1]
return vals[1:]
class LowLevelChipReader(PcscReader):
"""
Some cards (or just Gemalto readers?) fails with "656e Error, changed" unless you do this
"""
def open(self):
self.hcontext = HResult(smartcard.scard.SCardEstablishContext(smartcard.scard.SCARD_SCOPE_USER))
self.hcard, dwActiveProtocol = HResult(smartcard.scard.SCardConnect(
self.hcontext, self.name, smartcard.scard.SCARD_SHARE_EXCLUSIVE, smartcard.scard.SCARD_PROTOCOL_T0))
self.tag = Tag(self, None, None, None)
self.tag.uid = None
self.tag.ats = []
def close(self):
HResult(smartcard.scard.SCardDisconnect(self.hcard, smartcard.scard.SCARD_LEAVE_CARD))
@property
def tags(self):
return [self.tag]
def send_to_tag(self, tag, apdu):
if tag is not None:
raise ValueError('Multiple tags not supported')
HResult(smartcard.scard.SCardBeginTransaction(self.hcard))
if DEBUG:
print('> %s' % toHexString(list(apdu)))
response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu)))
if DEBUG:
print('< %s' % toHexString(response))
sw1, sw2 = response[0:2]
if sw1 == 0x61: # More data
apdu2 = APDU(0, 0xc0, lc=sw2)
if DEBUG:
print('> %s' % toHexString(list(apdu2)))
response = HResult(smartcard.scard.SCardTransmit(self.hcard, smartcard.scard.SCARD_PCI_T0, list(apdu2)))
if DEBUG:
print('< %s' % toHexString(response))
HResult(smartcard.scard.SCardEndTransaction(self.hcard, smartcard.scard.SCARD_LEAVE_CARD))
return response
class AcsReader(PcscReader):
def __init__(self, reader):
PcscReader.__init__(self, reader)
self.pn532 = Pn532(self)
def open(self):
PcscReader.open(self)
# We could pass this into connect, but this is clearer
self.atr = ATR(self.conn.getATR())
if DEBUG:
print('ATR: %s' % self.atr)
self.atr.dump()
if not self.atr.isT0Supported():
self.close()
raise CardConnectionException('Reader reports T0 protocol not supported')
if DEBUG:
print('Firmware version %s' % self.firmware_version())
self.pn532.set_retries(0, 0, 0)
def send(self, apdu):
resp, sw1, sw2 = self.conn.transmit(list(apdu))
return resp, sw1, sw2
@property
def tags(self):
return self.pn532.scan()
def firmware_version(self):
apdu = APDU(0xff, 0, 0x48)
resp, sw1, sw2 = self.send(apdu)
return toASCIIString(resp + [sw1, sw2])
def led_buzzer(self, red=None, green=None, blink=None, buzzer=None):
led_ctl = 0
if red is not None:
led_ctl |= 0x4
if not isinstance(red, (list, tuple)):
red = False, False, red
initial_led, blink_led, final_led = red
led_ctl |= 0x1 if final_led else 0
led_ctl |= 0x10 if initial_led else 0
led_ctl |= 0x40 if blink_led else 0
if green is not None:
led_ctl |= 0x8
if not isinstance(green, (list, tuple)):
green = False, False, green
initial_led, blink_led, final_led = green
led_ctl |= 0x2 if final_led else 0
led_ctl |= 0x20 if initial_led else 0
led_ctl |= 0x80 if blink_led else 0
initial_delay, blink_delay, blink_count = 0, 0, 0
if blink:
initial_delay, blink_delay, blink_count = blink
initial_delay = initial_delay / 100
blink_delay = blink_delay / 100
buzz_ctl = 0
if buzzer:
initial_buzz, blink_buzz = buzzer
buzz_ctl = 0
buzz_ctl |= 0x1 if initial_buzz else 0
buzz_ctl |= 0x2 if blink_buzz else 0
extra = [initial_delay, blink_delay, blink_count, buzz_ctl]
apdu = APDU(0xff, 0, 0x40, led_ctl, data=extra)
resp, sw1, sw2 = self.send(apdu)
if sw1 != 0x90:
raise ReaderException('Error setting LEDs %02x%02x' % (sw1, sw2))
red, green = list(map(bool, [sw2 & 0x1, sw2 & 0x2]))
return red, green
def red_on(self):
self.led_buzzer(red=True)
def red_off(self):
self.led_buzzer(red=False)
def green_on(self):
self.led_buzzer(green=True)
def green_off(self):
self.led_buzzer(green=False)
def leds_off(self):
self.led_buzzer(red=False, green=False)
def denied(self):
self.led_buzzer(
red=[True, False, False],
green=[True, True, False],
blink=[500, 300, 3],
buzzer=[True, False]
)
def send_to_pn532(self, apdu):
apdu = APDU(0xff, 0, 0, data=apdu)
resp, sw1, sw2 = self.send(apdu)
if sw1 != 0x61:
raise ReaderException('Error communicating with PN532: %02x%02x' % (sw1, sw2))
apdu = APDU(0xff, 0xc0, lc=sw2)
resp, sw1, sw2 = self.send(apdu)
return resp, sw1, sw2
def send_to_sam(self, p1, p2, lc):
if (self.atr.TS, self.atr.T0) == (0x3b, 0):
raise SAMException('SAM not reported present')
resp, sw1, sw2 = self.send(APDU(0x80, 0x14, p1, p2, lc))
if (sw1, sw2) != (0x90, 0):
raise ReaderException('Error communicating with SAM: %02x%02x' % (sw1, sw2))
return resp
def sam_serial(self):
return self.send_to_sam(0, 0, 8)
def sam_id(self):
return self.send_to_sam(4, 0, 6)
def sam_os(self):
resp = self.send_to_sam(6, 0, 8)
os = resp[:4]
rest = resp[4:]
return toASCIIString(os), rest
class Pn532(object):
BITRATES = [106, 212, 424]
MODULATIONS = {
0x00: 'Mifare/ISO14443/ISO18092 106kbps',
0x01: 'ISO18092 active',
0x02: 'Jewel',
0x10: 'FeliCa/ISO18092 passive 212/424kbps',
}
ENCODINGS = ['Type A', 'FeliCa 212kbps', 'FeliCa 424kbps', 'Type B', 'Type 1']
FIRMWARE_FEATURES = ['Type A', 'Type B', 'ISO18092']
def __init__(self, reader):
self.reader = reader
def send(self, cc, data=None):
if data is None:
data = []
tfi = 0xd4 # host to controller
resp, sw1, sw2 = self.reader.send_to_pn532([tfi, cc] + data)
tfi2, cc2 = resp[:2]
if (tfi2, cc2) != (0xd5, cc + 1):
raise PN532Exception('Error returned: %02x%02x' % (tfi2, cc2))
return resp[2:]
def test(self, test, params):
# INTERESTING
resp = self.send(0, [test] + params)
return resp
def firmware(self):
resp = self.send(0x2)
ic, ver, rev, support = resp
icname = {0x32: 'PN532'}.get(ic, 'Unknown %02x' % ic)
features = []
for n, f in enumerate(self.FIRMWARE_FEATURES):
if support & (1 << n):
features.append(f)
info = dict(
chip = icname,
version = (ver, rev),
features = features,
)
return info
def status(self):
resp = self.send(0x4)
r = iter(resp)
err = next(r)
field = next(r)
nbtg = next(r)
tags = []
for tag in range(nbtg):
tags.append(dict(
logical_id = next(r),
rx_kbps = self.BITRATES[next(r)],
tx_kbps = self.BITRATES[next(r)],
modulation = self.MODULATIONS[next(r)],
))
sam = next(r)
status = dict(
error = err,
field = bool(field),
tags = tags,
)
return status
# TODO: registers and GPIO
def set_params(self, nad=False, cid=False, atr_res=True, rats=True, picc=True, nopreamble=False):
flags = 0
flags |= 0x1 if nad else 0
flags |= 0x2 if cid else 0
flags |= 0x4 if atr_res else 0
flags |= 0x10 if rats else 0 # try to use ISO14443-4
flags |= 0x20 if picc else 0
flags |= 0x40 if nopreamble else 0
return self.send(0x12, [flags])
def shutdown(self, wakeup, interrupt=None):
args = [wakeup]
if interrupt is not None:
args.append(interrupt)
return self.send(0x16, args)
def set_radio(self, item, data):
return self.send(0x32, [item] + data)
def power_on(self):
return self.set_radio(1, [1])
def power_off(self):
return self.set_radio(1, [0])
def set_retries(self, atr_req=0xff, psl_req=1, passive=0xff):
return self.set_radio(5, [atr_req, psl_req, passive])
def send_to_tag(self, tag, data):
resp = self.send(0x40, [tag] + list(data))
if resp[0] != 0:
raise PN532Exception('Unexpected status %02x' % resp[0])
return resp[1:]
def halt_tag(self):
resp = self.send(0x44, [1])
def scan(self, max_tags=1, encoding='Type A', data=None):
# TODO: try max_tags=2
if data is None:
data = []
if encoding == 'Type B':
data = [0]
elif encoding.startswith('FeliCa'):
# This is suggested in the datasheet, but doesn't seem to work
data = [0x00, 0xff, 0xff, 0x00, 0x00]
brty = self.ENCODINGS.index(encoding)
resp = self.send(0x4a, [max_tags, brty] + data)
r = iter(resp)
nbtg = next(r)
if not nbtg:
raise NoCardException('No cards found', hresult=-1)
tags = []
if brty == 0:
for i in range(nbtg):
tagtype = 0x10
tags.append(self.parse_tag(tagtype, r))
else:
raise NotImplementedError()
return tags
def autoscan(self, polls=1, ms=150, types=[0x20, 0x23, 0x4, 0x10, 0x11, 0x12]):
if polls is None:
polls = 0xff
period = ms / 150
resp = self.send(0x60, [polls, period] + types)
r = iter(resp)
nbtg = next(r)
if not nbtg:
raise NoCardException('No cards found', hresult=-1)
tags = []
for i in range(nbtg):
tagtype = next(r)
length = next(r)
taginfo = [next(r) for i in range(length)]
tags.append(self.parse_tag(tagtype, iter(taginfo)))
return tags
# Move to tag.py
def parse_tag(self, tagtype, r):
target = next(r)
if tagtype in (0x10, 0x20):
sens_res = (next(r) << 8) + next(r)
sel_res = next(r)
uidlen = next(r)
uid = ''.join('%02x' % next(r) for i in range(uidlen))
tag = Tag(self, target, sens_res, sel_res)
tag.uid = uid
if tagtype == 0x20:
atslen = next(r)
ats = [next(r) for i in range(atslen - 1)]
tag.ats = ats
elif tagtype == 0x23:
atqb = [next(r) for i in range(12)]
arlen = next(r)
ar = [next(r) for i in range(arlen)]
elif tagtype == 0x11:
prlen = next(r)
pol_res = [next(r) for i in range(prlen - 1)]
p = iter(pol_res)
resp_code = next(p)
uid = ''.join('%02x' % next(p) for i in range(8))
print(uid)
elif tagtype == 0x4:
atqa = (next(r) << 8) + next(r)
uid = ''.join('%02x' % next(r) for i in range(4))
return tag
from .tag import Tag
if __name__ == '__main__':
with Pcsc.reader() as reader:
#reader.denied()
#time.sleep(1)
#print toASCIIString(reader.sam_id())
#print toHexString(reader.sam_serial())
#print reader.sam_os()
if isinstance(reader, AcsReader):
p = reader.pn532
#print p.firmware()
#p.shutdown(0)
#p.set_params(rats=False)
#tags = p.autoscan()
#print len(tags)
#print p.status()
#p.halt_tag()
for tag in reader.tags:
tag = tags[0]
print('UID: %s' % tag.uid)
print('ATR: %s' % toHexString(tag.ats))