blob: 24c9589044e56f1dfeef88a363788cdc5a4aad9b [file] [log] [blame]
Harald Welteb2edd142021-01-08 23:29:35 +01001# coding=utf-8
2"""Utilities / Functions related to ETSI TS 102 221, the core UICC spec.
3
4(C) 2021 by Harald Welte <laforge@osmocom.org>
5
6This program is free software: you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation, either version 2 of the License, or
9(at your option) any later version.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program. If not, see <http://www.gnu.org/licenses/>.
18"""
19
Harald Welte8f892fb2021-06-05 10:12:43 +020020from construct import *
21from pySim.construct import *
Harald Welteb2edd142021-01-08 23:29:35 +010022from pySim.utils import *
23from pySim.filesystem import *
Harald Welte181c7c52022-02-10 14:18:32 +010024from pySim.tlv import *
Harald Welte4ae228a2021-05-02 21:29:04 +020025from bidict import bidict
Philipp Maiera028c7d2021-11-08 16:12:03 +010026from pySim.profile import CardProfile
27from pySim.profile import match_uicc
28from pySim.profile import match_sim
Harald Welte181c7c52022-02-10 14:18:32 +010029import pySim.iso7816_4 as iso7816_4
Philipp Maiera028c7d2021-11-08 16:12:03 +010030
31# A UICC will usually also support 2G functionality. If this is the case, we
32# need to add DF_GSM and DF_TELECOM along with the UICC related files
33from pySim.ts_51_011 import DF_GSM, DF_TELECOM
Harald Welte4ae228a2021-05-02 21:29:04 +020034
35ts_102_22x_cmdset = CardCommandSet('TS 102 22x', [
36 # TS 102 221 Section 10.1.2 Table 10.5 "Coding of Instruction Byte"
37 CardCommand('SELECT', 0xA4, ['0X', '4X', '6X']),
38 CardCommand('STATUS', 0xF2, ['8X', 'CX', 'EX']),
39 CardCommand('READ BINARY', 0xB0, ['0X', '4X', '6X']),
40 CardCommand('UPDATE BINARY', 0xD6, ['0X', '4X', '6X']),
41 CardCommand('READ RECORD', 0xB2, ['0X', '4X', '6X']),
42 CardCommand('UPDATE RECORD', 0xDC, ['0X', '4X', '6X']),
43 CardCommand('SEARCH RECORD', 0xA2, ['0X', '4X', '6X']),
44 CardCommand('INCREASE', 0x32, ['8X', 'CX', 'EX']),
45 CardCommand('RETRIEVE DATA', 0xCB, ['8X', 'CX', 'EX']),
46 CardCommand('SET DATA', 0xDB, ['8X', 'CX', 'EX']),
47 CardCommand('VERIFY PIN', 0x20, ['0X', '4X', '6X']),
48 CardCommand('CHANGE PIN', 0x24, ['0X', '4X', '6X']),
49 CardCommand('DISABLE PIN', 0x26, ['0X', '4X', '6X']),
50 CardCommand('ENABLE PIN', 0x28, ['0X', '4X', '6X']),
51 CardCommand('UNBLOCK PIN', 0x2C, ['0X', '4X', '6X']),
52 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X', '6X']),
53 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X', '6X']),
54 CardCommand('AUTHENTICATE', 0x88, ['0X', '4X', '6X']),
55 CardCommand('AUTHENTICATE', 0x89, ['0X', '4X', '6X']),
56 CardCommand('GET CHALLENGE', 0x84, ['0X', '4X', '6X']),
57 CardCommand('TERMINAL CAPABILITY', 0xAA, ['8X', 'CX', 'EX']),
58 CardCommand('TERMINAL PROFILE', 0x10, ['80']),
59 CardCommand('ENVELOPE', 0xC2, ['80']),
60 CardCommand('FETCH', 0x12, ['80']),
61 CardCommand('TERMINAL RESPONSE', 0x14, ['80']),
62 CardCommand('MANAGE CHANNEL', 0x70, ['0X', '4X', '6X']),
63 CardCommand('MANAGE SECURE CHANNEL', 0x73, ['0X', '4X', '6X']),
64 CardCommand('TRANSACT DATA', 0x75, ['0X', '4X', '6X']),
65 CardCommand('SUSPEND UICC', 0x76, ['80']),
66 CardCommand('GET IDENTITY', 0x78, ['8X', 'CX', 'EX']),
67 CardCommand('EXCHANGE CAPABILITIES', 0x7A, ['80']),
68 CardCommand('GET RESPONSE', 0xC0, ['0X', '4X', '6X']),
69 # TS 102 222 Section 6.1 Table 1 "Coding of the commands"
70 CardCommand('CREATE FILE', 0xE0, ['0X', '4X']),
71 CardCommand('DELETE FILE', 0xE4, ['0X', '4X']),
72 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X']),
73 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X']),
74 CardCommand('TERMINATE DF', 0xE6, ['0X', '4X']),
75 CardCommand('TERMINATE EF', 0xE8, ['0X', '4X']),
76 CardCommand('TERMINATE CARD USAGE', 0xFE, ['0X', '4X']),
77 CardCommand('RESIZE FILE', 0xD4, ['8X', 'CX']),
Harald Weltec91085e2022-02-10 18:05:45 +010078])
Harald Welteb2edd142021-01-08 23:29:35 +010079
Harald Weltec8c33272022-02-11 14:45:23 +010080# ETSI TS 102 221 11.1.1.4.2
81class FileSize(BER_TLV_IE, tag=0x80):
82 _construct = GreedyInteger()
Harald Welteb2edd142021-01-08 23:29:35 +010083
Harald Weltec8c33272022-02-11 14:45:23 +010084# ETSI TS 102 221 11.1.1.4.2
85class TotalFileSize(BER_TLV_IE, tag=0x81):
86 _construct = GreedyInteger()
Harald Welteb2edd142021-01-08 23:29:35 +010087
88# ETSI TS 102 221 11.1.1.4.3
Harald Weltec8c33272022-02-11 14:45:23 +010089class FileDescriptor(BER_TLV_IE, tag=0x82):
90 def _from_bytes(self, in_bin: bytes):
91 out = {}
92 ft_dict = {
93 0: 'working_ef',
94 1: 'internal_ef',
95 7: 'df'
96 }
97 fs_dict = {
98 0: 'no_info_given',
99 1: 'transparent',
100 2: 'linear_fixed',
101 6: 'cyclic',
102 0x39: 'ber_tlv',
103 }
104 fdb = in_bin[0]
105 ftype = (fdb >> 3) & 7
106 if fdb & 0xbf == 0x39:
107 fstruct = 0x39
108 else:
109 fstruct = fdb & 7
110 out['shareable'] = True if fdb & 0x40 else False
111 out['file_type'] = ft_dict[ftype] if ftype in ft_dict else ftype
112 out['structure'] = fs_dict[fstruct] if fstruct in fs_dict else fstruct
113 if len(in_bin) >= 5:
114 out['record_len'] = int.from_bytes(in_bin[2:4], 'big')
115 out['num_of_rec'] = int.from_bytes(in_bin[4:5], 'big')
116 self.decoded = out
117 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100118
Harald Weltec8c33272022-02-11 14:45:23 +0100119# ETSI TS 102 221 11.1.1.4.4
120class FileIdentifier(BER_TLV_IE, tag=0x83):
121 _construct = GreedyBytes
Harald Weltec91085e2022-02-10 18:05:45 +0100122
Harald Weltec8c33272022-02-11 14:45:23 +0100123# ETSI TS 102 221 11.1.1.4.5
124class DfName(BER_TLV_IE, tag=0x84):
125 _construct = GreedyBytes
126
127# ETSI TS 102 221 11.1.1.4.6.1
128class UiccCharacteristics(BER_TLV_IE, tag=0x80):
129 _construct = GreedyBytes
130
131# ETSI TS 102 221 11.1.1.4.6.2
132class ApplicationPowerConsumption(BER_TLV_IE, tag=0x81):
133 _construct = Struct('voltage_class'/Int8ub,
134 'power_consumption_ma'/Int8ub,
135 'reference_freq_100k'/Int8ub)
136
137# ETSI TS 102 221 11.1.1.4.6.3
138class MinApplicationClockFrequency(BER_TLV_IE, tag=0x82):
139 _construct = Int8ub
140
141# ETSI TS 102 221 11.1.1.4.6.4
142class AvailableMemory(BER_TLV_IE, tag=0x83):
143 _construct = GreedyInteger()
144
145# ETSI TS 102 221 11.1.1.4.6.5
146class FileDetails(BER_TLV_IE, tag=0x84):
147 _construct = FlagsEnum(Byte, der_coding_only=1)
148
149# ETSI TS 102 221 11.1.1.4.6.6
150class ReservedFileSize(BER_TLV_IE, tag=0x85):
151 _construct = GreedyInteger()
152
153# ETSI TS 102 221 11.1.1.4.6.7
154class MaximumFileSize(BER_TLV_IE, tag=0x86):
155 _construct = GreedyInteger()
156
157# ETSI TS 102 221 11.1.1.4.6.8
158class SupportedFilesystemCommands(BER_TLV_IE, tag=0x87):
159 _construct = FlagsEnum(Byte, terminal_capability=1)
160
161# ETSI TS 102 221 11.1.1.4.6.9
162class SpecificUiccEnvironmentConditions(BER_TLV_IE, tag=0x88):
163 _construct = BitStruct('rfu'/BitsRFU(4),
164 'high_humidity_supported'/Flag,
165 'temperature_class'/Enum(BitsInteger(3), standard=0, class_A=1, class_B=2, class_C=3))
166
167# ETSI TS 102 221 11.1.1.4.6.10
168class Platform2PlatformCatSecuredApdu(BER_TLV_IE, tag=0x89):
169 _construct = GreedyBytes
170
171# ETSI TS 102 221 11.1.1.4.6.0
172class ProprietaryInformation(BER_TLV_IE, tag=0xA5,
173 nested=[UiccCharacteristics, ApplicationPowerConsumption,
174 MinApplicationClockFrequency, AvailableMemory,
175 FileDetails, ReservedFileSize, MaximumFileSize,
176 SupportedFilesystemCommands, SpecificUiccEnvironmentConditions]):
177 pass
178
179# ETSI TS 102 221 11.1.1.4.7.1
180class SecurityAttribCompact(BER_TLV_IE, tag=0x8c):
181 _construct = GreedyBytes
182
183# ETSI TS 102 221 11.1.1.4.7.2
184class SecurityAttribExpanded(BER_TLV_IE, tag=0xab):
185 _construct = GreedyBytes
186
187# ETSI TS 102 221 11.1.1.4.7.3
188class SecurityAttribReferenced(BER_TLV_IE, tag=0x8b):
189 # TODO: longer format with SEID
190 _construct = Struct('ef_arr_file_id'/Bytes(2), 'ef_arr_record_nr'/Int8ub)
191
192# ETSI TS 102 221 11.1.1.4.8
193class ShortFileIdentifier(BER_TLV_IE, tag=0x88):
194 _construct = Byte
Harald Welteb2edd142021-01-08 23:29:35 +0100195
196# ETSI TS 102 221 11.1.1.4.9
Harald Weltec8c33272022-02-11 14:45:23 +0100197class LifeCycleStatusInteger(BER_TLV_IE, tag=0x8A):
198 def _from_bytes(self, do: bytes):
199 lcsi = int.from_bytes(do, 'big')
200 if lcsi == 0x00:
201 ret = 'no_information'
202 elif lcsi == 0x01:
203 ret = 'creation'
204 elif lcsi == 0x03:
205 ret = 'initialization'
206 elif lcsi & 0x05 == 0x05:
207 ret = 'operational_activated'
208 elif lcsi & 0x05 == 0x04:
209 ret = 'operational_deactivated'
210 elif lcsi & 0xc0 == 0xc0:
211 ret = 'termination'
212 else:
213 ret = lcsi
214 self.decoded = ret
215 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100216
Harald Weltec8c33272022-02-11 14:45:23 +0100217# ETSI TS 102 221 11.1.1.4.9
218class PS_DO(BER_TLV_IE, tag=0x90):
219 _construct = GreedyBytes
220class UsageQualifier_DO(BER_TLV_IE, tag=0x95):
221 _construct = GreedyBytes
222class KeyReference(BER_TLV_IE, tag=0x83):
223 _construct = Byte
224class PinStatusTemplate_DO(BER_TLV_IE, tag=0xC6, nested=[PS_DO, UsageQualifier_DO, KeyReference]):
225 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100226
Harald Weltec8c33272022-02-11 14:45:23 +0100227class FcpTemplate(BER_TLV_IE, tag=0x62, nested=[FileSize, TotalFileSize, FileDescriptor, FileIdentifier,
228 DfName, ProprietaryInformation, SecurityAttribCompact,
229 SecurityAttribExpanded, SecurityAttribReferenced,
230 ShortFileIdentifier, LifeCycleStatusInteger,
231 PinStatusTemplate_DO]):
232 pass
Harald Welteb2edd142021-01-08 23:29:35 +0100233
234
235def tlv_key_replace(inmap, indata):
236 def newkey(inmap, key):
237 if key in inmap:
238 return inmap[key]
239 else:
240 return key
241 return {newkey(inmap, d[0]): d[1] for d in indata.items()}
242
Harald Weltec91085e2022-02-10 18:05:45 +0100243
Harald Welteb2edd142021-01-08 23:29:35 +0100244def tlv_val_interpret(inmap, indata):
245 def newval(inmap, key, val):
246 if key in inmap:
247 return inmap[key](val)
248 else:
249 return val
250 return {d[0]: newval(inmap, d[0], d[1]) for d in indata.items()}
251
Harald Welte4ae228a2021-05-02 21:29:04 +0200252# ETSI TS 102 221 Section 9.2.7 + ISO7816-4 9.3.3/9.3.4
253
Harald Weltec91085e2022-02-10 18:05:45 +0100254
Harald Welte4ae228a2021-05-02 21:29:04 +0200255class _AM_DO_DF(DataObject):
256 def __init__(self):
257 super().__init__('access_mode', 'Access Mode', tag=0x80)
258
Harald Weltec91085e2022-02-10 18:05:45 +0100259 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200260 res = []
261 if len(do) != 1:
262 raise ValueError("We only support single-byte AMF inside AM-DO")
263 amf = do[0]
264 # tables 17..29 and 41..44 of 7816-4
265 if amf & 0x80 == 0:
266 if amf & 0x40:
267 res.append('delete_file')
268 if amf & 0x20:
269 res.append('terminate_df')
270 if amf & 0x10:
271 res.append('activate_file')
272 if amf & 0x08:
273 res.append('deactivate_file')
274 if amf & 0x04:
275 res.append('create_file_df')
276 if amf & 0x02:
277 res.append('create_file_ef')
278 if amf & 0x01:
279 res.append('delete_file_child')
280 self.decoded = res
281
282 def to_bytes(self):
283 val = 0
284 if 'delete_file' in self.decoded:
285 val |= 0x40
286 if 'terminate_df' in self.decoded:
287 val |= 0x20
288 if 'activate_file' in self.decoded:
289 val |= 0x10
290 if 'deactivate_file' in self.decoded:
291 val |= 0x08
292 if 'create_file_df' in self.decoded:
293 val |= 0x04
294 if 'create_file_ef' in self.decoded:
295 val |= 0x02
296 if 'delete_file_child' in self.decoded:
297 val |= 0x01
298 return val.to_bytes(1, 'big')
299
300
301class _AM_DO_EF(DataObject):
302 """ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31"""
Harald Weltec91085e2022-02-10 18:05:45 +0100303
Harald Welte4ae228a2021-05-02 21:29:04 +0200304 def __init__(self):
305 super().__init__('access_mode', 'Access Mode', tag=0x80)
306
Harald Weltec91085e2022-02-10 18:05:45 +0100307 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200308 res = []
309 if len(do) != 1:
310 raise ValueError("We only support single-byte AMF inside AM-DO")
311 amf = do[0]
312 # tables 17..29 and 41..44 of 7816-4
313 if amf & 0x80 == 0:
314 if amf & 0x40:
315 res.append('delete_file')
316 if amf & 0x20:
317 res.append('terminate_ef')
318 if amf & 0x10:
319 res.append('activate_file_or_record')
320 if amf & 0x08:
321 res.append('deactivate_file_or_record')
322 if amf & 0x04:
323 res.append('write_append')
324 if amf & 0x02:
325 res.append('update_erase')
326 if amf & 0x01:
327 res.append('read_search_compare')
328 self.decoded = res
329
330 def to_bytes(self):
331 val = 0
332 if 'delete_file' in self.decoded:
333 val |= 0x40
334 if 'terminate_ef' in self.decoded:
335 val |= 0x20
336 if 'activate_file_or_record' in self.decoded:
337 val |= 0x10
338 if 'deactivate_file_or_record' in self.decoded:
339 val |= 0x08
340 if 'write_append' in self.decoded:
341 val |= 0x04
342 if 'update_erase' in self.decoded:
343 val |= 0x02
344 if 'read_search_compare' in self.decoded:
345 val |= 0x01
346 return val.to_bytes(1, 'big')
347
Harald Weltec91085e2022-02-10 18:05:45 +0100348
Harald Welte4ae228a2021-05-02 21:29:04 +0200349class _AM_DO_CHDR(DataObject):
350 """Command Header Access Mode DO according to ISO 7816-4 Table 32."""
Harald Weltec91085e2022-02-10 18:05:45 +0100351
Harald Welte4ae228a2021-05-02 21:29:04 +0200352 def __init__(self, tag):
353 super().__init__('command_header', 'Command Header Description', tag=tag)
354
Harald Weltec91085e2022-02-10 18:05:45 +0100355 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200356 res = {}
357 i = 0
358 if self.tag & 0x08:
359 res['CLA'] = do[i]
360 i += 1
361 if self.tag & 0x04:
362 res['INS'] = do[i]
363 i += 1
364 if self.tag & 0x02:
365 res['P1'] = do[i]
366 i += 1
367 if self.tag & 0x01:
368 res['P2'] = do[i]
369 i += 1
370 self.decoded = res
371
372 def _compute_tag(self):
373 """Override to encode the tag, as it depends on the value."""
374 tag = 0x80
375 if 'CLA' in self.decoded:
376 tag |= 0x08
377 if 'INS' in self.decoded:
378 tag |= 0x04
379 if 'P1' in self.decoded:
380 tag |= 0x02
381 if 'P2' in self.decoded:
382 tag |= 0x01
383 return tag
384
385 def to_bytes(self):
386 res = bytearray()
387 if 'CLA' in self.decoded:
388 res.append(self.decoded['CLA'])
389 if 'INS' in self.decoded:
390 res.append(self.decoded['INS'])
391 if 'P1' in self.decoded:
392 res.append(self.decoded['P1'])
393 if 'P2' in self.decoded:
394 res.append(self.decoded['P2'])
395 return res
396
Harald Weltec91085e2022-02-10 18:05:45 +0100397
Harald Welte4ae228a2021-05-02 21:29:04 +0200398AM_DO_CHDR = DataObjectChoice('am_do_chdr', members=[
Harald Weltec91085e2022-02-10 18:05:45 +0100399 _AM_DO_CHDR(0x81), _AM_DO_CHDR(0x82), _AM_DO_CHDR(0x83), _AM_DO_CHDR(0x84),
400 _AM_DO_CHDR(0x85), _AM_DO_CHDR(0x86), _AM_DO_CHDR(0x87), _AM_DO_CHDR(0x88),
401 _AM_DO_CHDR(0x89), _AM_DO_CHDR(0x8a), _AM_DO_CHDR(0x8b), _AM_DO_CHDR(0x8c),
402 _AM_DO_CHDR(0x8d), _AM_DO_CHDR(0x8e), _AM_DO_CHDR(0x8f)])
Harald Welte4ae228a2021-05-02 21:29:04 +0200403
404AM_DO_DF = AM_DO_CHDR | _AM_DO_DF()
405AM_DO_EF = AM_DO_CHDR | _AM_DO_EF()
406
407
408# TS 102 221 Section 9.5.1 / Table 9.3
409pin_names = bidict({
410 0x01: 'PIN1',
411 0x02: 'PIN2',
412 0x03: 'PIN3',
413 0x04: 'PIN4',
414 0x05: 'PIN5',
415 0x06: 'PIN6',
416 0x07: 'PIN7',
417 0x08: 'PIN8',
418 0x0a: 'ADM1',
419 0x0b: 'ADM2',
420 0x0c: 'ADM3',
421 0x0d: 'ADM4',
422 0x0e: 'ADM5',
423
424 0x11: 'UNIVERSAL_PIN',
425 0x81: '2PIN1',
426 0x82: '2PIN2',
427 0x83: '2PIN3',
428 0x84: '2PIN4',
429 0x85: '2PIN5',
430 0x86: '2PIN6',
431 0x87: '2PIN7',
432 0x88: '2PIN8',
433 0x8a: 'ADM6',
434 0x8b: 'ADM7',
435 0x8c: 'ADM8',
436 0x8d: 'ADM9',
437 0x8e: 'ADM10',
Harald Weltec91085e2022-02-10 18:05:45 +0100438})
439
Harald Welte4ae228a2021-05-02 21:29:04 +0200440
441class CRT_DO(DataObject):
442 """Control Reference Template as per TS 102 221 9.5.1"""
Harald Weltec91085e2022-02-10 18:05:45 +0100443
Harald Welte4ae228a2021-05-02 21:29:04 +0200444 def __init__(self):
Harald Weltec91085e2022-02-10 18:05:45 +0100445 super().__init__('control_reference_template',
446 'Control Reference Template', tag=0xA4)
Harald Welte4ae228a2021-05-02 21:29:04 +0200447
448 def from_bytes(self, do: bytes):
449 """Decode a Control Reference Template DO."""
450 if len(do) != 6:
451 raise ValueError('Unsupported CRT DO length: %s', do)
452 if do[0] != 0x83 or do[1] != 0x01:
453 raise ValueError('Unsupported Key Ref Tag or Len in CRT DO %s', do)
454 if do[3:] != b'\x95\x01\x08':
Harald Weltec91085e2022-02-10 18:05:45 +0100455 raise ValueError(
456 'Unsupported Usage Qualifier Tag or Len in CRT DO %s', do)
Harald Welte4ae228a2021-05-02 21:29:04 +0200457 self.encoded = do[0:6]
458 self.decoded = pin_names[do[2]]
459 return do[6:]
460
461 def to_bytes(self):
462 pin = pin_names.inverse[self.decoded]
463 return b'\x83\x01' + pin.to_bytes(1, 'big') + b'\x95\x01\x08'
464
465# ISO7816-4 9.3.3 Table 33
Harald Weltec91085e2022-02-10 18:05:45 +0100466
467
Harald Welte4ae228a2021-05-02 21:29:04 +0200468class SecCondByte_DO(DataObject):
469 def __init__(self, tag=0x9d):
470 super().__init__('security_condition_byte', tag=tag)
471
Harald Weltec91085e2022-02-10 18:05:45 +0100472 def from_bytes(self, binary: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200473 if len(binary) != 1:
474 raise ValueError
475 inb = binary[0]
476 if inb == 0:
477 cond = 'always'
478 if inb == 0xff:
479 cond = 'never'
480 res = []
481 if inb & 0x80:
482 cond = 'and'
483 else:
484 cond = 'or'
485 if inb & 0x40:
486 res.append('secure_messaging')
487 if inb & 0x20:
488 res.append('external_auth')
489 if inb & 0x10:
490 res.append('user_auth')
Harald Weltec91085e2022-02-10 18:05:45 +0100491 rd = {'mode': cond}
Harald Welte4ae228a2021-05-02 21:29:04 +0200492 if len(res):
493 rd['conditions'] = res
494 self.decoded = rd
495
496 def to_bytes(self):
497 mode = self.decoded['mode']
498 if mode == 'always':
499 res = 0
500 elif mode == 'never':
501 res = 0xff
502 else:
503 res = 0
504 if mode == 'and':
505 res |= 0x80
506 elif mode == 'or':
507 pass
508 else:
509 raise ValueError('Unknown mode %s' % mode)
510 for c in self.decoded['conditions']:
511 if c == 'secure_messaging':
512 res |= 0x40
513 elif c == 'external_auth':
514 res |= 0x20
515 elif c == 'user_auth':
516 res |= 0x10
517 else:
518 raise ValueError('Unknown condition %s' % c)
519 return res.to_bytes(1, 'big')
520
Harald Weltec91085e2022-02-10 18:05:45 +0100521
Harald Welte4ae228a2021-05-02 21:29:04 +0200522Always_DO = TL0_DataObject('always', 'Always', 0x90)
523Never_DO = TL0_DataObject('never', 'Never', 0x97)
Harald Welteb0608332022-02-10 12:45:37 +0100524
Harald Weltec91085e2022-02-10 18:05:45 +0100525
Harald Welteb0608332022-02-10 12:45:37 +0100526class Nested_DO(DataObject):
527 """A DO that nests another DO/Choice/Sequence"""
Harald Weltec91085e2022-02-10 18:05:45 +0100528
Harald Welteb0608332022-02-10 12:45:37 +0100529 def __init__(self, name, tag, choice):
530 super().__init__(name, tag=tag)
531 self.children = choice
Harald Weltec91085e2022-02-10 18:05:45 +0100532
533 def from_bytes(self, binary: bytes) -> list:
Harald Welteb0608332022-02-10 12:45:37 +0100534 remainder = binary
535 self.decoded = []
536 while remainder:
537 rc, remainder = self.children.decode(remainder)
538 self.decoded.append(rc)
539 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100540
Harald Welteb0608332022-02-10 12:45:37 +0100541 def to_bytes(self) -> bytes:
542 encoded = [self.children.encode(d) for d in self.decoded]
543 return b''.join(encoded)
544
Harald Weltec91085e2022-02-10 18:05:45 +0100545
Harald Welteb0608332022-02-10 12:45:37 +0100546OR_Template = DataObjectChoice('or_template', 'OR-Template',
547 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
548OR_DO = Nested_DO('or', 0xa0, OR_Template)
549AND_Template = DataObjectChoice('and_template', 'AND-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100550 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100551AND_DO = Nested_DO('and', 0xa7, AND_Template)
552NOT_Template = DataObjectChoice('not_template', 'NOT-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100553 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100554NOT_DO = Nested_DO('not', 0xaf, NOT_Template)
Harald Welte4ae228a2021-05-02 21:29:04 +0200555SC_DO = DataObjectChoice('security_condition', 'Security Condition',
Harald Welteb0608332022-02-10 12:45:37 +0100556 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO(),
557 OR_DO, AND_DO, NOT_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200558
Harald Welteb2edd142021-01-08 23:29:35 +0100559# TS 102 221 Section 13.1
Harald Weltec91085e2022-02-10 18:05:45 +0100560
561
Harald Welteb2edd142021-01-08 23:29:35 +0100562class EF_DIR(LinFixedEF):
Harald Welte181c7c52022-02-10 14:18:32 +0100563 class ApplicationLabel(BER_TLV_IE, tag=0x50):
564 # TODO: UCS-2 coding option as per Annex A of TS 102 221
565 _construct = GreedyString('ascii')
566
567 # see https://github.com/PyCQA/pylint/issues/5794
568 #pylint: disable=undefined-variable
569 class ApplicationTemplate(BER_TLV_IE, tag=0x61,
570 nested=[iso7816_4.ApplicationId, ApplicationLabel, iso7816_4.FileReference,
571 iso7816_4.CommandApdu, iso7816_4.DiscretionaryData,
572 iso7816_4.DiscretionaryTemplate, iso7816_4.URL,
573 iso7816_4.ApplicationRelatedDOSet]):
574 pass
575
Harald Welteb2edd142021-01-08 23:29:35 +0100576 def __init__(self, fid='2f00', sfid=0x1e, name='EF.DIR', desc='Application Directory'):
Harald Weltec91085e2022-02-10 18:05:45 +0100577 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len={5, 54})
Harald Welte181c7c52022-02-10 14:18:32 +0100578 self._tlv = EF_DIR.ApplicationTemplate
Harald Welteb2edd142021-01-08 23:29:35 +0100579
580# TS 102 221 Section 13.2
Harald Weltec91085e2022-02-10 18:05:45 +0100581
582
Harald Welteb2edd142021-01-08 23:29:35 +0100583class EF_ICCID(TransparentEF):
584 def __init__(self, fid='2fe2', sfid=0x02, name='EF.ICCID', desc='ICC Identification'):
Harald Weltec91085e2022-02-10 18:05:45 +0100585 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={10, 10})
Harald Welteb2edd142021-01-08 23:29:35 +0100586
587 def _decode_hex(self, raw_hex):
588 return {'iccid': dec_iccid(raw_hex)}
589
590 def _encode_hex(self, abstract):
591 return enc_iccid(abstract['iccid'])
592
593# TS 102 221 Section 13.3
Harald Weltec91085e2022-02-10 18:05:45 +0100594
595
Harald Welteb2edd142021-01-08 23:29:35 +0100596class EF_PL(TransRecEF):
597 def __init__(self, fid='2f05', sfid=0x05, name='EF.PL', desc='Preferred Languages'):
Harald Weltec91085e2022-02-10 18:05:45 +0100598 super().__init__(fid, sfid=sfid, name=name,
599 desc=desc, rec_len=2, size={2, None})
600
Harald Welte0c840f02022-01-21 15:42:22 +0100601 def _decode_record_bin(self, bin_data):
602 if bin_data == b'\xff\xff':
603 return None
604 else:
605 return bin_data.decode('ascii')
Harald Weltec91085e2022-02-10 18:05:45 +0100606
Harald Welte0c840f02022-01-21 15:42:22 +0100607 def _encode_record_bin(self, in_json):
608 if in_json is None:
609 return b'\xff\xff'
610 else:
611 return in_json.encode('ascii')
612
Harald Welteb2edd142021-01-08 23:29:35 +0100613
614# TS 102 221 Section 13.4
615class EF_ARR(LinFixedEF):
616 def __init__(self, fid='2f06', sfid=0x06, name='EF.ARR', desc='Access Rule Reference'):
617 super().__init__(fid, sfid=sfid, name=name, desc=desc)
Harald Welte4ae228a2021-05-02 21:29:04 +0200618 # add those commands to the general commands of a TransparentEF
619 self.shell_commands += [self.AddlShellCommands()]
620
621 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100622 def flatten(inp: list):
Harald Welte4ae228a2021-05-02 21:29:04 +0200623 """Flatten the somewhat deep/complex/nested data returned from decoder."""
624 def sc_abbreviate(sc):
625 if 'always' in sc:
626 return 'always'
627 elif 'never' in sc:
628 return 'never'
629 elif 'control_reference_template' in sc:
630 return sc['control_reference_template']
631 else:
632 return sc
633
634 by_mode = {}
635 for t in inp:
636 am = t[0]
637 sc = t[1]
638 sc_abbr = sc_abbreviate(sc)
639 if 'access_mode' in am:
640 for m in am['access_mode']:
641 by_mode[m] = sc_abbr
642 elif 'command_header' in am:
643 ins = am['command_header']['INS']
644 if 'CLA' in am['command_header']:
645 cla = am['command_header']['CLA']
646 else:
647 cla = None
648 cmd = ts_102_22x_cmdset.lookup(ins, cla)
649 if cmd:
Harald Weltec91085e2022-02-10 18:05:45 +0100650 name = cmd.name.lower().replace(' ', '_')
Harald Welte4ae228a2021-05-02 21:29:04 +0200651 by_mode[name] = sc_abbr
652 else:
653 raise ValueError
654 else:
655 raise ValueError
656 return by_mode
657
658 def _decode_record_bin(self, raw_bin_data):
659 # we can only guess if we should decode for EF or DF here :(
Harald Weltec91085e2022-02-10 18:05:45 +0100660 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200661 dec = arr_seq.decode_multi(raw_bin_data)
662 # we cannot pass the result through flatten() here, as we don't have a related
663 # 'un-flattening' decoder, and hence would be unable to encode :(
664 return dec[0]
665
666 @with_default_category('File-Specific Commands')
667 class AddlShellCommands(CommandSet):
668 def __init__(self):
669 super().__init__()
670
671 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_rec_dec_parser)
672 def do_read_arr_record(self, opts):
673 """Read one EF.ARR record in flattened, human-friendly form."""
674 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
675 data = self._cmd.rs.selected_file.flatten(data)
676 self._cmd.poutput_json(data, opts.oneline)
677
678 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_recs_dec_parser)
679 def do_read_arr_records(self, opts):
680 """Read + decode all EF.ARR records in flattened, human-friendly form."""
681 num_of_rec = self._cmd.rs.selected_file_fcp['file_descriptor']['num_of_rec']
682 # collect all results in list so they are rendered as JSON list when printing
683 data_list = []
684 for recnr in range(1, 1 + num_of_rec):
685 (data, sw) = self._cmd.rs.read_record_dec(recnr)
686 data = self._cmd.rs.selected_file.flatten(data)
687 data_list.append(data)
688 self._cmd.poutput_json(data_list, opts.oneline)
689
Harald Welteb2edd142021-01-08 23:29:35 +0100690
691# TS 102 221 Section 13.6
692class EF_UMPC(TransparentEF):
693 def __init__(self, fid='2f08', sfid=0x08, name='EF.UMPC', desc='UICC Maximum Power Consumption'):
Harald Weltec91085e2022-02-10 18:05:45 +0100694 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={5, 5})
695 addl_info = FlagsEnum(Byte, req_inc_idle_current=1,
696 support_uicc_suspend=2)
697 self._construct = Struct(
698 'max_current_mA'/Int8ub, 't_op_s'/Int8ub, 'addl_info'/addl_info)
699
Harald Welteb2edd142021-01-08 23:29:35 +0100700
Harald Welteb2edd142021-01-08 23:29:35 +0100701class CardProfileUICC(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +0100702
703 ORDER = 1
704
Harald Weltec91085e2022-02-10 18:05:45 +0100705 def __init__(self, name='UICC'):
Harald Welteb2edd142021-01-08 23:29:35 +0100706 files = [
707 EF_DIR(),
708 EF_ICCID(),
709 EF_PL(),
710 EF_ARR(),
711 # FIXME: DF.CD
712 EF_UMPC(),
713 ]
714 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +0100715 'Normal': {
716 '9000': 'Normal ending of the command',
717 '91xx': 'Normal ending of the command, with extra information from the proactive UICC containing a command for the terminal',
718 '92xx': 'Normal ending of the command, with extra information concerning an ongoing data transfer session',
Harald Welteb2edd142021-01-08 23:29:35 +0100719 },
Harald Weltec91085e2022-02-10 18:05:45 +0100720 'Postponed processing': {
721 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Harald Welteb2edd142021-01-08 23:29:35 +0100722 },
Harald Weltec91085e2022-02-10 18:05:45 +0100723 'Warnings': {
724 '6200': 'No information given, state of non-volatile memory unchanged',
725 '6281': 'Part of returned data may be corrupted',
726 '6282': 'End of file/record reached before reading Le bytes or unsuccessful search',
727 '6283': 'Selected file invalidated',
728 '6284': 'Selected file in termination state',
729 '62f1': 'More data available',
730 '62f2': 'More data available and proactive command pending',
731 '62f3': 'Response data available',
732 '63f1': 'More data expected',
733 '63f2': 'More data expected and proactive command pending',
734 '63cx': 'Command successful but after using an internal update retry routine X times',
Harald Welteb2edd142021-01-08 23:29:35 +0100735 },
Harald Weltec91085e2022-02-10 18:05:45 +0100736 'Execution errors': {
737 '6400': 'No information given, state of non-volatile memory unchanged',
738 '6500': 'No information given, state of non-volatile memory changed',
739 '6581': 'Memory problem',
Harald Welteb2edd142021-01-08 23:29:35 +0100740 },
Harald Weltec91085e2022-02-10 18:05:45 +0100741 'Checking errors': {
742 '6700': 'Wrong length',
743 '67xx': 'The interpretation of this status word is command dependent',
744 '6b00': 'Wrong parameter(s) P1-P2',
745 '6d00': 'Instruction code not supported or invalid',
746 '6e00': 'Class not supported',
747 '6f00': 'Technical problem, no precise diagnosis',
748 '6fxx': 'The interpretation of this status word is command dependent',
Harald Welteb2edd142021-01-08 23:29:35 +0100749 },
Harald Weltec91085e2022-02-10 18:05:45 +0100750 'Functions in CLA not supported': {
751 '6800': 'No information given',
752 '6881': 'Logical channel not supported',
753 '6882': 'Secure messaging not supported',
Harald Welteb2edd142021-01-08 23:29:35 +0100754 },
Harald Weltec91085e2022-02-10 18:05:45 +0100755 'Command not allowed': {
756 '6900': 'No information given',
757 '6981': 'Command incompatible with file structure',
758 '6982': 'Security status not satisfied',
759 '6983': 'Authentication/PIN method blocked',
760 '6984': 'Referenced data invalidated',
761 '6985': 'Conditions of use not satisfied',
762 '6986': 'Command not allowed (no EF selected)',
763 '6989': 'Command not allowed - secure channel - security not satisfied',
Harald Welteb2edd142021-01-08 23:29:35 +0100764 },
Harald Weltec91085e2022-02-10 18:05:45 +0100765 'Wrong parameters': {
766 '6a80': 'Incorrect parameters in the data field',
767 '6a81': 'Function not supported',
768 '6a82': 'File not found',
769 '6a83': 'Record not found',
770 '6a84': 'Not enough memory space',
771 '6a86': 'Incorrect parameters P1 to P2',
772 '6a87': 'Lc inconsistent with P1 to P2',
773 '6a88': 'Referenced data not found',
Harald Welteb2edd142021-01-08 23:29:35 +0100774 },
Harald Weltec91085e2022-02-10 18:05:45 +0100775 'Application errors': {
776 '9850': 'INCREASE cannot be performed, max value reached',
777 '9862': 'Authentication error, application specific',
778 '9863': 'Security session or association expired',
779 '9864': 'Minimum UICC suspension time is too long',
Harald Welteb2edd142021-01-08 23:29:35 +0100780 },
Harald Weltec91085e2022-02-10 18:05:45 +0100781 }
Harald Welteb2edd142021-01-08 23:29:35 +0100782
Harald Weltec91085e2022-02-10 18:05:45 +0100783 super().__init__(name, desc='ETSI TS 102 221', cla="00",
784 sel_ctrl="0004", files_in_mf=files, sw=sw)
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100785
Philipp Maier5998a3a2021-11-16 15:16:39 +0100786 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100787 def decode_select_response(resp_hex: str) -> object:
Philipp Maier5998a3a2021-11-16 15:16:39 +0100788 """ETSI TS 102 221 Section 11.1.1.3"""
Harald Weltec8c33272022-02-11 14:45:23 +0100789 t = FcpTemplate()
790 t.from_tlv(h2b(resp_hex))
791 d = t.to_dict()
792 return flatten_dict_lists(d['fcp_template'])
Philipp Maiera028c7d2021-11-08 16:12:03 +0100793
794 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100795 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100796 return match_uicc(scc)
797
Harald Weltec91085e2022-02-10 18:05:45 +0100798
Philipp Maiera028c7d2021-11-08 16:12:03 +0100799class CardProfileUICCSIM(CardProfileUICC):
800 """Same as above, but including 2G SIM support"""
801
802 ORDER = 0
803
804 def __init__(self):
805 super().__init__('UICC-SIM')
806
807 # Add GSM specific files
808 self.files_in_mf.append(DF_TELECOM())
809 self.files_in_mf.append(DF_GSM())
810
811 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100812 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100813 return match_uicc(scc) and match_sim(scc)