blob: 308fc4a3e980af51d7b6b93d69248779dcfa8932 [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 *
Harald Welte747a9782022-02-13 17:52:28 +010021from construct import Optional as COptional
Harald Welte8f892fb2021-06-05 10:12:43 +020022from pySim.construct import *
Harald Welteb2edd142021-01-08 23:29:35 +010023from pySim.utils import *
24from pySim.filesystem import *
Harald Welte181c7c52022-02-10 14:18:32 +010025from pySim.tlv import *
Harald Welte4ae228a2021-05-02 21:29:04 +020026from bidict import bidict
Philipp Maiera028c7d2021-11-08 16:12:03 +010027from pySim.profile import CardProfile
28from pySim.profile import match_uicc
29from pySim.profile import match_sim
Harald Welte181c7c52022-02-10 14:18:32 +010030import pySim.iso7816_4 as iso7816_4
Philipp Maiera028c7d2021-11-08 16:12:03 +010031
32# A UICC will usually also support 2G functionality. If this is the case, we
33# need to add DF_GSM and DF_TELECOM along with the UICC related files
Harald Welte323a3502023-07-11 17:26:39 +020034from pySim.ts_51_011 import DF_GSM, DF_TELECOM, AddonSIM
35from pySim.gsm_r import AddonGSMR
36from pySim.cdma_ruim import AddonRUIM
Harald Welte4ae228a2021-05-02 21:29:04 +020037
38ts_102_22x_cmdset = CardCommandSet('TS 102 22x', [
39 # TS 102 221 Section 10.1.2 Table 10.5 "Coding of Instruction Byte"
40 CardCommand('SELECT', 0xA4, ['0X', '4X', '6X']),
41 CardCommand('STATUS', 0xF2, ['8X', 'CX', 'EX']),
42 CardCommand('READ BINARY', 0xB0, ['0X', '4X', '6X']),
43 CardCommand('UPDATE BINARY', 0xD6, ['0X', '4X', '6X']),
44 CardCommand('READ RECORD', 0xB2, ['0X', '4X', '6X']),
45 CardCommand('UPDATE RECORD', 0xDC, ['0X', '4X', '6X']),
46 CardCommand('SEARCH RECORD', 0xA2, ['0X', '4X', '6X']),
47 CardCommand('INCREASE', 0x32, ['8X', 'CX', 'EX']),
48 CardCommand('RETRIEVE DATA', 0xCB, ['8X', 'CX', 'EX']),
49 CardCommand('SET DATA', 0xDB, ['8X', 'CX', 'EX']),
50 CardCommand('VERIFY PIN', 0x20, ['0X', '4X', '6X']),
51 CardCommand('CHANGE PIN', 0x24, ['0X', '4X', '6X']),
52 CardCommand('DISABLE PIN', 0x26, ['0X', '4X', '6X']),
53 CardCommand('ENABLE PIN', 0x28, ['0X', '4X', '6X']),
54 CardCommand('UNBLOCK PIN', 0x2C, ['0X', '4X', '6X']),
55 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X', '6X']),
56 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X', '6X']),
57 CardCommand('AUTHENTICATE', 0x88, ['0X', '4X', '6X']),
58 CardCommand('AUTHENTICATE', 0x89, ['0X', '4X', '6X']),
59 CardCommand('GET CHALLENGE', 0x84, ['0X', '4X', '6X']),
60 CardCommand('TERMINAL CAPABILITY', 0xAA, ['8X', 'CX', 'EX']),
61 CardCommand('TERMINAL PROFILE', 0x10, ['80']),
62 CardCommand('ENVELOPE', 0xC2, ['80']),
63 CardCommand('FETCH', 0x12, ['80']),
64 CardCommand('TERMINAL RESPONSE', 0x14, ['80']),
65 CardCommand('MANAGE CHANNEL', 0x70, ['0X', '4X', '6X']),
66 CardCommand('MANAGE SECURE CHANNEL', 0x73, ['0X', '4X', '6X']),
67 CardCommand('TRANSACT DATA', 0x75, ['0X', '4X', '6X']),
68 CardCommand('SUSPEND UICC', 0x76, ['80']),
69 CardCommand('GET IDENTITY', 0x78, ['8X', 'CX', 'EX']),
70 CardCommand('EXCHANGE CAPABILITIES', 0x7A, ['80']),
71 CardCommand('GET RESPONSE', 0xC0, ['0X', '4X', '6X']),
72 # TS 102 222 Section 6.1 Table 1 "Coding of the commands"
73 CardCommand('CREATE FILE', 0xE0, ['0X', '4X']),
74 CardCommand('DELETE FILE', 0xE4, ['0X', '4X']),
75 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X']),
76 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X']),
77 CardCommand('TERMINATE DF', 0xE6, ['0X', '4X']),
78 CardCommand('TERMINATE EF', 0xE8, ['0X', '4X']),
79 CardCommand('TERMINATE CARD USAGE', 0xFE, ['0X', '4X']),
80 CardCommand('RESIZE FILE', 0xD4, ['8X', 'CX']),
Harald Weltec91085e2022-02-10 18:05:45 +010081])
Harald Welteb2edd142021-01-08 23:29:35 +010082
Harald Weltec8c33272022-02-11 14:45:23 +010083# ETSI TS 102 221 11.1.1.4.2
84class FileSize(BER_TLV_IE, tag=0x80):
Philipp Maier541a9152022-06-01 18:21:17 +020085 _construct = GreedyInteger(minlen=2)
Harald Welteb2edd142021-01-08 23:29:35 +010086
Harald Weltec8c33272022-02-11 14:45:23 +010087# ETSI TS 102 221 11.1.1.4.2
88class TotalFileSize(BER_TLV_IE, tag=0x81):
Philipp Maier541a9152022-06-01 18:21:17 +020089 _construct = GreedyInteger(minlen=2)
Harald Welteb2edd142021-01-08 23:29:35 +010090
91# ETSI TS 102 221 11.1.1.4.3
Harald Weltec8c33272022-02-11 14:45:23 +010092class FileDescriptor(BER_TLV_IE, tag=0x82):
Harald Welteee6a9512023-12-23 16:14:04 +010093 _test_decode = [
94 # FIXME: this doesn't work as _encode test for some strange reason.
95 ( '82027921', { "file_descriptor_byte": { "shareable": True, "structure": "ber_tlv" }, "record_len": None, "num_of_rec": None } ),
96 ]
97 _test_de_encode = [
98 ( '82027821', { "file_descriptor_byte": { "shareable": True, "file_type": "df", "structure": "no_info_given" }, "record_len": None, "num_of_rec": None }),
99 ( '82024121', { "file_descriptor_byte": { "shareable": True, "file_type": "working_ef", "structure": "transparent" }, "record_len": None, "num_of_rec": None } ),
100 ( '82054221006e05', { "file_descriptor_byte": { "shareable": True, "file_type": "working_ef", "structure": "linear_fixed" }, "record_len": 110, "num_of_rec": 5 } ),
101 ]
Harald Welte747a9782022-02-13 17:52:28 +0100102 class BerTlvAdapter(Adapter):
103 def _parse(self, obj, context, path):
Harald Welteee6a9512023-12-23 16:14:04 +0100104 data = obj.read()
105 if data == b'\x01\x01\x01\x00\x00\x01':
Harald Welte747a9782022-02-13 17:52:28 +0100106 return 'ber_tlv'
107 raise ValidationError
108 def _build(self, obj, context, path):
109 if obj == 'ber_tlv':
Harald Welteee6a9512023-12-23 16:14:04 +0100110 return b'\x01\x01\x01\x00\x00\x01'
Harald Welte747a9782022-02-13 17:52:28 +0100111 raise ValidationError
112
113 FDB = Select(BitStruct(Const(0, Bit), 'shareable'/Flag, 'structure'/BerTlvAdapter(Const(0x39, BitsInteger(6)))),
114 BitStruct(Const(0, Bit), 'shareable'/Flag, 'file_type'/Enum(BitsInteger(3), working_ef=0, internal_ef=1, df=7),
115 'structure'/Enum(BitsInteger(3), no_info_given=0, transparent=1, linear_fixed=2, cyclic=6))
116 )
117 _construct = Struct('file_descriptor_byte'/FDB, Const(b'\x21'),
Harald Welte4ebeebf2022-02-25 09:47:51 +0100118 'record_len'/COptional(Int16ub), 'num_of_rec'/COptional(Int8ub))
Harald Weltec91085e2022-02-10 18:05:45 +0100119
Harald Weltec8c33272022-02-11 14:45:23 +0100120# ETSI TS 102 221 11.1.1.4.4
121class FileIdentifier(BER_TLV_IE, tag=0x83):
Harald Welte3c9b7842021-10-19 21:44:24 +0200122 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100123
Harald Weltec8c33272022-02-11 14:45:23 +0100124# ETSI TS 102 221 11.1.1.4.5
125class DfName(BER_TLV_IE, tag=0x84):
Harald Welte3c9b7842021-10-19 21:44:24 +0200126 _construct = HexAdapter(GreedyBytes)
Harald Weltec8c33272022-02-11 14:45:23 +0100127
128# ETSI TS 102 221 11.1.1.4.6.1
129class UiccCharacteristics(BER_TLV_IE, tag=0x80):
130 _construct = GreedyBytes
131
132# ETSI TS 102 221 11.1.1.4.6.2
133class ApplicationPowerConsumption(BER_TLV_IE, tag=0x81):
134 _construct = Struct('voltage_class'/Int8ub,
135 'power_consumption_ma'/Int8ub,
136 'reference_freq_100k'/Int8ub)
137
138# ETSI TS 102 221 11.1.1.4.6.3
139class MinApplicationClockFrequency(BER_TLV_IE, tag=0x82):
140 _construct = Int8ub
141
142# ETSI TS 102 221 11.1.1.4.6.4
143class AvailableMemory(BER_TLV_IE, tag=0x83):
144 _construct = GreedyInteger()
145
146# ETSI TS 102 221 11.1.1.4.6.5
147class FileDetails(BER_TLV_IE, tag=0x84):
148 _construct = FlagsEnum(Byte, der_coding_only=1)
149
150# ETSI TS 102 221 11.1.1.4.6.6
151class ReservedFileSize(BER_TLV_IE, tag=0x85):
152 _construct = GreedyInteger()
153
154# ETSI TS 102 221 11.1.1.4.6.7
155class MaximumFileSize(BER_TLV_IE, tag=0x86):
156 _construct = GreedyInteger()
157
158# ETSI TS 102 221 11.1.1.4.6.8
159class SupportedFilesystemCommands(BER_TLV_IE, tag=0x87):
160 _construct = FlagsEnum(Byte, terminal_capability=1)
161
162# ETSI TS 102 221 11.1.1.4.6.9
163class SpecificUiccEnvironmentConditions(BER_TLV_IE, tag=0x88):
164 _construct = BitStruct('rfu'/BitsRFU(4),
165 'high_humidity_supported'/Flag,
166 'temperature_class'/Enum(BitsInteger(3), standard=0, class_A=1, class_B=2, class_C=3))
167
168# ETSI TS 102 221 11.1.1.4.6.10
169class Platform2PlatformCatSecuredApdu(BER_TLV_IE, tag=0x89):
170 _construct = GreedyBytes
171
Harald Welte3c9b7842021-10-19 21:44:24 +0200172# sysmoISIM-SJA2 specific
173class ToolkitAccessConditions(BER_TLV_IE, tag=0xD2):
174 _construct = FlagsEnum(Byte, rfm_create=1, rfm_delete_terminate=2, other_applet_create=4,
175 other_applet_delete_terminate=8)
176
Harald Weltec8c33272022-02-11 14:45:23 +0100177# ETSI TS 102 221 11.1.1.4.6.0
178class ProprietaryInformation(BER_TLV_IE, tag=0xA5,
179 nested=[UiccCharacteristics, ApplicationPowerConsumption,
180 MinApplicationClockFrequency, AvailableMemory,
181 FileDetails, ReservedFileSize, MaximumFileSize,
Harald Welte3c9b7842021-10-19 21:44:24 +0200182 SupportedFilesystemCommands, SpecificUiccEnvironmentConditions,
183 ToolkitAccessConditions]):
Harald Weltec8c33272022-02-11 14:45:23 +0100184 pass
185
186# ETSI TS 102 221 11.1.1.4.7.1
187class SecurityAttribCompact(BER_TLV_IE, tag=0x8c):
188 _construct = GreedyBytes
189
190# ETSI TS 102 221 11.1.1.4.7.2
191class SecurityAttribExpanded(BER_TLV_IE, tag=0xab):
192 _construct = GreedyBytes
193
194# ETSI TS 102 221 11.1.1.4.7.3
195class SecurityAttribReferenced(BER_TLV_IE, tag=0x8b):
196 # TODO: longer format with SEID
Harald Welte3c9b7842021-10-19 21:44:24 +0200197 _construct = Struct('ef_arr_file_id'/HexAdapter(Bytes(2)), 'ef_arr_record_nr'/Int8ub)
Harald Weltec8c33272022-02-11 14:45:23 +0100198
199# ETSI TS 102 221 11.1.1.4.8
200class ShortFileIdentifier(BER_TLV_IE, tag=0x88):
Harald Welte5e9bd932022-02-25 09:35:28 +0100201 # If the length of the TLV is 1, the SFI value is indicated in the 5 most significant bits (bits b8 to b4)
202 # of the TLV value field. In this case, bits b3 to b1 shall be set to 0
203 class Shift3RAdapter(Adapter):
204 def _decode(self, obj, context, path):
Philipp Maier373b23c2022-06-01 18:16:02 +0200205 return int.from_bytes(obj, 'big') >> 3
Harald Welte5e9bd932022-02-25 09:35:28 +0100206 def _encode(self, obj, context, path):
Philipp Maier373b23c2022-06-01 18:16:02 +0200207 val = int(obj) << 3
208 return val.to_bytes(1, 'big')
209 _construct = COptional(Shift3RAdapter(Bytes(1)))
Harald Welteb2edd142021-01-08 23:29:35 +0100210
211# ETSI TS 102 221 11.1.1.4.9
Harald Weltec8c33272022-02-11 14:45:23 +0100212class LifeCycleStatusInteger(BER_TLV_IE, tag=0x8A):
Harald Welteee6a9512023-12-23 16:14:04 +0100213 _test_de_encode = [
214 ( '8a0105', 'operational_activated' ),
215 ]
Harald Weltec8c33272022-02-11 14:45:23 +0100216 def _from_bytes(self, do: bytes):
217 lcsi = int.from_bytes(do, 'big')
218 if lcsi == 0x00:
219 ret = 'no_information'
220 elif lcsi == 0x01:
221 ret = 'creation'
222 elif lcsi == 0x03:
223 ret = 'initialization'
224 elif lcsi & 0x05 == 0x05:
225 ret = 'operational_activated'
226 elif lcsi & 0x05 == 0x04:
227 ret = 'operational_deactivated'
228 elif lcsi & 0xc0 == 0xc0:
229 ret = 'termination'
230 else:
231 ret = lcsi
232 self.decoded = ret
233 return self.decoded
Harald Welte3c9b7842021-10-19 21:44:24 +0200234 def _to_bytes(self):
235 if self.decoded == 'no_information':
236 return b'\x00'
237 elif self.decoded == 'creation':
238 return b'\x01'
239 elif self.decoded == 'initialization':
240 return b'\x03'
241 elif self.decoded == 'operational_activated':
242 return b'\x05'
243 elif self.decoded == 'operational_deactivated':
244 return b'\x04'
245 elif self.decoded == 'termination':
246 return b'\x0c'
247 elif isinstance(self.decoded, int):
248 return self.decoded.to_bytes(1, 'big')
249 else:
250 raise ValueError
Harald Weltec91085e2022-02-10 18:05:45 +0100251
Harald Weltec8c33272022-02-11 14:45:23 +0100252# ETSI TS 102 221 11.1.1.4.9
253class PS_DO(BER_TLV_IE, tag=0x90):
254 _construct = GreedyBytes
255class UsageQualifier_DO(BER_TLV_IE, tag=0x95):
256 _construct = GreedyBytes
257class KeyReference(BER_TLV_IE, tag=0x83):
258 _construct = Byte
259class PinStatusTemplate_DO(BER_TLV_IE, tag=0xC6, nested=[PS_DO, UsageQualifier_DO, KeyReference]):
260 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100261
Harald Weltec8c33272022-02-11 14:45:23 +0100262class FcpTemplate(BER_TLV_IE, tag=0x62, nested=[FileSize, TotalFileSize, FileDescriptor, FileIdentifier,
263 DfName, ProprietaryInformation, SecurityAttribCompact,
264 SecurityAttribExpanded, SecurityAttribReferenced,
265 ShortFileIdentifier, LifeCycleStatusInteger,
266 PinStatusTemplate_DO]):
267 pass
Harald Welteb2edd142021-01-08 23:29:35 +0100268
269
270def tlv_key_replace(inmap, indata):
271 def newkey(inmap, key):
272 if key in inmap:
273 return inmap[key]
274 else:
275 return key
276 return {newkey(inmap, d[0]): d[1] for d in indata.items()}
277
Harald Weltec91085e2022-02-10 18:05:45 +0100278
Harald Welteb2edd142021-01-08 23:29:35 +0100279def tlv_val_interpret(inmap, indata):
280 def newval(inmap, key, val):
281 if key in inmap:
282 return inmap[key](val)
283 else:
284 return val
285 return {d[0]: newval(inmap, d[0], d[1]) for d in indata.items()}
286
Harald Welte4ae228a2021-05-02 21:29:04 +0200287# ETSI TS 102 221 Section 9.2.7 + ISO7816-4 9.3.3/9.3.4
Harald Welte4ae228a2021-05-02 21:29:04 +0200288class _AM_DO_DF(DataObject):
289 def __init__(self):
290 super().__init__('access_mode', 'Access Mode', tag=0x80)
291
Harald Weltec91085e2022-02-10 18:05:45 +0100292 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200293 res = []
294 if len(do) != 1:
295 raise ValueError("We only support single-byte AMF inside AM-DO")
296 amf = do[0]
297 # tables 17..29 and 41..44 of 7816-4
298 if amf & 0x80 == 0:
299 if amf & 0x40:
300 res.append('delete_file')
301 if amf & 0x20:
302 res.append('terminate_df')
303 if amf & 0x10:
304 res.append('activate_file')
305 if amf & 0x08:
306 res.append('deactivate_file')
307 if amf & 0x04:
308 res.append('create_file_df')
309 if amf & 0x02:
310 res.append('create_file_ef')
311 if amf & 0x01:
312 res.append('delete_file_child')
313 self.decoded = res
314
315 def to_bytes(self):
316 val = 0
317 if 'delete_file' in self.decoded:
318 val |= 0x40
319 if 'terminate_df' in self.decoded:
320 val |= 0x20
321 if 'activate_file' in self.decoded:
322 val |= 0x10
323 if 'deactivate_file' in self.decoded:
324 val |= 0x08
325 if 'create_file_df' in self.decoded:
326 val |= 0x04
327 if 'create_file_ef' in self.decoded:
328 val |= 0x02
329 if 'delete_file_child' in self.decoded:
330 val |= 0x01
331 return val.to_bytes(1, 'big')
332
333
334class _AM_DO_EF(DataObject):
335 """ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31"""
Harald Weltec91085e2022-02-10 18:05:45 +0100336
Harald Welte4ae228a2021-05-02 21:29:04 +0200337 def __init__(self):
338 super().__init__('access_mode', 'Access Mode', tag=0x80)
339
Harald Weltec91085e2022-02-10 18:05:45 +0100340 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200341 res = []
342 if len(do) != 1:
343 raise ValueError("We only support single-byte AMF inside AM-DO")
344 amf = do[0]
345 # tables 17..29 and 41..44 of 7816-4
346 if amf & 0x80 == 0:
347 if amf & 0x40:
348 res.append('delete_file')
349 if amf & 0x20:
350 res.append('terminate_ef')
351 if amf & 0x10:
352 res.append('activate_file_or_record')
353 if amf & 0x08:
354 res.append('deactivate_file_or_record')
355 if amf & 0x04:
356 res.append('write_append')
357 if amf & 0x02:
358 res.append('update_erase')
359 if amf & 0x01:
360 res.append('read_search_compare')
361 self.decoded = res
362
363 def to_bytes(self):
364 val = 0
365 if 'delete_file' in self.decoded:
366 val |= 0x40
367 if 'terminate_ef' in self.decoded:
368 val |= 0x20
369 if 'activate_file_or_record' in self.decoded:
370 val |= 0x10
371 if 'deactivate_file_or_record' in self.decoded:
372 val |= 0x08
373 if 'write_append' in self.decoded:
374 val |= 0x04
375 if 'update_erase' in self.decoded:
376 val |= 0x02
377 if 'read_search_compare' in self.decoded:
378 val |= 0x01
379 return val.to_bytes(1, 'big')
380
Harald Weltec91085e2022-02-10 18:05:45 +0100381
Harald Welte4ae228a2021-05-02 21:29:04 +0200382class _AM_DO_CHDR(DataObject):
383 """Command Header Access Mode DO according to ISO 7816-4 Table 32."""
Harald Weltec91085e2022-02-10 18:05:45 +0100384
Harald Welte4ae228a2021-05-02 21:29:04 +0200385 def __init__(self, tag):
386 super().__init__('command_header', 'Command Header Description', tag=tag)
387
Harald Weltec91085e2022-02-10 18:05:45 +0100388 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200389 res = {}
390 i = 0
391 if self.tag & 0x08:
392 res['CLA'] = do[i]
393 i += 1
394 if self.tag & 0x04:
395 res['INS'] = do[i]
396 i += 1
397 if self.tag & 0x02:
398 res['P1'] = do[i]
399 i += 1
400 if self.tag & 0x01:
401 res['P2'] = do[i]
402 i += 1
403 self.decoded = res
404
405 def _compute_tag(self):
406 """Override to encode the tag, as it depends on the value."""
407 tag = 0x80
408 if 'CLA' in self.decoded:
409 tag |= 0x08
410 if 'INS' in self.decoded:
411 tag |= 0x04
412 if 'P1' in self.decoded:
413 tag |= 0x02
414 if 'P2' in self.decoded:
415 tag |= 0x01
416 return tag
417
418 def to_bytes(self):
419 res = bytearray()
420 if 'CLA' in self.decoded:
421 res.append(self.decoded['CLA'])
422 if 'INS' in self.decoded:
423 res.append(self.decoded['INS'])
424 if 'P1' in self.decoded:
425 res.append(self.decoded['P1'])
426 if 'P2' in self.decoded:
427 res.append(self.decoded['P2'])
428 return res
429
Harald Weltec91085e2022-02-10 18:05:45 +0100430
Harald Welte4ae228a2021-05-02 21:29:04 +0200431AM_DO_CHDR = DataObjectChoice('am_do_chdr', members=[
Harald Weltec91085e2022-02-10 18:05:45 +0100432 _AM_DO_CHDR(0x81), _AM_DO_CHDR(0x82), _AM_DO_CHDR(0x83), _AM_DO_CHDR(0x84),
433 _AM_DO_CHDR(0x85), _AM_DO_CHDR(0x86), _AM_DO_CHDR(0x87), _AM_DO_CHDR(0x88),
434 _AM_DO_CHDR(0x89), _AM_DO_CHDR(0x8a), _AM_DO_CHDR(0x8b), _AM_DO_CHDR(0x8c),
435 _AM_DO_CHDR(0x8d), _AM_DO_CHDR(0x8e), _AM_DO_CHDR(0x8f)])
Harald Welte4ae228a2021-05-02 21:29:04 +0200436
437AM_DO_DF = AM_DO_CHDR | _AM_DO_DF()
438AM_DO_EF = AM_DO_CHDR | _AM_DO_EF()
439
440
441# TS 102 221 Section 9.5.1 / Table 9.3
442pin_names = bidict({
443 0x01: 'PIN1',
444 0x02: 'PIN2',
445 0x03: 'PIN3',
446 0x04: 'PIN4',
447 0x05: 'PIN5',
448 0x06: 'PIN6',
449 0x07: 'PIN7',
450 0x08: 'PIN8',
451 0x0a: 'ADM1',
452 0x0b: 'ADM2',
453 0x0c: 'ADM3',
454 0x0d: 'ADM4',
455 0x0e: 'ADM5',
456
457 0x11: 'UNIVERSAL_PIN',
458 0x81: '2PIN1',
459 0x82: '2PIN2',
460 0x83: '2PIN3',
461 0x84: '2PIN4',
462 0x85: '2PIN5',
463 0x86: '2PIN6',
464 0x87: '2PIN7',
465 0x88: '2PIN8',
466 0x8a: 'ADM6',
467 0x8b: 'ADM7',
468 0x8c: 'ADM8',
469 0x8d: 'ADM9',
470 0x8e: 'ADM10',
Harald Weltec91085e2022-02-10 18:05:45 +0100471})
472
Harald Welte4ae228a2021-05-02 21:29:04 +0200473
474class CRT_DO(DataObject):
475 """Control Reference Template as per TS 102 221 9.5.1"""
Harald Weltec91085e2022-02-10 18:05:45 +0100476
Harald Welte4ae228a2021-05-02 21:29:04 +0200477 def __init__(self):
Harald Weltec91085e2022-02-10 18:05:45 +0100478 super().__init__('control_reference_template',
479 'Control Reference Template', tag=0xA4)
Harald Welte4ae228a2021-05-02 21:29:04 +0200480
481 def from_bytes(self, do: bytes):
482 """Decode a Control Reference Template DO."""
483 if len(do) != 6:
484 raise ValueError('Unsupported CRT DO length: %s', do)
485 if do[0] != 0x83 or do[1] != 0x01:
486 raise ValueError('Unsupported Key Ref Tag or Len in CRT DO %s', do)
487 if do[3:] != b'\x95\x01\x08':
Harald Weltec91085e2022-02-10 18:05:45 +0100488 raise ValueError(
489 'Unsupported Usage Qualifier Tag or Len in CRT DO %s', do)
Harald Welte4ae228a2021-05-02 21:29:04 +0200490 self.encoded = do[0:6]
491 self.decoded = pin_names[do[2]]
492 return do[6:]
493
494 def to_bytes(self):
495 pin = pin_names.inverse[self.decoded]
496 return b'\x83\x01' + pin.to_bytes(1, 'big') + b'\x95\x01\x08'
497
498# ISO7816-4 9.3.3 Table 33
499class SecCondByte_DO(DataObject):
500 def __init__(self, tag=0x9d):
501 super().__init__('security_condition_byte', tag=tag)
502
Harald Weltec91085e2022-02-10 18:05:45 +0100503 def from_bytes(self, binary: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200504 if len(binary) != 1:
505 raise ValueError
506 inb = binary[0]
507 if inb == 0:
508 cond = 'always'
509 if inb == 0xff:
510 cond = 'never'
511 res = []
512 if inb & 0x80:
513 cond = 'and'
514 else:
515 cond = 'or'
516 if inb & 0x40:
517 res.append('secure_messaging')
518 if inb & 0x20:
519 res.append('external_auth')
520 if inb & 0x10:
521 res.append('user_auth')
Harald Weltec91085e2022-02-10 18:05:45 +0100522 rd = {'mode': cond}
Harald Welte4ae228a2021-05-02 21:29:04 +0200523 if len(res):
524 rd['conditions'] = res
525 self.decoded = rd
526
527 def to_bytes(self):
528 mode = self.decoded['mode']
529 if mode == 'always':
530 res = 0
531 elif mode == 'never':
532 res = 0xff
533 else:
534 res = 0
535 if mode == 'and':
536 res |= 0x80
537 elif mode == 'or':
538 pass
539 else:
540 raise ValueError('Unknown mode %s' % mode)
541 for c in self.decoded['conditions']:
542 if c == 'secure_messaging':
543 res |= 0x40
544 elif c == 'external_auth':
545 res |= 0x20
546 elif c == 'user_auth':
547 res |= 0x10
548 else:
549 raise ValueError('Unknown condition %s' % c)
550 return res.to_bytes(1, 'big')
551
Harald Weltec91085e2022-02-10 18:05:45 +0100552
Harald Welte4ae228a2021-05-02 21:29:04 +0200553Always_DO = TL0_DataObject('always', 'Always', 0x90)
554Never_DO = TL0_DataObject('never', 'Never', 0x97)
Harald Welteb0608332022-02-10 12:45:37 +0100555
Harald Weltec91085e2022-02-10 18:05:45 +0100556
Harald Welteb0608332022-02-10 12:45:37 +0100557class Nested_DO(DataObject):
558 """A DO that nests another DO/Choice/Sequence"""
Harald Weltec91085e2022-02-10 18:05:45 +0100559
Harald Welteb0608332022-02-10 12:45:37 +0100560 def __init__(self, name, tag, choice):
561 super().__init__(name, tag=tag)
562 self.children = choice
Harald Weltec91085e2022-02-10 18:05:45 +0100563
564 def from_bytes(self, binary: bytes) -> list:
Harald Welteb0608332022-02-10 12:45:37 +0100565 remainder = binary
566 self.decoded = []
567 while remainder:
568 rc, remainder = self.children.decode(remainder)
569 self.decoded.append(rc)
570 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100571
Harald Welteb0608332022-02-10 12:45:37 +0100572 def to_bytes(self) -> bytes:
573 encoded = [self.children.encode(d) for d in self.decoded]
574 return b''.join(encoded)
575
Harald Weltec91085e2022-02-10 18:05:45 +0100576
Harald Welteb0608332022-02-10 12:45:37 +0100577OR_Template = DataObjectChoice('or_template', 'OR-Template',
578 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
579OR_DO = Nested_DO('or', 0xa0, OR_Template)
580AND_Template = DataObjectChoice('and_template', 'AND-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100581 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100582AND_DO = Nested_DO('and', 0xa7, AND_Template)
583NOT_Template = DataObjectChoice('not_template', 'NOT-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100584 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100585NOT_DO = Nested_DO('not', 0xaf, NOT_Template)
Harald Welte4ae228a2021-05-02 21:29:04 +0200586SC_DO = DataObjectChoice('security_condition', 'Security Condition',
Harald Welteb0608332022-02-10 12:45:37 +0100587 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO(),
588 OR_DO, AND_DO, NOT_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200589
Harald Welteb2edd142021-01-08 23:29:35 +0100590# TS 102 221 Section 13.1
591class EF_DIR(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100592 # FIXME: re-encode failure when changing to _test_de_encode
593 _test_decode = [
594 ( '61294f10a0000000871002ffffffff890709000050055553696d31730ea00c80011781025f608203454150',
595 { "application_template": [ { "application_id": h2b("a0000000871002ffffffff8907090000") },
596 { "application_label": "USim1" },
597 { "discretionary_template": h2b("a00c80011781025f608203454150") } ] }
598 ),
Harald Welteee6a9512023-12-23 16:14:04 +0100599 ( '61194f10a0000000871004ffffffff890709000050054953696d31',
600 { "application_template": [ { "application_id": h2b("a0000000871004ffffffff8907090000") },
601 { "application_label": "ISim1" } ] }
602 ),
Harald Welte865eea62023-01-27 19:26:12 +0100603 ]
Harald Welte181c7c52022-02-10 14:18:32 +0100604 class ApplicationLabel(BER_TLV_IE, tag=0x50):
605 # TODO: UCS-2 coding option as per Annex A of TS 102 221
606 _construct = GreedyString('ascii')
607
608 # see https://github.com/PyCQA/pylint/issues/5794
609 #pylint: disable=undefined-variable
610 class ApplicationTemplate(BER_TLV_IE, tag=0x61,
611 nested=[iso7816_4.ApplicationId, ApplicationLabel, iso7816_4.FileReference,
612 iso7816_4.CommandApdu, iso7816_4.DiscretionaryData,
613 iso7816_4.DiscretionaryTemplate, iso7816_4.URL,
614 iso7816_4.ApplicationRelatedDOSet]):
615 pass
616
Harald Welteb2edd142021-01-08 23:29:35 +0100617 def __init__(self, fid='2f00', sfid=0x1e, name='EF.DIR', desc='Application Directory'):
Harald Welte99e4cc02022-07-21 15:25:47 +0200618 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(5, 54))
Harald Welte181c7c52022-02-10 14:18:32 +0100619 self._tlv = EF_DIR.ApplicationTemplate
Harald Welteb2edd142021-01-08 23:29:35 +0100620
621# TS 102 221 Section 13.2
622class EF_ICCID(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100623 _test_de_encode = [
624 ( '988812010000400310f0', { "iccid": "8988211000000430010" } ),
625 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100626 def __init__(self, fid='2fe2', sfid=0x02, name='EF.ICCID', desc='ICC Identification'):
Harald Welte13edf302022-07-21 15:19:23 +0200627 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=(10, 10))
Harald Welteb2edd142021-01-08 23:29:35 +0100628
629 def _decode_hex(self, raw_hex):
630 return {'iccid': dec_iccid(raw_hex)}
631
632 def _encode_hex(self, abstract):
633 return enc_iccid(abstract['iccid'])
634
635# TS 102 221 Section 13.3
636class EF_PL(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100637 _test_de_encode = [
638 ( '6465', "de" ),
639 ( '656e', "en" ),
640 ( 'ffff', None ),
641 ]
Harald Weltece01f482023-12-28 09:41:35 +0100642
Harald Welteb2edd142021-01-08 23:29:35 +0100643 def __init__(self, fid='2f05', sfid=0x05, name='EF.PL', desc='Preferred Languages'):
Harald Weltec91085e2022-02-10 18:05:45 +0100644 super().__init__(fid, sfid=sfid, name=name,
Harald Welte13edf302022-07-21 15:19:23 +0200645 desc=desc, rec_len=2, size=(2, None))
Harald Weltec91085e2022-02-10 18:05:45 +0100646
Harald Weltef6b37af2023-01-24 15:42:26 +0100647 def _decode_record_bin(self, bin_data, **kwargs):
Harald Welte0c840f02022-01-21 15:42:22 +0100648 if bin_data == b'\xff\xff':
649 return None
650 else:
651 return bin_data.decode('ascii')
Harald Weltec91085e2022-02-10 18:05:45 +0100652
Harald Weltef6b37af2023-01-24 15:42:26 +0100653 def _encode_record_bin(self, in_json, **kwargs):
Harald Welte0c840f02022-01-21 15:42:22 +0100654 if in_json is None:
655 return b'\xff\xff'
656 else:
657 return in_json.encode('ascii')
658
Harald Welteb2edd142021-01-08 23:29:35 +0100659
660# TS 102 221 Section 13.4
661class EF_ARR(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100662 _test_de_encode = [
663 ( '800101a40683010a950108800106900080016097008401d4a40683010a950108',
664 [ [ { "access_mode": [ "read_search_compare" ] },
665 { "control_reference_template": "ADM1" } ],
666 [ { "access_mode": [ "write_append", "update_erase" ] },
667 { "always": None } ],
668 [ { "access_mode": [ "delete_file", "terminate_ef" ] },
669 { "never": None } ],
670 [ { "command_header": { "INS": 212 } },
671 { "control_reference_template": "ADM1" } ]
672 ] ),
673 ( '80010190008001029700800118a40683010a9501088401d4a40683010a950108',
674 [ [ { "access_mode": [ "read_search_compare" ] },
675 { "always": None } ],
676 [ { "access_mode": [ "update_erase" ] },
677 { "never": None } ],
678 [ { "access_mode": [ "activate_file_or_record", "deactivate_file_or_record" ] },
679 { "control_reference_template": "ADM1" } ],
680 [ { "command_header": { "INS": 212 } },
681 { "control_reference_template": "ADM1" } ]
682 ] ),
683 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100684 def __init__(self, fid='2f06', sfid=0x06, name='EF.ARR', desc='Access Rule Reference'):
685 super().__init__(fid, sfid=sfid, name=name, desc=desc)
Harald Welte4ae228a2021-05-02 21:29:04 +0200686 # add those commands to the general commands of a TransparentEF
687 self.shell_commands += [self.AddlShellCommands()]
688
689 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100690 def flatten(inp: list):
Harald Welte4ae228a2021-05-02 21:29:04 +0200691 """Flatten the somewhat deep/complex/nested data returned from decoder."""
692 def sc_abbreviate(sc):
693 if 'always' in sc:
694 return 'always'
695 elif 'never' in sc:
696 return 'never'
697 elif 'control_reference_template' in sc:
698 return sc['control_reference_template']
699 else:
700 return sc
701
702 by_mode = {}
703 for t in inp:
704 am = t[0]
705 sc = t[1]
706 sc_abbr = sc_abbreviate(sc)
707 if 'access_mode' in am:
708 for m in am['access_mode']:
709 by_mode[m] = sc_abbr
710 elif 'command_header' in am:
711 ins = am['command_header']['INS']
712 if 'CLA' in am['command_header']:
713 cla = am['command_header']['CLA']
714 else:
715 cla = None
716 cmd = ts_102_22x_cmdset.lookup(ins, cla)
717 if cmd:
Harald Weltec91085e2022-02-10 18:05:45 +0100718 name = cmd.name.lower().replace(' ', '_')
Harald Welte4ae228a2021-05-02 21:29:04 +0200719 by_mode[name] = sc_abbr
720 else:
721 raise ValueError
722 else:
723 raise ValueError
724 return by_mode
725
Harald Weltef6b37af2023-01-24 15:42:26 +0100726 def _decode_record_bin(self, raw_bin_data, **kwargs):
Harald Welte4ae228a2021-05-02 21:29:04 +0200727 # we can only guess if we should decode for EF or DF here :(
Harald Weltec91085e2022-02-10 18:05:45 +0100728 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200729 dec = arr_seq.decode_multi(raw_bin_data)
730 # we cannot pass the result through flatten() here, as we don't have a related
731 # 'un-flattening' decoder, and hence would be unable to encode :(
732 return dec[0]
733
Harald Weltef6b37af2023-01-24 15:42:26 +0100734 def _encode_record_bin(self, in_json, **kwargs):
Harald Weltec30bed22022-04-05 14:45:18 +0200735 # we can only guess if we should decode for EF or DF here :(
736 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
737 return arr_seq.encode_multi(in_json)
738
Harald Welte4ae228a2021-05-02 21:29:04 +0200739 @with_default_category('File-Specific Commands')
740 class AddlShellCommands(CommandSet):
741 def __init__(self):
742 super().__init__()
743
744 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_rec_dec_parser)
745 def do_read_arr_record(self, opts):
746 """Read one EF.ARR record in flattened, human-friendly form."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200747 (data, sw) = self._cmd.lchan.read_record_dec(opts.record_nr)
748 data = self._cmd.lchan.selected_file.flatten(data)
Harald Welte4ae228a2021-05-02 21:29:04 +0200749 self._cmd.poutput_json(data, opts.oneline)
750
751 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_recs_dec_parser)
752 def do_read_arr_records(self, opts):
753 """Read + decode all EF.ARR records in flattened, human-friendly form."""
Harald Weltea6c0f882022-07-17 14:23:17 +0200754 num_of_rec = self._cmd.lchan.selected_file_num_of_rec()
Harald Welte4ae228a2021-05-02 21:29:04 +0200755 # collect all results in list so they are rendered as JSON list when printing
756 data_list = []
757 for recnr in range(1, 1 + num_of_rec):
Harald Weltea6c0f882022-07-17 14:23:17 +0200758 (data, sw) = self._cmd.lchan.read_record_dec(recnr)
759 data = self._cmd.lchan.selected_file.flatten(data)
Harald Welte4ae228a2021-05-02 21:29:04 +0200760 data_list.append(data)
761 self._cmd.poutput_json(data_list, opts.oneline)
762
Harald Welteb2edd142021-01-08 23:29:35 +0100763
764# TS 102 221 Section 13.6
765class EF_UMPC(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100766 _test_de_encode = [
767 ( '3cff02', { "max_current_mA": 60, "t_op_s": 255,
768 "addl_info": { "req_inc_idle_current": False, "support_uicc_suspend": True } } ),
Harald Welte324175f2023-12-21 20:25:30 +0100769 ( '320500', { "max_current_mA": 50, "t_op_s": 5, "addl_info": {"req_inc_idle_current": False,
770 "support_uicc_suspend": False } } ),
Harald Welte865eea62023-01-27 19:26:12 +0100771 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100772 def __init__(self, fid='2f08', sfid=0x08, name='EF.UMPC', desc='UICC Maximum Power Consumption'):
Harald Welte13edf302022-07-21 15:19:23 +0200773 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=(5, 5))
Harald Weltec91085e2022-02-10 18:05:45 +0100774 addl_info = FlagsEnum(Byte, req_inc_idle_current=1,
775 support_uicc_suspend=2)
776 self._construct = Struct(
777 'max_current_mA'/Int8ub, 't_op_s'/Int8ub, 'addl_info'/addl_info)
778
Harald Welteb2edd142021-01-08 23:29:35 +0100779
Harald Welteb2edd142021-01-08 23:29:35 +0100780class CardProfileUICC(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +0100781
782 ORDER = 1
783
Harald Weltec91085e2022-02-10 18:05:45 +0100784 def __init__(self, name='UICC'):
Harald Welteb2edd142021-01-08 23:29:35 +0100785 files = [
786 EF_DIR(),
787 EF_ICCID(),
788 EF_PL(),
789 EF_ARR(),
790 # FIXME: DF.CD
791 EF_UMPC(),
792 ]
Harald Welte323a3502023-07-11 17:26:39 +0200793 addons = [
794 AddonSIM,
795 AddonGSMR,
796 AddonRUIM,
797 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100798 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +0100799 'Normal': {
800 '9000': 'Normal ending of the command',
801 '91xx': 'Normal ending of the command, with extra information from the proactive UICC containing a command for the terminal',
802 '92xx': 'Normal ending of the command, with extra information concerning an ongoing data transfer session',
Harald Welteb2edd142021-01-08 23:29:35 +0100803 },
Harald Weltec91085e2022-02-10 18:05:45 +0100804 'Postponed processing': {
805 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Harald Welteb2edd142021-01-08 23:29:35 +0100806 },
Harald Weltec91085e2022-02-10 18:05:45 +0100807 'Warnings': {
808 '6200': 'No information given, state of non-volatile memory unchanged',
809 '6281': 'Part of returned data may be corrupted',
810 '6282': 'End of file/record reached before reading Le bytes or unsuccessful search',
811 '6283': 'Selected file invalidated',
812 '6284': 'Selected file in termination state',
813 '62f1': 'More data available',
814 '62f2': 'More data available and proactive command pending',
815 '62f3': 'Response data available',
816 '63f1': 'More data expected',
817 '63f2': 'More data expected and proactive command pending',
818 '63cx': 'Command successful but after using an internal update retry routine X times',
Harald Welteb2edd142021-01-08 23:29:35 +0100819 },
Harald Weltec91085e2022-02-10 18:05:45 +0100820 'Execution errors': {
821 '6400': 'No information given, state of non-volatile memory unchanged',
822 '6500': 'No information given, state of non-volatile memory changed',
823 '6581': 'Memory problem',
Harald Welteb2edd142021-01-08 23:29:35 +0100824 },
Harald Weltec91085e2022-02-10 18:05:45 +0100825 'Checking errors': {
826 '6700': 'Wrong length',
827 '67xx': 'The interpretation of this status word is command dependent',
828 '6b00': 'Wrong parameter(s) P1-P2',
829 '6d00': 'Instruction code not supported or invalid',
830 '6e00': 'Class not supported',
831 '6f00': 'Technical problem, no precise diagnosis',
832 '6fxx': 'The interpretation of this status word is command dependent',
Harald Welteb2edd142021-01-08 23:29:35 +0100833 },
Harald Weltec91085e2022-02-10 18:05:45 +0100834 'Functions in CLA not supported': {
835 '6800': 'No information given',
836 '6881': 'Logical channel not supported',
837 '6882': 'Secure messaging not supported',
Harald Welteb2edd142021-01-08 23:29:35 +0100838 },
Harald Weltec91085e2022-02-10 18:05:45 +0100839 'Command not allowed': {
840 '6900': 'No information given',
841 '6981': 'Command incompatible with file structure',
842 '6982': 'Security status not satisfied',
843 '6983': 'Authentication/PIN method blocked',
844 '6984': 'Referenced data invalidated',
845 '6985': 'Conditions of use not satisfied',
846 '6986': 'Command not allowed (no EF selected)',
847 '6989': 'Command not allowed - secure channel - security not satisfied',
Harald Welteb2edd142021-01-08 23:29:35 +0100848 },
Harald Weltec91085e2022-02-10 18:05:45 +0100849 'Wrong parameters': {
850 '6a80': 'Incorrect parameters in the data field',
851 '6a81': 'Function not supported',
852 '6a82': 'File not found',
853 '6a83': 'Record not found',
854 '6a84': 'Not enough memory space',
855 '6a86': 'Incorrect parameters P1 to P2',
856 '6a87': 'Lc inconsistent with P1 to P2',
857 '6a88': 'Referenced data not found',
Harald Welteb2edd142021-01-08 23:29:35 +0100858 },
Harald Weltec91085e2022-02-10 18:05:45 +0100859 'Application errors': {
860 '9850': 'INCREASE cannot be performed, max value reached',
861 '9862': 'Authentication error, application specific',
862 '9863': 'Security session or association expired',
863 '9864': 'Minimum UICC suspension time is too long',
Harald Welteb2edd142021-01-08 23:29:35 +0100864 },
Harald Weltec91085e2022-02-10 18:05:45 +0100865 }
Harald Welteb2edd142021-01-08 23:29:35 +0100866
Harald Weltec91085e2022-02-10 18:05:45 +0100867 super().__init__(name, desc='ETSI TS 102 221', cla="00",
Harald Welte659781c2023-06-06 17:00:51 +0200868 sel_ctrl="0004", files_in_mf=files, sw=sw,
Harald Welte323a3502023-07-11 17:26:39 +0200869 shell_cmdsets = [self.AddlShellCommands()], addons = addons)
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100870
Philipp Maier5998a3a2021-11-16 15:16:39 +0100871 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100872 def decode_select_response(resp_hex: str) -> object:
Philipp Maier5998a3a2021-11-16 15:16:39 +0100873 """ETSI TS 102 221 Section 11.1.1.3"""
Harald Weltec8c33272022-02-11 14:45:23 +0100874 t = FcpTemplate()
875 t.from_tlv(h2b(resp_hex))
876 d = t.to_dict()
877 return flatten_dict_lists(d['fcp_template'])
Philipp Maiera028c7d2021-11-08 16:12:03 +0100878
879 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100880 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100881 return match_uicc(scc)
882
Harald Welte659781c2023-06-06 17:00:51 +0200883 @with_default_category('TS 102 221 Specific Commands')
884 class AddlShellCommands(CommandSet):
885 suspend_uicc_parser = argparse.ArgumentParser()
886 suspend_uicc_parser.add_argument('--min-duration-secs', type=int, default=60,
887 help='Proposed minimum duration of suspension')
888 suspend_uicc_parser.add_argument('--max-duration-secs', type=int, default=24*60*60,
889 help='Proposed maximum duration of suspension')
890
891 # not ISO7816-4 but TS 102 221
892 @cmd2.with_argparser(suspend_uicc_parser)
893 def do_suspend_uicc(self, opts):
Harald Welteb0e0dce2023-06-06 17:21:13 +0200894 """Perform the SUSPEND UICC command. Only supported on some UICC (check EF.UMPC)."""
Harald Welte659781c2023-06-06 17:00:51 +0200895 (duration, token, sw) = self._cmd.card._scc.suspend_uicc(min_len_secs=opts.min_duration_secs,
896 max_len_secs=opts.max_duration_secs)
897 self._cmd.poutput(
898 'Negotiated Duration: %u secs, Token: %s, SW: %s' % (duration, token, sw))
899
Harald Welteb0e0dce2023-06-06 17:21:13 +0200900 resume_uicc_parser = argparse.ArgumentParser()
901 resume_uicc_parser.add_argument('token', type=str, help='Token provided during SUSPEND')
902
903 @cmd2.with_argparser(resume_uicc_parser)
904 def do_resume_uicc(self, opts):
905 """Perform the REUSME UICC operation. Only supported on some UICC. Also: A power-cycle
906 of the card is required between SUSPEND and RESUME, and only very few non-RESUME
907 commands are permitted between SUSPEND and RESUME. See TS 102 221 Section 11.1.22."""
908 self._cmd.card._scc.resume_uicc(opts.token)