-
Notifications
You must be signed in to change notification settings - Fork 227
/
RFIDIOt.py.orig
2226 lines (2209 loc) · 75.2 KB
/
RFIDIOt.py.orig
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
# RFIDIOt.py - RFID IO tools for python
# -*- coding: iso-8859-15 -*-
#
# Adam Laurie <[email protected]>
# http://rfidiot.org/
#
# This code is copyright (c) Adam Laurie, 2006,7,8,9 All rights reserved.
# For non-commercial use only, the following terms apply - for all other
# uses, please contact the author:
#
# This code is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# use Psyco compiler to speed things up if available
try:
import psyco
psyco.profile(0.01)
psyco.full()
except ImportError:
pass
import os
import sys
import random
import string
import time
from Crypto.Hash import SHA
from Crypto.Cipher import DES3
from Crypto.Cipher import DES
from operator import *
import pynfc
import signal
try:
import smartcard, smartcard.CardRequest
IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE = smartcard.scard.SCARD_CTL_CODE(1)
except:
print '*** Warning - no pyscard installed or pcscd not running'
MASK_CCITT = 0x1021 # CRC-CCITT mask (ISO 3309, used in X25, HDLC)
MASK_11785 = 0x8408
MASK_CRC16 = 0xA001 # CRC16 mask (used in ARC files)
DEBUG= False
#DEBUG= True
NoInit= False
NFCReader= None
class rfidiot:
"RFIDIOt - RFID I/O tools - http://rfidiot.org"
# local imports
from iso3166 import ISO3166CountryCodesAlpha
from iso3166 import ISO3166CountryCodes
#
# open reader port
#
def __init__(self,readernum,reader,port,baud,to,debug,noinit,nfcreader):
global NoInit
global DEBUG
self.readertype= reader
self.readersubtype= reader
readernum= int(readernum)
DEBUG= debug
NoInit= noinit
NFCReader= nfcreader
if not NoInit:
if self.readertype == self.READER_PCSC:
try:
self.pcsc_protocol= smartcard.scard.SCARD_PROTOCOL_T1
except:
print 'Could not find PCSC daemon, try with option -n if you don\'t have a reader'
os._exit(True)
# select the reader specified
try:
self.pcsc= smartcard.System.readers()
except:
print 'Could not find PCSC daemon, try with option -n if you don\'t have a reader'
os._exit(True)
if readernum >= len(self.pcsc):
print 'There is no such reader #%i, PCSC sees only %i reader(s)' % (readernum, len(self.pcsc))
os._exit(True)
try:
self.readername= self.pcsc[readernum].name
self.pcsc_connection= self.pcsc[readernum].createConnection()
# debug option will show APDU traffic
if DEBUG:
from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver
observer=ConsoleCardConnectionObserver()
self.pcsc_connection.addObserver( observer )
except:
print 'Could not create connection to %s' % self.readername
os._exit(True)
# determine PCSC subtype
if string.find(self.readername,'OMNIKEY') == 0:
self.readersubtype= self.READER_OMNIKEY
else:
if string.find(self.readername,'SDI010') == 0:
self.readersubtype= self.READER_SCM
else:
if string.find(self.readername,'ACS ACR 38U') == 0 or string.find(self.readername,'ACS ACR38U') == 0:
self.readersubtype= self.READER_ACS
self.pcsc_protocol= smartcard.scard.SCARD_PROTOCOL_T0
self.hcard = None
elif string.find(self.readername,'ACS ACR122U PICC') == 0:
self.readersubtype= self.READER_ACS
self.pcsc_protocol= smartcard.scard.SCARD_PROTOCOL_T1
self.hcard = None
else:
# default to Omnikey for now
self.readersubtype= self.READER_OMNIKEY
if DEBUG:
print 'Reader Subtype:',self.readersubtype
# create a connection
try:
self.pcsc_connection.connect()
except:
# card may be something like a HID PROX which only returns ATR and does not allow connect
hresult, hcontext = smartcard.scard.SCardEstablishContext( smartcard.scard.SCARD_SCOPE_USER )
if hresult != 0:
raise error, 'Failed to establish context: ' + smartcard.scard.SCardGetErrorMessage(hresult)
hresult, readers = smartcard.scard.SCardListReaders( hcontext, [] )
readerstates= [ (readers[readernum], smartcard.scard.SCARD_STATE_UNAWARE ) ]
hresult, newstates = smartcard.scard.SCardGetStatusChange( hcontext, 0, readerstates )
if self.readersubtype == self.READER_ACS and self.pcsc_protocol == smartcard.scard.SCARD_PROTOCOL_T1:
# SCARD_SHARE_SHARED if there is a PICC otherwise SCARD_SHARE_DIRECT
hresult, hcard, dwActiveProtocol = smartcard.scard.SCardConnect(
hcontext, readers[readernum], smartcard.scard.SCARD_SHARE_DIRECT, smartcard.scard.SCARD_PROTOCOL_T0 )
self.hcard = hcard
# Let's test if we can really use SCardControl, e.g. by sending a get_firmware_version APDU
apdu = [ 0xFF, 0x00, 0x48, 0x00, 0x00 ]
hresult, response = smartcard.scard.SCardControl( self.hcard, IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE, apdu )
if hresult != smartcard.scard.SCARD_S_SUCCESS:
print 'Failed to control: ' + smartcard.scard.SCardGetErrorMessage(hresult)
if hresult == smartcard.scard.SCARD_E_NOT_TRANSACTED:
print 'Did you set DRIVER_OPTION_CCID_EXCHANGE_AUTHORIZED in ifdDriverOptions in libccid_Info.plist?'
os._exit(True)
self.pcsc_atr= self.ListToHex(newstates[0][2])
pass
if self.readersubtype == self.READER_ACS:
self.acs_set_retry(to)
#libnfc device
elif self.readertype == self.READER_LIBNFC:
self.nfc = pynfc.NFC()
self.readername = self.nfc.LIBNFC_READER
elif self.readertype == self.READER_NONE:
self.readername = 'none'
else:
# frosch always starts at 9600 baud - need to add code to test for selected rate and
# switch if required.
try:
import serial
self.ser = serial.Serial(port, baud, timeout=to)
self.ser.readline()
self.ser.flushInput()
self.ser.flushOutput()
except:
print 'Could not open serial port %s' % port
os._exit(True)
#
# variables
#
# VERSION: RFIDIOt.py version number
# errorcode: 1 letter errorcode returned by the reader
#
# MIFAREdata: ASCII HEX representation of data block after successful read
# MIFAREbinary: data block converted back to binary
# MIFAREBLOCKLEN: constant ASCII HEX block length
# MIFAREVALUELEN: constant ASCII HEX value length
# MIFAREserialnumber: Unique ID (UID) of card
# MIFAREkeyA: KEYA from key block (will always be 000000000000)
# MIFAREkeyB: KEYB from key block
# MIFAREaccessconditions: access conditions field from Key Block
# MIFAREC1: Access conditions bitfield C1
# MIFAREC2: Access conditions bitfield C2
# MIFAREC3: Access conditions bitfield C3
# MIFAREblock0AC: Block 0 Access Conditions
# MIFAREblock1AC: Block 1 Access Conditions
# MIFAREblock2AC: Block 2 Access Conditions
# MIFAREblock3AC: Block 3 Access Conditions
# MIFAREACKB: Human readable Key Block Access Conditions
# MIFAREACDB: Human readable Data Block Access ConditionsA
#
# MRPmrzu: Machine Readable Passport - Machine Readable Zone - Upper
# MRPmrzl Machine Readable Passport - Machine Readable Zone - Lower
VERSION= '1.0c-beta'
# Reader types
READER_ACG= 0x01
READER_FROSCH= 0x02
READER_DEMOTAG= 0x03
READER_PCSC= 0x04
READER_OMNIKEY= 0x05
READER_SCM= 0x06
READER_ACS= 0x07
READER_LIBNFC = 0x08
READER_NONE = 0x09
# TAG related globals
errorcode= ''
binary= ''
data= ''
sel_res= ''
sens_res= ''
tagtype= ''
speed= ''
framesize= ''
uid= ''
MIFAREdata=''
MIFAREbinary=''
MIFAREBLOCKLEN=32
MIFAREVALUELEN=8
MIFAREserialnumber= ''
MIFAREcheckbyte= ''
MIFAREmanufacturerdata= ''
MIFAREkeyA= ''
MIFAREkeyB= ''
MIFAREaccessconditions= ''
MIFAREaccessconditionsuserbyte= ' '
MIFAREC1= 0
MIFAREC2= 0
MIFAREC3= 0
MIFAREblock0AC= ''
MIFAREblock1AC= ''
MIFAREblock2AC= ''
MIFAREblock3AC= ''
# PCSC uses 'External Authentication', whereby keys are stored in the reader and then presented to the card. They only need
# to be set up once per session, so login will store them in a global dictionary.
# PCSC_Keys= { key : keynum } where keynum is 0 - 31 as per OmniKey docs
PCSC_Keys= {}
# Static Globals
MIFAREACKB= {'000':'Write KeyA: KEYA, Read Access bits: KEYA, Write Access bits: NONE, Read KeyB: KEYA, Write KeyB: KEYA (KEYB readable)',\
'010':'Write KeyA: NONE, Read Access bits: KEYA, Write Access bits: NONE, Read KeyB: KEYA, Write KeyB: NONE (KEYB readable)',\
'100':'Write KeyA: KEYB, Read Access bits: KEYA/B, Write Access bits: NONE, Read KeyB: NONE, Write KeyB: KEYB',\
'110':'Write KeyA: NONE, Read Access bits: KEYA/B, Write Access bits: NONE, Read KeyB: NONE, Write KeyB: NONE',\
'001':'Write KeyA: KEYA, Read Access bits: KEYA, Write Access bits: KEYA, Read KeyB: KEYA, Write KeyB: KEYA (KEYB readable, transport configuration)',\
'011':'Write KeyA: KEYB, Read Access bits: KEYA/B, Write Access bits: KEYB, Read KeyB: NONE, Write KeyB: KEYB',\
'101':'Write KeyA: NONE, Read Access bits: KEYA/B, Write Access bits: KEYB, Read KeyB: NONE, Write KeyB: NONE',\
'111':'Write KeyA: NONE, Read Access bits: KEYA/B, Write Access bits: NONE, Read KeyB: NONE, Write KeyB: NONE'}
MIFAREACDB= {'000':'Read: KEYA/B, Write: KEYA/B, Increment: KEYA/B, Decrement/Transfer/Restore: KEYA/B (transport configuration)',\
'010':'Read: KEYA/B, Write: NONE, Increment: NONE, Decrement/Transfer/Restore: NONE',\
'100':'Read: KEYA/B, Write: KEYB, Increment: NONE, Decrement/Transfer/Restore: NONE',\
'110':'Read: KEYA/B, Write: KEYB, Increment: KEYB, Decrement/Transfer/Restore: KEYA/B',\
'001':'Read: KEYA/B, Write: NONE, Increment: NONE, Decrement/Transfer/Restore: KEYA/B',\
'011':'Read: KEYB, Write: KEYB, Increment: NONE, Decrement/Transfer/Restore: NONE',\
'101':'Read: KEYB, Write: NONE, Increment: NONE, Decrement/Transfer/Restore: NONE',\
'111':'Read: NONE, Write: NONE, Increment: NONE, Decrement/Transfer/Restore: NONE'}
LFXTags= {'U':'EM 4x02 (Unique)',\
'Z':'EM 4x05 (ISO FDX-B)',\
'T':'EM 4x50',\
'h':'Hitag 1 / Hitag S',\
'H':'Hitag 2',\
'Q':'Q5',\
'R':'TI-RFID Systems',\
'N':'No TAG present!'}
# number of data blocks for each tag type (including block 0)
LFXTagBlocks= {'U':0,\
'Z':0,\
'T':34,\
'h':64,\
'H':8,\
'Q':8,\
'R':18,\
'N':0}
ALL= 'all'
EM4x02= 'U'
EM4x05= 'Z'
Q5= 'Q'
HITAG1= 'h'
HITAG2= 'H'
HITAG2_TRANSPORT_RWD='4D494B52'
HITAG2_TRANSPORT_TAG='AA4854'
HITAG2_TRANSPORT_HIGH='4F4E'
HITAG2_PUBLIC_A= '02'
HITAG2_PUBLIC_B= '00'
HITAG2_PUBLIC_C= '04'
HITAG2_PASSWORD= '06'
HITAG2_CRYPTO= '0e'
ACG_FAIL= 'N'
# Mifare transort keys
MIFARE_TK= { 'AA' : 'A0A1A2A3A4A5',\
'BB' : 'B0B1B2B3B4B5',\
'FF' : 'FFFFFFFFFFFF'}
ISOTags= {'a':'ISO 14443 Type A ',\
'b':'ISO 14443 Type B ',\
'd':'ICODE UID ',\
'e':'ICODE EPC ',\
'i':'ICODE ',\
's':'SR176 ',\
'v':'ISO 15693 '}
ISOTagsA= {'t':'All Supported Tags'}
ISO15693= 'v'
# Manufacturer codes (Listed in ISO/IEC 7816-6)
ISO7816Manufacturer= { '00':'Not Specified',\
'01':'Motorola',\
'02':'ST Microelectronics',\
'03':'Hitachi, Ltd',\
'04':'Philips Semiconductors (NXP)',\
'05':'Infineon Technologies AG',\
'06':'Cylinc',\
'07':'Texas Instrument',\
'08':'Fujitsu Limited',\
'09':'Matsushita Electronics Corporation',\
'0a':'NEC',\
'0b':'Oki Electric Industry Co. Ltd',\
'0c':'Toshiba Corp.',\
'0d':'Mitsubishi Electric Corp.',\
'0e':'Samsung Electronics Co. Ltd',\
'0f':'Hyundai Electronics Industries Co. Ltd',\
'10':'LG-Semiconductors Co. Ltd',\
'12':'HID Corporation',\
'16':'EM Microelectronic-Marin SA',
}
ISOAPDU= {'ERASE BINARY':'0E',
'VERIFY':'20',
# Global Platform
'INITIALIZE_UPDATE':'50',
# GP end
'MANAGE_CHANNEL':'70',
'EXTERNAL_AUTHENTICATE':'82',
'GET_CHALLENGE':'84',
'INTERNAL_AUTHENTICATE':'88',
'SELECT_FILE':'A4',
#vonjeek start
'VONJEEK_SELECT_FILE':'A5',
'VONJEEK_UPDATE_BINARY':'A6',
'VONJEEK_SET_MRZ':'A7',
'VONJEEK_SET_BAC':'A8',
'VONJEEK_SET_DATASET':'AA',
#vonjeek end
# special for JCOP
'MIFARE_ACCESS':'AA',
'ATR_HIST':'AB',
'SET_RANDOM_UID':'AC',
# JCOP end
'READ_BINARY':'B0',
'READ_RECORD(S)':'B2',
'GET_RESPONSE':'C0',
'ENVELOPE':'C2',
'GET_DATA':'CA',
'WRITE_BINARY':'D0',
'WRITE_RECORD':'D2',
'UPDATE_BINARY':'D6',
'PUT_DATA':'DA',
'UPDATE_DATA':'DC',
'CREATE_FILE':'E0',
'APPEND_RECORD':'E2',
# Global Platform
'GET_STATUS':'F2',
# GP end
'READ_BALANCE':'4C',
'INIT_LOAD': '40',
'LOAD_CMD':'42',
'WRITE_MEMORY':'7A',
'READ_MEMORY':'78',
}
# some control parameters
ISO_7816_SELECT_BY_NAME= '04'
ISO_7816_SELECT_BY_EF= '02'
ISO_7816_OPTION_FIRST_OR_ONLY= '00'
ISO_7816_OPTION_NEXT_OCCURRENCE= '02'
# well known AIDs
AID_CARD_MANAGER= 'A000000003000000'
AID_MRTD= 'A0000002471001'
AID_JAVA_LANG= 'A0000000620001'
AID_JAVACARD_FRAMEWORK= 'A0000000620101'
AID_JAVACARD_SECURITY= 'A0000000620102'
AID_JAVARCARDX_CRYPTO= 'A0000000620201'
AID_FIPS_140_2= 'A000000167413001'
AID_JAVACARD_BIOMETRY= 'A0000001320001'
AID_SECURITY_DOMAIN= 'A0000000035350'
AID_PKCS_15= 'A000000063'
AID_JCOP_IDENTIFY= 'A000000167413000FF'
# Global Platform
CLA_GLOBAL_PLATFORM= '80'
GP_MAC_KEY= '404142434445464748494A4B4C4D4E4F'
GP_ENC_KEY= '404142434445464748494A4B4C4D4E4F'
GP_KEK_KEY= '404142434445464748494A4B4C4D4E4F'
GP_NO_ENCRYPTION= '00'
GP_C_MAC= '01'
GP_C_MAC_DECRYPTION= '02'
GP_SCP02= '02'
GP_REG_DATA= 'E3'
GP_REG_AID= '4F'
GP_REG_LCS= '9F70'
GP_REG_PRIV= 'C5'
GP_FILTER_ISD= '80'
GP_FILTER_ASSD= '40'
GP_FILTER_ELF= '20'
ISO_OK= '9000'
ISO_SECURE= '6982'
ISO_NOINFO= '6200'
ISO_SPEED= {'00':'106kBaud',\
'02':'212kBaud',\
'04':'424kBaud',\
'08':'848kBaud'}
ISO_FRAMESIZE= { '00':'16',\
'01':'24',\
'02':'32',\
'03':'40',\
'04':'48',\
'05':'64',\
'06':'96',\
'07':'128',\
'08':'256'}
ISO7816ErrorCodes= {
'61':'SW2 indicates the number of response bytes still available',
'6200':'No information given',
'6281':'Part of returned data may be corrupted',
'6282':'End of file/record reached before reading Le bytes',
'6283':'Selected file invalidated',
'6284':'FCI not formatted according to ISO7816-4 section 5.1.5',
'6300':'No information given',
'6301':'ACR: PN532 does not respond',
'6327':'ACR: Contacless Response invalid checksum',
'637F':'ACR: PN532 invalid Contactless Command',
'6381':'File filled up by the last write',
'6382':'Card Key not supported',
'6383':'Reader Key not supported',
'6384':'Plain transmission not supported',
'6385':'Secured Transmission not supported',
'6386':'Volatile memory not available',
'6387':'Non Volatile memory not available',
'6388':'Key number not valid',
'6389':'Key length is not correct',
'63C':'Counter provided by X (valued from 0 to 15) (exact meaning depending on the command)',
'64':'State of non-volatile memory unchanged (SW2=00, other values are RFU)',
'6400':'Card Execution error',
'6500':'No information given',
'6581':'Memory failure',
'66':'Reserved for security-related issues (not defined in this part of ISO/IEC 7816)',
'6700':'Wrong length',
'6800':'No information given',
'6881':'Logical channel not supported',
'6882':'Secure messaging not supported',
'6900':'No information given',
'6981':'Command incompatible with file structure',
'6982':'Security status not satisfied',
'6983':'Authentication method blocked',
'6984':'Referenced data invalidated',
'6985':'Conditions of use not satisfied',
'6986':'Command not allowed (no current EF)',
'6987':'Expected SM data objects missing',
'6988':'SM data objects incorrect',
'6A00':'No information given',
'6A80':'Incorrect parameters in the data field',
'6A81':'Function not supported',
'6A82':'File not found',
'6A83':'Record not found',
'6A84':'Not enough memory space in the file',
'6A85':'Lc inconsistent with TLV structure',
'6A86':'Incorrect parameters P1-P2',
'6A87':'Lc inconsistent with P1-P2',
'6A88':'Referenced data not found',
'6B00':'Wrong parameter(s) P1-P2',
'6C':'Wrong length Le: SW2 indicates the exact length',
'6D00':'Instruction code not supported or invalid',
'6E00':'Class not supported',
'6F00':'No precise diagnosis',
'9000':'No further qualification',
'ABCD':'RFIDIOt: Reader does not support this command',
'F':'Read error or Security status not satisfied',
'FFFB':'Mifare (JCOP) Block Out Of Range',
'FFFF':'Unspecified Mifare (JCOP) Error',
'N':'No precise diagnosis',
'PC00':'No TAG present!',
'PC01':'PCSC Communications Error',
'PN00': 'PN531 Communications Error',
'R':'Block out of range',
'X':'Authentication failed',
}
DES_IV='\0\0\0\0\0\0\0\0'
DES_PAD= [chr(0x80),chr(0),chr(0),chr(0),chr(0),chr(0),chr(0),chr(0)]
DES_PAD_HEX= '8000000000000000'
KENC= '\0\0\0\1'
KMAC= '\0\0\0\2'
DO87= '870901'
DO8E= '8E08'
DO97= '9701'
DO99= '99029000'
#
# frosch command set
#
#
# Reader Key Init Mode (update internal secret key)
FR_RWD_Key_Init_Mode= chr(0x4B)
# Reader Key Init Mode Reset (exit key init mode)
FR_RWD_KI_Reset= chr(0x52)
# READER Key Init Mode Read EEPROM
FR_RWD_KI_Read_EE_Data= chr(0x58)
# Reader Stop
FR_RWD_Stop_Cmd= chr(0xA6)
# Reader Reset
FR_RWD_HF_Reset= chr(0x68)
# Reader Version
FR_RWD_Get_Version= chr(0x56)
# Hitag1 Get Serial Number
FR_HT1_Get_Snr= chr(0x47)
# Hitag1 Get Serial Number & set tag into Advanced Protocol Mode
FR_HT1_Get_Snr_Adv= chr(0xA2)
# Hitag1 Select Last Seen
FR_HT1_Select_Last= chr(0x53)
# Hitag1 Select Serial Number
FR_HT1_Select_Snr= chr(0x53)
# Hitag1 Read Page
FR_HT1_Read_Page= chr(0x50)
# Hitag2 Get Serial Number (password mode)
FR_HT2_Get_Snr_PWD= chr(0x80) + chr(0x00)
# Hitag2 Get Serial Number Reset (to reset for normal access when in public modes)
FR_HT2_Get_Snr_Reset= chr(0x80)
# Hitag2 Halt Selected
FR_HT2_Halt_Selected= chr(0x81)
# Hitag2 read page
FR_HT2_Read_Page= chr(0x82)
# Hitag2 Read Miro (Unique / Public Mode A)
FR_HT2_Read_Miro= chr(0x4d)
# Hitag2 Read Public B (FDX-B)
FR_HT2_Read_PublicB= chr(0x9e)
# Hitag2 Write Page
FR_HT2_Write_Page= chr(0x84)
#
# frosch errors
#
FROSCH_Errors= { '00':'No Error',\
'02':'Error',\
'07':'No Error',\
'eb':'Antenna Overload',\
'f1':'EEPROM Read Protected',\
'f2':'EEPROM Write Protected',\
'f3':'EEPROM Wrong - Old Data',\
'f4':'EEPROM Error',\
'f5':'CryptoBlock not INIT',\
'f6':'Acknowledgement Error',\
'f9':'Authentication Error',\
'fa':'Incorrect Password TAG',\
'fb':'Incorrect Password RWD',\
'fc':'Timeout',\
'fd':'No TAG present!',\
'ff':'Serial port fail or wrong mode'}
#
# frosch constants
#
FR_BAUD_RATE= { 9600:chr(0x01),\
14400:chr(0x02),\
19200:chr(0x03),\
38400:chr(0x04),\
57600:chr(0x05),\
115200:chr(0x06)}
FR_NO_ERROR= chr(0x00)
FR_PLAIN= chr(0x00)
FR_CRYPTO= chr(0x01)
FR_TIMEOUT= 'fc'
FR_COMMAND_MODE= 0x00
FR_KEY_INIT_MODE= 0x01
#
# frosch statics
#
FR_BCC_Mode= FR_COMMAND_MODE
#
# DemoTag command set
#
DT_SET_UID= 'u'
#
# DemoTag Errors
#
DT_ERROR= '?'
#
# PCSC APDUs
#
# these are basically standard APDUs but with fields filled in and using OmniKey terminology
# should really unify them all, but for now...
# COMMAND : [Class, Ins, P1, P2, DATA, LEN]
PCSC_APDU= {
'ACS_14443_A' : ['d4','40','01'],
'ACS_14443_B' : ['d4','42','02'],
'ACS_14443_0' : ['d5','86','80', '05'],
'ACS_DISABLE_AUTO_POLL' : ['ff','00','51','3f','00'],
'ACS_DIRECT_TRANSMIT' : ['ff','00','00','00'],
'ACS_GET_SAM_SERIAL' : ['80','14','00','00','08'],
'ACS_GET_SAM_ID' : ['80','14','04','00','06'],
'ACS_GET_READER_FIRMWARE' : ['ff','00','48','00','00'],
'ACS_GET_RESPONSE' : ['ff','c0','00','00'],
'ACS_GET_STATUS' : ['d4','04'],
'ACS_IN_LIST_PASSIVE_TARGET' : ['d4','4a'],
'ACS_LED_GREEN' : ['ff','00','40','0e','04','00','00','00','00'],
'ACS_LED_ORANGE' : ['ff','00','40','0f','04','00','00','00','00'],
'ACS_LED_RED' : ['ff','00','40','0d','04','00','00','00','00'],
'ACS_MIFARE_LOGIN' : ['d4','40','01'],
'ACS_READ_MIFARE' : ['d4','40','01','30'],
'ACS_POLL_MIFARE' : ['d4','4a','01','00'],
'ACS_POWER_OFF' : ['d4','32','01','00'],
'ACS_POWER_ON' : ['d4','32','01','01'],
'ACS_RATS_14443_4_OFF' : ['d4','12','24'],
'ACS_RATS_14443_4_ON' : ['d4','12','34'],
'ACS_SET_PARAMETERS' : ['d4','12'],
'ACS_SET_RETRY' : ['d4','32','05','00','00','00'],
'AUTHENTICATE' : ['ff', ISOAPDU['INTERNAL_AUTHENTICATE']],
'GUID' : ['ff', ISOAPDU['GET_DATA'], '00', '00', '00'],
'ACS_GET_ATS' : ['ff', ISOAPDU['GET_DATA'], '01', '00', '00'],
'LOAD_KEY' : ['ff', ISOAPDU['EXTERNAL_AUTHENTICATE']],
'READ_BLOCK' : ['ff', ISOAPDU['READ_BINARY']],
'UPDATE_BLOCK' : ['ff', ISOAPDU['UPDATE_BINARY']],
'VERIFY' : ['ff', ISOAPDU['VERIFY']],
'WRITE_BLOCK' : ['ff', ISOAPDU['WRITE_BINARY']],
}
# PCSC Errors
PCSC_NO_CARD= 'PC00'
PCSC_COMMS_ERROR= 'PC01'
PCSC_VOLATILE= '00'
PCSC_NON_VOLATILE= '20'
# PCSC Contactless Storage Cards
PCSC_CSC= '804F'
# PCSC Workgroup RID
PCSC_RID= 'A000000306'
# PCSC Storage Standard Byte
PCSC_SS= { '00':'No information given',\
'01':'ISO 14443 A, part 1',\
'02':'ISO 14443 A, part 2',\
'03':'ISO 14443 A, part 3',\
'04':'RFU',\
'05':'ISO 14443 B, part 1',\
'06':'ISO 14443 B, part 2',\
'07':'ISO 14443 B, part 3',\
'08':'RFU',\
'09':'ISO 15693, part 1',\
'0A':'ISO 15693, part 2',\
'0B':'ISO 15693, part 3',\
'0C':'ISO 15693, part 4',\
'0D':'Contact (7816-10) I2 C',\
'0E':'Contact (7816-10) Extended I2 C',\
'0F':'Contact (7816-10) 2WBP',\
'10':'Contact (7816-10) 3WBP',\
'FF':'RFU'}
# PCSC card names
PCSC_NAME= { '0000':'No name given',\
'0001':'Mifare Standard 1K',\
'0002':'Mifare Standard 4K',\
'0003':'Mifare Ultra light',\
'0004':'SLE55R_XXXX',\
'0006':'SR176',\
'0007':'SRI X4K',\
'0008':'AT88RF020',\
'0009':'AT88SC0204CRF',\
'000A':'AT88SC0808CRF',\
'000B':'AT88SC1616CRF',\
'000C':'AT88SC3216CRF',\
'000D':'AT88SC6416CRF',\
'000E':'SRF55V10P',\
'000F':'SRF55V02P',\
'0010':'SRF55V10S',\
'0011':'SRF55V02S',\
'0012':'TAG_IT',\
'0013':'LRI512',\
'0014':'ICODESLI',\
'0015':'TEMPSENS',\
'0016':'I.CODE1',\
'0017':'PicoPass 2K',\
'0018':'PicoPass 2KS',\
'0019':'PicoPass 16K',\
'001A':'PicoPass 16Ks',\
'001B':'PicoPass 16K(8x2)',\
'001C':'PicoPass 16KS(8x2)',\
'001D':'PicoPass 32KS(16+16)',\
'001E':'PicoPass 32KS(16+8x2)',\
'001F':'PicoPass 32KS(8x2+16)',\
'0020':'PicoPass 32KS(8x2+8x2)',\
'0021':'LRI64',\
'0022':'I.CODE UID',\
'0023':'I.CODE EPC',\
'0024':'LRI12',\
'0025':'LRI128',\
'0026':'Mifare Mini'}
# ACS Constants
ACS_TAG_FOUND= 'D54B'
ACS_DATA_OK= 'D541'
ACS_NO_SAM= '3B00'
ACS_TAG_MIFARE_ULTRA= 'MIFARE Ultralight'
ACS_TAG_MIFARE_1K= 'MIFARE 1K'
ACS_TAG_MIFARE_MINI= 'MIFARE MINI'
ACS_TAG_MIFARE_4K= 'MIFARE 4K'
ACS_TAG_MIFARE_DESFIRE= 'MIFARE DESFIRE'
ACS_TAG_JCOP30= 'JCOP30'
ACS_TAG_JCOP40= 'JCOP40'
ACS_TAG_MIFARE_OYSTER= 'London Transport Oyster'
ACS_TAG_GEMPLUS_MPCOS= 'Gemplus MPCOS'
ACS_TAG_TYPES= {
'00':ACS_TAG_MIFARE_ULTRA,
'08':ACS_TAG_MIFARE_1K,
'09':ACS_TAG_MIFARE_MINI,
'18':ACS_TAG_MIFARE_4K,
'20':ACS_TAG_MIFARE_DESFIRE,
'28':ACS_TAG_JCOP30,
'38':ACS_TAG_JCOP40,
'88':ACS_TAG_MIFARE_OYSTER,
'98':ACS_TAG_GEMPLUS_MPCOS,
}
# HID constants
HID_PROX_H10301= '3B0601'
HID_PROX_H10302= '3B0702'
HID_PROX_H10304= '3B0704'
HID_PROX_H10320= '3B0514'
HID_PROX_CORP1K= '3B0764'
HID_PROX_TYPES= {
HID_PROX_H10301:'HID Prox H10301 - 26 bit (FAC + CN)',
HID_PROX_H10302:'HID Prox H10302 - 37 bit (CN)',
HID_PROX_H10304:'HID Prox H10304 - 37 bit (FAC + CN)',
HID_PROX_H10320:'HID Prox H10320 - 32 bit clock/data card',
HID_PROX_CORP1K:'HID Prox Corp 1000 - 35 bit (CIC + CN)',
}
#
# local/informational functions
#
def info(self,caller):
if len(caller) > 0:
print caller + ' (using RFIDIOt v' + self.VERSION + ')'
if not NoInit:
self.reset()
self.version()
if len(caller) > 0:
print ' Reader:',
if self.readertype == self.READER_ACG:
print 'ACG ' + self.readername,
print ' (serial no: ' + self.id() + ')'
if self.readertype == self.READER_FROSCH:
print 'Frosch ' + self.ToBinary(self.data[:16]) + ' / ' + self.ToBinary(self.data[16:32]),
print ' (serial no: ' + self.data[32:54] + ')'
if self.readertype == self.READER_PCSC:
print 'PCSC ' + self.readername
if self.readersubtype == self.READER_ACS and self.pcsc_protocol == smartcard.scard.SCARD_PROTOCOL_T0:
# get ATR to see if we have a SAM
self.select()
if not self.pcsc_atr[:4] == self.ACS_NO_SAM:
if self.acs_get_firmware_revision():
print ' (Firmware: %s, ' % self.ToBinary(self.data),
else:
print "\ncan't get firmware revision!"
os._exit(True)
if self.acs_get_sam_serial():
print 'SAM Serial: %s, ' % self.data,
else:
print "\ncan't get SAM Serial Number!"
os._exit(True)
if self.acs_get_sam_id():
print 'SAM ID: %s)' % self.ToBinary(self.data)
else:
print "\ncan't get SAM Serial Number!"
os._exit(True)
elif self.readersubtype == self.READER_ACS and self.pcsc_protocol == smartcard.scard.SCARD_PROTOCOL_T1:
if self.acs_get_firmware_revision():
print ' (Firmware: %s)' % self.ToBinary(self.data)
else:
print "\ncan't get firmware revision!"
os._exit(True)
if self.readertype == self.READER_LIBNFC:
print 'LibNFC', self.readername
print
#
# reader functions
#
def reset(self):
if self.readertype == self.READER_ACG:
# send a select to stop just in case it's in multi-select mode
self.ser.write('s')
self.ser.readline()
self.ser.flushInput()
self.ser.flushOutput()
# now send a reset and read response
self.ser.write('x')
self.ser.readline()
# now send a select and read remaining lines
self.ser.write('s')
self.ser.readline()
self.ser.flushInput()
self.ser.flushOutput()
return True
if self.readertype == self.READER_FROSCH:
if self.frosch(self.FR_RWD_HF_Reset,''):
return True
else:
print self.FROSCH_Errors[self.errorcode]
os._exit(True)
if self.readertype == self.READER_PCSC:
if self.readersubtype == self.READER_ACS:
self.acs_power_off()
self.acs_power_on()
self.data= 'A PCSC Reader (need to add reset function!)'
if self.readertype == self.READER_LIBNFC:
self.nfc.powerOff()
self.nfc.powerOn()
def version(self):
if self.readertype == self.READER_ACG:
self.ser.write('v')
try:
self.data= self.ser.readline()[:-2]
self.readername= self.data
except:
print '\nReader not responding - check baud rate'
os._exit(True)
# check for garbage data (wrong baud rate)
if not self.data or self.data[0] < ' ' or self.data[0] > '~':
print '\nGarbage received from reader - check baud rate'
os._exit(True)
return True
if self.readertype == self.READER_FROSCH:
if self.frosch(self.FR_RWD_Get_Version,''):
return True
else:
print self.FROSCH_Errors[self.errorcode]
os._exit(True)
def id(self):
return self.readEEPROM(0)[:2] + self.readEEPROM(1)[:2] + self.readEEPROM(2)[:2] + self.readEEPROM(3)[:2]
def station(self):
return self.readEEPROM(0x0a)[:2]
def PCON(self):
return self.readEEPROM(0x0b)[:2]
def PCON2(self):
return self.readEEPROM(0x13)[:2]
def PCON3(self):
return self.readEEPROM(0x1b)[:2]
def BAUD(self):
return self.readEEPROM(0x0c)[:2]
def CGT(self):
return self.readEEPROM(0x0d)[:2]
def opmode(self):
return self.readEEPROM(0x0e)[:2]
def SST(self):
return self.readEEPROM(0x0f)[:2]
def ROT(self):
return self.readEEPROM(0x14)[:2]
def RRT(self):
return self.readEEPROM(0x15)[:2]
def AFI(self):
return self.readEEPROM(0x16)[:2]
def STOa(self):
return self.readEEPROM(0x17)[:2]
def STOb(self):
return self.readEEPROM(0x18)[:2]
def STOs(self):
return self.readEEPROM(0x19)[:2]
def readEEPROM(self,byte):
self.ser.write('rp%02x' % byte)
return self.ser.readline()[:2]
def writeEEPROM(self,byte,value):
self.ser.write('wp%02x%02x' % (byte,value))
self.errorcode= self.ser.readline()[:-2]
if eval(self.errorcode) == value:
return True
return False
def settagtype(self,type):
if self.readertype == self.READER_ACG:
# ACG HF reader uses 't' for 'all', LF uses 'a'
if type == self.ALL:
if string.find(self.readername,'LFX') == 0:
type= 'a'
else:
type= 't'
self.ser.write('o' + type)
self.errorcode= self.ser.readline()[:-2]
if self.errorcode == 'O' + string.upper(type):
self.tagtype= type
return True
if self.readertype == self.READER_FROSCH:
if type == self.EM4x02:
return self.frosch(self.FR_HT2_Read_Miro,'')
if type == self.EM4x05:
return self.frosch(self.FR_HT2_Read_PublicB,'')
return False
#
# card functions
#
def pcsc_listreaders(self):
n= 0
print 'PCSC devices:'
#for reader in self.pcsc.listReader():
for reader in self.pcsc:
print ' No: %d\t\t%s' % (n,reader)
n += 1
def libnfc_listreaders(self):
self.nfc.listreaders(NFCReader)
def waitfortag(self,message):
print message
# we need a way to interrupt infinite loop
if self.readersubtype == self.READER_OMNIKEY or self.readersubtype == self.READER_SCM:
wait=True
while wait:
try:
self.pcsc_connection.connect()
self.select()
wait=False
except:
sys.stdin.flush()
time.sleep(0.5)
else:
while not self.select():
# do nothing
time.sleep(0.1)
return True
def select(self):
self.uid= ''
# return True or False and set tag type and data
if self.readertype == self.READER_ACG:
self.ser.write('s')
self.data= self.ser.readline()[:-2]
self.tagtype= self.data[:1]
if self.tagtype == self.ACG_FAIL:
self.errorcode= self.PCSC_NO_CARD
return False
# strip leading tag type from LFX response
if self.readername.find("LFX") == 0:
self.uid= self.data[1:]
else:
self.uid= self.data
return True
if self.readertype == self.READER_FROSCH:
if self.frosch(self.FR_HT2_Get_Snr_PWD,''):
# select returns an extra byte on the serial number, so strip it
self.data= self.data[:len(self.data) - 2]
self.tagtype= self.HITAG2
self.uid= self.data
return True
if self.frosch(self.FR_HT1_Get_Snr,''):
# select returns an extra byte on the serial number, so strip it
# and preserve for after select command
serialno= self.data[:len(self.data) - 2]
if self.frosch(self.FR_HT1_Select_Last,''):
self.tagtype= self.HITAG1
self.data= self.uid= serialno
return True
return False
if self.readertype == self.READER_PCSC:
try:
# start a new connection in case TAG has been switched
self.pcsc_connection.disconnect()
self.pcsc_connection.connect()
time.sleep(0.6)
self.pcsc_atr= self.ListToHex(self.pcsc_connection.getATR())
atslen= 2 * int(self.pcsc_atr[3],16)
self.pcsc_ats= self.pcsc_atr[8:8 + atslen]
if self.readersubtype == self.READER_ACS:
self.acs_select_tag()
else:
self.pcsc_send_apdu(self.PCSC_APDU['GUID'])
except smartcard.Exceptions.NoCardException:
self.errorcode= self.PCSC_NO_CARD
return False
except:
self.errorcode= self.PCSC_COMMS_ERROR
return False
if self.errorcode == self.ISO_OK:
self.uid= self.data
if not self.readersubtype == self.READER_ACS:
self.tagtype= self.PCSCGetTagType(self.pcsc_atr)
# pcsc returns ISO15693 tags LSByte first, so reverse
if string.find(self.tagtype,'ISO 15693') >= 0:
self.data= self.uid= self.HexByteReverse(self.data)
return True
else:
return False
if self.readertype == self.READER_LIBNFC:
try:
if DEBUG:
print 'reading card using LIBNFC'
result = self.nfc.readISO14443A()
if result:
self.atr = result.atr
self.uid = result.uid
if DEBUG:
print 'ATR: ' + self.atr
print 'UID: ' + self.uid
return True
else:
if DEBUG:
print 'Error selecting card'
return False
except ValueError:
self.errorcode = 'Error reading card using LIBNFC' + e
return False
def h2publicselect(self):
"select Hitag2 from Public Mode A/B/C"
if self.readertype == self.READER_FROSCH:
if (self.frosch(self.FR_HT2_Get_Snr_Reset,self.FR_PLAIN + 'M')):
self.tagtype= self.HITAG2
self.data= self.data[:8]
return True
return False
def h2login(self,password):
"login to hitag2 in password mode"