This repository has been archived by the owner on Mar 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
mrtd.py
277 lines (215 loc) · 9.27 KB
/
mrtd.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
from pypassport.reader import ReaderManager, TimeOutException
from pypassport.epassport import EPassport, mrz
# from pypassport.doc9303 import tagconverter
import tagconverter
from pypassport.doc9303.bac import BACException
from pypassport.iso7816 import Iso7816Exception
from image_handler import convert_jp2
import json, logging, re, time
from datetime import datetime
class MRTD:
"""
Machine Readable Travel Document
TODO:
- add doc
"""
def __init__(self, mrz=None, output=False):
if(type(mrz) is list):
# doc_nr, dob, exp_date
mrz = self._buildMRZ(mrz[0], mrz[1], mrz[2])
self.mrz_string = mrz
self.output = output
self.epassport = None
self.reader_obj = None
self.dg1_retries = 0
self.dg2_retries = 0
self.max_retries = 3
self.rm = ReaderManager()
def do_bac(self):
self.epassport.doBasicAccessControl()
def _set_reader_obj(self):
if self.reader_obj != None:
return
rm = self.rm
rm = ReaderManager()
logging.info("Waiting for card...")
try:
self.reader_obj = rm.waitForCard()
except TimeOutException as e:
logging.warn("Retrying after '{}'".format(e.message))
return self._set_reader_obj()
logging.info("Card detected!")
def wait_for_card(self):
reader = self.rm._autoDetect()
if reader:
self.reader_obj = reader
return True
def check_mrz(self, mrz_string):
mrz_obj = mrz.MRZ(mrz_string)
return mrz_obj.checkMRZ()
def _set_epassport(self):
if self.check_mrz(self.mrz_string) == False:
logging.warn("MRZ is not valid")
return False
self._set_reader_obj()
self.epassport = EPassport(self.reader_obj, self.mrz_string)
return True
def personal_data(self):
self._set_epassport()
try:
if self.dg1_retries == self.max_retries:
logging.info("Reposition ID-card and try again")
return
if self.dg1_retries > 0:
logging.info("Retry count: {}".format(self.dg1_retries))
dg1_data = self.epassport['DG1']
except Iso7816Exception as e:
logging.exception(e.message)
logging.info("Retrying...")
self.dg1_retries += 1
return self.personal_data()
except BACException as e:
logging.exception(e.message)
logging.info("Possible mismatch MRZ and document")
return None
clean_info = {}
for attribute, value in dg1_data.iteritems():
tag_name = tagconverter.tagToName[attribute]
if tag_name is 'name':
value = self.format_name(value)
elif tag_name is 'date_of_birth' or tag_name is 'expiry_date':
# adjustment year is '-10' since a passport is valid for max 10 years, i.e. 280101 = 1 January 2028
value = self.format_date(value, -10)
elif tag_name is not 'mrz_data_elements':
value = re.sub('<', '', value)
clean_info.update({tag_name: value})
if self.output:
doc_number_tag = '5A'
doc_number = dg1_data[doc_number_tag]
with open('output/' + doc_number + '.json', 'w') as outfile:
json.dump(clean_info, outfile)
return clean_info
def photo_data(self, output_format='jpeg'):
if self._set_epassport() == False:
logging.error("EPassport not set")
return
logging.info("Getting image from NFC, this might take a while...")
try:
if self.dg2_retries == self.max_retries:
logging.info("Reposition ID-card and try again")
return
if self.dg2_retries > 0:
logging.info("Retry count: {}".format(self.dg2_retries))
dg2_data = self.epassport['DG2']
except Iso7816Exception as e:
logging.exception(e.message)
logging.info("Retrying...")
self.dg2_retries += 1
return self.photo_data()
except BACException as e:
logging.exception(e.message)
logging.info("Possible mismatch MRZ and document")
return None
# check from ePassportviewer
if dg2_data['A1'].has_key('5F2E'): tag = '5F2E' # 5F2E: Biometric data block
elif dg2_data['A1'].has_key('7F2E'): tag = '7F2E' # 7F2E: Biometric data block (enciphered)
img_data = dg2_data['A1'][tag]
if self.output:
dg1_data = self.epassport['DG1']
doc_number_tag = '5A'
output_name = dg1_data[doc_number_tag]
else:
output_name = 'tmp'
return convert_jp2(img_data, output_name, output_format, self.output)
def format_name(self, input):
"""
Formats a name as taken from DG1 to a readable format
Returns a list with the surname as first element and first name as second element,
e.g. ["Van Der Meulen", "Martin"]
:param input: e.g. "VAN<DER<MEULEN<<MARTIN<<<<<<<<<<<<<<<<<"
"""
index_end_surname = input.index("<<")
surname = input[:index_end_surname]
if surname.find("<") == -1:
surname = surname.lower().capitalize()
else:
surname_list = surname.split("<")
surname = ""
i = 0
for name in surname_list:
surname += name.lower().capitalize()
if i != len(surname_list)-1:
surname += " "
i += 1
first_name = input[index_end_surname:]
first_name = first_name[2:]
index_end = first_name.index("<<")
first_name = first_name[:index_end]
if first_name.find("<") == -1:
first_name = first_name.lower().capitalize()
else:
first_name_list = first_name.split("<")
first_name = ""
i = 0
for name in first_name_list:
first_name += name.lower().capitalize()
if i != len(first_name_list)-1:
first_name += " "
i += 1
full_name = []
full_name.append(surname)
full_name.append(first_name)
return full_name
def format_date(self, input, adjustment_years=10):
"""
Formats a date as taken from DG1 (yymmdd) to a standard format (yyyy-mm-dd).
In this function the standard date formatting of Python is adjusted to fit the use case.
With Pythons default datetime will format '69' to '1969' and '68' to '2068'.
So all the years after '69 will be concidered 20th century and before '69 as 21st century.
This is changed to where the switch in century interpretation is x years before the current year.
This means as for today, 4th December 2018, i.e. '08' is '2008' and '09' is '1909'
:param input: year in format 'yymmdd'
:param adjustment_years: amount of years before current year what will be the new turn of century
"""
date_obj = datetime.strptime(input, '%y%m%d')
current_year = datetime.now().year
if date_obj.year > current_year - adjustment_years:
date_obj = date_obj.replace(year=date_obj.year-100)
date = date_obj.strftime("%Y-%m-%d")
return date
# From pypassport > attacks > bruteForce
def _buildMRZ(self, id_pass, dob, exp, pers_num="<<<<<<<<<<<<<<"):
"""
Create the MRZ based on:
- the document number
- the date of birth
- the expiration date
- (optional) personal number
@param id_pass: Document number
@type id_pass: String (0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<)
@param dob: Date of birth
@type dob: String (YYMMDD)
@param exp: Expiration date
@type exp: String (YYMMDD)
@param pers_num: (optional) Personal number. If not set, value = "<<<<<<<<<<<<<<"
@type pers_num: String (0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<)
@return: A String "PPPPPPPPPPCXXXBBBBBBCXEEEEEECNNNNNNNNNNNNNNCC"
"""
id_pass_full = id_pass + (9-len(id_pass))*'<' + self._calculCheckDigit(id_pass)
dob_full = dob + self._calculCheckDigit(dob)
exp_full = exp + self._calculCheckDigit(exp)
pers_num_full = pers_num + self._calculCheckDigit(pers_num)
return id_pass_full + "???" + dob_full + "?" + exp_full + pers_num_full + self._calculCheckDigit(id_pass_full+dob_full+exp_full+pers_num_full)
# From pypassport > doc9303 > mrz
def _calculCheckDigit(self, value):
weighting = [7,3,1]
weight = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '<':0,
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'G':16, 'H':17, 'I':18, 'J':19, 'K':20, 'L':21, 'M':22,
'N':23, 'O':24, 'P':25, 'Q':26, 'R':27, 'S':28, 'T':29, 'U':30, 'V':31, 'W':32, 'X':33, 'Y':34, 'Z':35};
cpt=0
res=0
for x in value:
tmp = weight[str(x)] * weighting[cpt%3]
res += tmp
cpt += 1
return str(res%10)