-
Notifications
You must be signed in to change notification settings - Fork 39
/
app.py
310 lines (244 loc) · 9.38 KB
/
app.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
# pylint: disable=unused-import
import argparse
import binascii
import io
from flask import Flask, jsonify, render_template, request
from werkzeug.exceptions import BadRequest
from config import (
CTR_PARAM,
ENC_FILE_DATA_PARAM,
ENC_PICC_DATA_PARAM,
REQUIRE_LRP,
SDMMAC_PARAM,
MASTER_KEY,
UID_PARAM,
DERIVE_MODE,
)
if DERIVE_MODE == "legacy":
from libsdm.legacy_derive import derive_tag_key, derive_undiversified_key
elif DERIVE_MODE == "standard":
from libsdm.derive import derive_tag_key, derive_undiversified_key
else:
raise RuntimeError("Invalid DERIVE_MODE.")
from libsdm.sdm import (
EncMode,
InvalidMessage,
ParamMode,
decrypt_sun_message,
validate_plain_sun,
)
app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
@app.errorhandler(400)
def handler_bad_request(err):
return render_template('error.html', code=400, msg=str(err)), 400
@app.errorhandler(403)
def handler_forbidden(err):
return render_template('error.html', code=403, msg=str(err)), 403
@app.errorhandler(404)
def handler_not_found(err):
return render_template('error.html', code=404, msg=str(err)), 404
@app.context_processor
def inject_demo_mode():
demo_mode = MASTER_KEY == (b"\x00" * 16)
return {"demo_mode": demo_mode}
@app.route('/')
def sdm_main():
"""
Main page with a few examples.
"""
return render_template('sdm_main.html')
# pylint: disable=too-many-branches
def parse_parameters():
arg_e = request.args.get('e')
if arg_e:
param_mode = ParamMode.BULK
try:
e_b = binascii.unhexlify(arg_e)
except binascii.Error:
raise BadRequest("Failed to decode parameters.") from None
e_buf = io.BytesIO(e_b)
if (len(e_b) - 8) % 16 == 0:
# using AES (16 byte PICCEncData)
file_len = len(e_b) - 16 - 8
enc_picc_data_b = e_buf.read(16)
if file_len > 0:
enc_file_data_b = e_buf.read(file_len)
else:
enc_file_data_b = None
sdmmac_b = e_buf.read(8)
elif (len(e_b) - 8) % 16 == 8:
# using LRP (24 byte PICCEncData)
file_len = len(e_b) - 24 - 8
enc_picc_data_b = e_buf.read(24)
if file_len > 0:
enc_file_data_b = e_buf.read(file_len)
else:
enc_file_data_b = None
sdmmac_b = e_buf.read(8)
else:
raise BadRequest("Incorrect length of the dynamic parameter.")
else:
param_mode = ParamMode.SEPARATED
enc_picc_data = request.args.get(ENC_PICC_DATA_PARAM)
enc_file_data = request.args.get(ENC_FILE_DATA_PARAM)
sdmmac = request.args.get(SDMMAC_PARAM)
if not enc_picc_data:
raise BadRequest(f"Parameter {ENC_PICC_DATA_PARAM} is required")
if not sdmmac:
raise BadRequest(f"Parameter {SDMMAC_PARAM} is required")
try:
enc_file_data_b = None
enc_picc_data_b = binascii.unhexlify(enc_picc_data)
sdmmac_b = binascii.unhexlify(sdmmac)
if enc_file_data:
enc_file_data_b = binascii.unhexlify(enc_file_data)
except binascii.Error:
raise BadRequest("Failed to decode parameters.") from None
return param_mode, enc_picc_data_b, enc_file_data_b, sdmmac_b
@app.route('/tagpt')
def sdm_info_plain():
"""
Return HTML
"""
return _internal_tagpt()
@app.route('/api/tagpt')
def sdm_api_info_plain():
"""
Return JSON
"""
try:
return _internal_tagpt(force_json=True)
except BadRequest as err:
return jsonify({"error": str(err)}), 400
def _internal_tagpt(force_json=False):
try:
uid = binascii.unhexlify(request.args[UID_PARAM])
read_ctr = binascii.unhexlify(request.args[CTR_PARAM])
cmac = binascii.unhexlify(request.args[SDMMAC_PARAM])
except binascii.Error:
raise BadRequest("Failed to decode parameters.") from None
try:
sdm_file_read_key = derive_tag_key(MASTER_KEY, uid, 2)
res = validate_plain_sun(uid=uid,
read_ctr=read_ctr,
sdmmac=cmac,
sdm_file_read_key=sdm_file_read_key)
except InvalidMessage:
raise BadRequest("Invalid message (most probably wrong signature).") from None
if REQUIRE_LRP and res['encryption_mode'] != EncMode.LRP:
raise BadRequest("Invalid encryption mode, expected LRP.")
if request.args.get("output") == "json" or force_json:
return jsonify({
"uid": res['uid'].hex().upper(),
"read_ctr": res['read_ctr'],
"enc_mode": res['encryption_mode'].name
})
return render_template('sdm_info.html',
encryption_mode=res['encryption_mode'].name,
uid=res['uid'],
read_ctr_num=res['read_ctr'])
@app.route('/webnfc')
def sdm_webnfc():
return render_template('sdm_webnfc.html')
@app.route('/tagtt')
def sdm_info_tt():
return _internal_sdm(with_tt=True)
@app.route('/api/tagtt')
def sdm_api_info_tt():
try:
return _internal_sdm(with_tt=True, force_json=True)
except BadRequest as err:
return jsonify({"error": str(err)})
@app.route('/tag')
def sdm_info():
return _internal_sdm(with_tt=False)
@app.route('/api/tag')
def sdm_api_info():
try:
return _internal_sdm(with_tt=False, force_json=True)
except BadRequest as err:
return jsonify({"error": str(err)})
# pylint: disable=too-many-branches, too-many-statements, too-many-locals
def _internal_sdm(with_tt=False, force_json=False):
"""
SUN decrypting/validating endpoint.
"""
param_mode, enc_picc_data_b, enc_file_data_b, sdmmac_b = parse_parameters()
try:
res = decrypt_sun_message(param_mode=param_mode,
sdm_meta_read_key=derive_undiversified_key(MASTER_KEY, 1),
sdm_file_read_key=lambda uid: derive_tag_key(MASTER_KEY, uid, 2),
picc_enc_data=enc_picc_data_b,
sdmmac=sdmmac_b,
enc_file_data=enc_file_data_b)
except InvalidMessage:
raise BadRequest("Invalid message (most probably wrong signature).") from InvalidMessage
if REQUIRE_LRP and res['encryption_mode'] != EncMode.LRP:
raise BadRequest("Invalid encryption mode, expected LRP.")
picc_data_tag = res['picc_data_tag']
uid = res['uid']
read_ctr_num = res['read_ctr']
file_data = res['file_data']
encryption_mode = res['encryption_mode'].name
file_data_utf8 = ""
tt_status_api = ""
tt_status = ""
tt_color = ""
if res['file_data']:
if param_mode == ParamMode.BULK:
file_data_len = file_data[2]
file_data_unpacked = file_data[3:3 + file_data_len]
else:
file_data_unpacked = file_data
file_data_utf8 = file_data_unpacked.decode('utf-8', 'ignore')
if with_tt:
tt_perm_status = file_data[0:1].decode('ascii', 'replace')
tt_cur_status = file_data[1:2].decode('ascii', 'replace')
if tt_perm_status == 'C' and tt_cur_status == 'C':
tt_status_api = 'secure'
tt_status = 'OK (not tampered)'
tt_color = 'green'
elif tt_perm_status == 'O' and tt_cur_status == 'C':
tt_status_api = 'tampered_closed'
tt_status = 'Tampered! (loop closed)'
tt_color = 'red'
elif tt_perm_status == 'O' and tt_cur_status == 'O':
tt_status_api = 'tampered_open'
tt_status = 'Tampered! (loop open)'
tt_color = 'red'
elif tt_perm_status == 'I' and tt_cur_status == 'I':
tt_status_api = 'not_initialized'
tt_status = 'Not initialized'
tt_color = 'orange'
elif tt_perm_status == 'N' and tt_cur_status == 'T':
tt_status_api = 'not_supported'
tt_status = 'Not supported by the tag'
tt_color = 'orange'
else:
tt_status_api = 'unknown'
tt_status = 'Unknown'
tt_color = 'orange'
if request.args.get("output") == "json" or force_json:
return jsonify({
"uid": uid.hex().upper(),
"file_data": file_data.hex() if file_data else None,
"read_ctr": read_ctr_num,
"tt_status": tt_status_api,
"enc_mode": encryption_mode
})
return render_template('sdm_info.html',
encryption_mode=encryption_mode,
picc_data_tag=picc_data_tag,
uid=uid,
read_ctr_num=read_ctr_num,
file_data=file_data,
file_data_utf8=file_data_utf8,
tt_status=tt_status,
tt_color=tt_color)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='OTA NFC Server')
parser.add_argument('--host', type=str, nargs='?', help='address to listen on')
parser.add_argument('--port', type=int, nargs='?', help='port to listen on')
args = parser.parse_args()
app.run(host=args.host, port=args.port)