blob: 08e836c05c8accd37e4ea664c83b6fadc97fc779 [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
34from pySim.ts_51_011 import DF_GSM, DF_TELECOM
Harald Welte4ae228a2021-05-02 21:29:04 +020035
36ts_102_22x_cmdset = CardCommandSet('TS 102 22x', [
37 # TS 102 221 Section 10.1.2 Table 10.5 "Coding of Instruction Byte"
38 CardCommand('SELECT', 0xA4, ['0X', '4X', '6X']),
39 CardCommand('STATUS', 0xF2, ['8X', 'CX', 'EX']),
40 CardCommand('READ BINARY', 0xB0, ['0X', '4X', '6X']),
41 CardCommand('UPDATE BINARY', 0xD6, ['0X', '4X', '6X']),
42 CardCommand('READ RECORD', 0xB2, ['0X', '4X', '6X']),
43 CardCommand('UPDATE RECORD', 0xDC, ['0X', '4X', '6X']),
44 CardCommand('SEARCH RECORD', 0xA2, ['0X', '4X', '6X']),
45 CardCommand('INCREASE', 0x32, ['8X', 'CX', 'EX']),
46 CardCommand('RETRIEVE DATA', 0xCB, ['8X', 'CX', 'EX']),
47 CardCommand('SET DATA', 0xDB, ['8X', 'CX', 'EX']),
48 CardCommand('VERIFY PIN', 0x20, ['0X', '4X', '6X']),
49 CardCommand('CHANGE PIN', 0x24, ['0X', '4X', '6X']),
50 CardCommand('DISABLE PIN', 0x26, ['0X', '4X', '6X']),
51 CardCommand('ENABLE PIN', 0x28, ['0X', '4X', '6X']),
52 CardCommand('UNBLOCK PIN', 0x2C, ['0X', '4X', '6X']),
53 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X', '6X']),
54 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X', '6X']),
55 CardCommand('AUTHENTICATE', 0x88, ['0X', '4X', '6X']),
56 CardCommand('AUTHENTICATE', 0x89, ['0X', '4X', '6X']),
57 CardCommand('GET CHALLENGE', 0x84, ['0X', '4X', '6X']),
58 CardCommand('TERMINAL CAPABILITY', 0xAA, ['8X', 'CX', 'EX']),
59 CardCommand('TERMINAL PROFILE', 0x10, ['80']),
60 CardCommand('ENVELOPE', 0xC2, ['80']),
61 CardCommand('FETCH', 0x12, ['80']),
62 CardCommand('TERMINAL RESPONSE', 0x14, ['80']),
63 CardCommand('MANAGE CHANNEL', 0x70, ['0X', '4X', '6X']),
64 CardCommand('MANAGE SECURE CHANNEL', 0x73, ['0X', '4X', '6X']),
65 CardCommand('TRANSACT DATA', 0x75, ['0X', '4X', '6X']),
66 CardCommand('SUSPEND UICC', 0x76, ['80']),
67 CardCommand('GET IDENTITY', 0x78, ['8X', 'CX', 'EX']),
68 CardCommand('EXCHANGE CAPABILITIES', 0x7A, ['80']),
69 CardCommand('GET RESPONSE', 0xC0, ['0X', '4X', '6X']),
70 # TS 102 222 Section 6.1 Table 1 "Coding of the commands"
71 CardCommand('CREATE FILE', 0xE0, ['0X', '4X']),
72 CardCommand('DELETE FILE', 0xE4, ['0X', '4X']),
73 CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X']),
74 CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X']),
75 CardCommand('TERMINATE DF', 0xE6, ['0X', '4X']),
76 CardCommand('TERMINATE EF', 0xE8, ['0X', '4X']),
77 CardCommand('TERMINATE CARD USAGE', 0xFE, ['0X', '4X']),
78 CardCommand('RESIZE FILE', 0xD4, ['8X', 'CX']),
Harald Weltec91085e2022-02-10 18:05:45 +010079])
Harald Welteb2edd142021-01-08 23:29:35 +010080
Harald Weltec8c33272022-02-11 14:45:23 +010081# ETSI TS 102 221 11.1.1.4.2
82class FileSize(BER_TLV_IE, tag=0x80):
Philipp Maier541a9152022-06-01 18:21:17 +020083 _construct = GreedyInteger(minlen=2)
Harald Welteb2edd142021-01-08 23:29:35 +010084
Harald Weltec8c33272022-02-11 14:45:23 +010085# ETSI TS 102 221 11.1.1.4.2
86class TotalFileSize(BER_TLV_IE, tag=0x81):
Philipp Maier541a9152022-06-01 18:21:17 +020087 _construct = GreedyInteger(minlen=2)
Harald Welteb2edd142021-01-08 23:29:35 +010088
89# ETSI TS 102 221 11.1.1.4.3
Harald Weltec8c33272022-02-11 14:45:23 +010090class FileDescriptor(BER_TLV_IE, tag=0x82):
Harald Welte747a9782022-02-13 17:52:28 +010091 class BerTlvAdapter(Adapter):
92 def _parse(self, obj, context, path):
93 if obj == 0x39:
94 return 'ber_tlv'
95 raise ValidationError
96 def _build(self, obj, context, path):
97 if obj == 'ber_tlv':
98 return 0x39
99 raise ValidationError
100
101 FDB = Select(BitStruct(Const(0, Bit), 'shareable'/Flag, 'structure'/BerTlvAdapter(Const(0x39, BitsInteger(6)))),
102 BitStruct(Const(0, Bit), 'shareable'/Flag, 'file_type'/Enum(BitsInteger(3), working_ef=0, internal_ef=1, df=7),
103 'structure'/Enum(BitsInteger(3), no_info_given=0, transparent=1, linear_fixed=2, cyclic=6))
104 )
105 _construct = Struct('file_descriptor_byte'/FDB, Const(b'\x21'),
Harald Welte4ebeebf2022-02-25 09:47:51 +0100106 'record_len'/COptional(Int16ub), 'num_of_rec'/COptional(Int8ub))
Harald Weltec91085e2022-02-10 18:05:45 +0100107
Harald Weltec8c33272022-02-11 14:45:23 +0100108# ETSI TS 102 221 11.1.1.4.4
109class FileIdentifier(BER_TLV_IE, tag=0x83):
Harald Welte3c9b7842021-10-19 21:44:24 +0200110 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100111
Harald Weltec8c33272022-02-11 14:45:23 +0100112# ETSI TS 102 221 11.1.1.4.5
113class DfName(BER_TLV_IE, tag=0x84):
Harald Welte3c9b7842021-10-19 21:44:24 +0200114 _construct = HexAdapter(GreedyBytes)
Harald Weltec8c33272022-02-11 14:45:23 +0100115
116# ETSI TS 102 221 11.1.1.4.6.1
117class UiccCharacteristics(BER_TLV_IE, tag=0x80):
118 _construct = GreedyBytes
119
120# ETSI TS 102 221 11.1.1.4.6.2
121class ApplicationPowerConsumption(BER_TLV_IE, tag=0x81):
122 _construct = Struct('voltage_class'/Int8ub,
123 'power_consumption_ma'/Int8ub,
124 'reference_freq_100k'/Int8ub)
125
126# ETSI TS 102 221 11.1.1.4.6.3
127class MinApplicationClockFrequency(BER_TLV_IE, tag=0x82):
128 _construct = Int8ub
129
130# ETSI TS 102 221 11.1.1.4.6.4
131class AvailableMemory(BER_TLV_IE, tag=0x83):
132 _construct = GreedyInteger()
133
134# ETSI TS 102 221 11.1.1.4.6.5
135class FileDetails(BER_TLV_IE, tag=0x84):
136 _construct = FlagsEnum(Byte, der_coding_only=1)
137
138# ETSI TS 102 221 11.1.1.4.6.6
139class ReservedFileSize(BER_TLV_IE, tag=0x85):
140 _construct = GreedyInteger()
141
142# ETSI TS 102 221 11.1.1.4.6.7
143class MaximumFileSize(BER_TLV_IE, tag=0x86):
144 _construct = GreedyInteger()
145
146# ETSI TS 102 221 11.1.1.4.6.8
147class SupportedFilesystemCommands(BER_TLV_IE, tag=0x87):
148 _construct = FlagsEnum(Byte, terminal_capability=1)
149
150# ETSI TS 102 221 11.1.1.4.6.9
151class SpecificUiccEnvironmentConditions(BER_TLV_IE, tag=0x88):
152 _construct = BitStruct('rfu'/BitsRFU(4),
153 'high_humidity_supported'/Flag,
154 'temperature_class'/Enum(BitsInteger(3), standard=0, class_A=1, class_B=2, class_C=3))
155
156# ETSI TS 102 221 11.1.1.4.6.10
157class Platform2PlatformCatSecuredApdu(BER_TLV_IE, tag=0x89):
158 _construct = GreedyBytes
159
Harald Welte3c9b7842021-10-19 21:44:24 +0200160# sysmoISIM-SJA2 specific
161class ToolkitAccessConditions(BER_TLV_IE, tag=0xD2):
162 _construct = FlagsEnum(Byte, rfm_create=1, rfm_delete_terminate=2, other_applet_create=4,
163 other_applet_delete_terminate=8)
164
Harald Weltec8c33272022-02-11 14:45:23 +0100165# ETSI TS 102 221 11.1.1.4.6.0
166class ProprietaryInformation(BER_TLV_IE, tag=0xA5,
167 nested=[UiccCharacteristics, ApplicationPowerConsumption,
168 MinApplicationClockFrequency, AvailableMemory,
169 FileDetails, ReservedFileSize, MaximumFileSize,
Harald Welte3c9b7842021-10-19 21:44:24 +0200170 SupportedFilesystemCommands, SpecificUiccEnvironmentConditions,
171 ToolkitAccessConditions]):
Harald Weltec8c33272022-02-11 14:45:23 +0100172 pass
173
174# ETSI TS 102 221 11.1.1.4.7.1
175class SecurityAttribCompact(BER_TLV_IE, tag=0x8c):
176 _construct = GreedyBytes
177
178# ETSI TS 102 221 11.1.1.4.7.2
179class SecurityAttribExpanded(BER_TLV_IE, tag=0xab):
180 _construct = GreedyBytes
181
182# ETSI TS 102 221 11.1.1.4.7.3
183class SecurityAttribReferenced(BER_TLV_IE, tag=0x8b):
184 # TODO: longer format with SEID
Harald Welte3c9b7842021-10-19 21:44:24 +0200185 _construct = Struct('ef_arr_file_id'/HexAdapter(Bytes(2)), 'ef_arr_record_nr'/Int8ub)
Harald Weltec8c33272022-02-11 14:45:23 +0100186
187# ETSI TS 102 221 11.1.1.4.8
188class ShortFileIdentifier(BER_TLV_IE, tag=0x88):
Harald Welte5e9bd932022-02-25 09:35:28 +0100189 # If the length of the TLV is 1, the SFI value is indicated in the 5 most significant bits (bits b8 to b4)
190 # of the TLV value field. In this case, bits b3 to b1 shall be set to 0
191 class Shift3RAdapter(Adapter):
192 def _decode(self, obj, context, path):
Philipp Maier373b23c2022-06-01 18:16:02 +0200193 return int.from_bytes(obj, 'big') >> 3
Harald Welte5e9bd932022-02-25 09:35:28 +0100194 def _encode(self, obj, context, path):
Philipp Maier373b23c2022-06-01 18:16:02 +0200195 val = int(obj) << 3
196 return val.to_bytes(1, 'big')
197 _construct = COptional(Shift3RAdapter(Bytes(1)))
Harald Welteb2edd142021-01-08 23:29:35 +0100198
199# ETSI TS 102 221 11.1.1.4.9
Harald Weltec8c33272022-02-11 14:45:23 +0100200class LifeCycleStatusInteger(BER_TLV_IE, tag=0x8A):
201 def _from_bytes(self, do: bytes):
202 lcsi = int.from_bytes(do, 'big')
203 if lcsi == 0x00:
204 ret = 'no_information'
205 elif lcsi == 0x01:
206 ret = 'creation'
207 elif lcsi == 0x03:
208 ret = 'initialization'
209 elif lcsi & 0x05 == 0x05:
210 ret = 'operational_activated'
211 elif lcsi & 0x05 == 0x04:
212 ret = 'operational_deactivated'
213 elif lcsi & 0xc0 == 0xc0:
214 ret = 'termination'
215 else:
216 ret = lcsi
217 self.decoded = ret
218 return self.decoded
Harald Welte3c9b7842021-10-19 21:44:24 +0200219 def _to_bytes(self):
220 if self.decoded == 'no_information':
221 return b'\x00'
222 elif self.decoded == 'creation':
223 return b'\x01'
224 elif self.decoded == 'initialization':
225 return b'\x03'
226 elif self.decoded == 'operational_activated':
227 return b'\x05'
228 elif self.decoded == 'operational_deactivated':
229 return b'\x04'
230 elif self.decoded == 'termination':
231 return b'\x0c'
232 elif isinstance(self.decoded, int):
233 return self.decoded.to_bytes(1, 'big')
234 else:
235 raise ValueError
Harald Weltec91085e2022-02-10 18:05:45 +0100236
Harald Weltec8c33272022-02-11 14:45:23 +0100237# ETSI TS 102 221 11.1.1.4.9
238class PS_DO(BER_TLV_IE, tag=0x90):
239 _construct = GreedyBytes
240class UsageQualifier_DO(BER_TLV_IE, tag=0x95):
241 _construct = GreedyBytes
242class KeyReference(BER_TLV_IE, tag=0x83):
243 _construct = Byte
244class PinStatusTemplate_DO(BER_TLV_IE, tag=0xC6, nested=[PS_DO, UsageQualifier_DO, KeyReference]):
245 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100246
Harald Weltec8c33272022-02-11 14:45:23 +0100247class FcpTemplate(BER_TLV_IE, tag=0x62, nested=[FileSize, TotalFileSize, FileDescriptor, FileIdentifier,
248 DfName, ProprietaryInformation, SecurityAttribCompact,
249 SecurityAttribExpanded, SecurityAttribReferenced,
250 ShortFileIdentifier, LifeCycleStatusInteger,
251 PinStatusTemplate_DO]):
252 pass
Harald Welteb2edd142021-01-08 23:29:35 +0100253
254
255def tlv_key_replace(inmap, indata):
256 def newkey(inmap, key):
257 if key in inmap:
258 return inmap[key]
259 else:
260 return key
261 return {newkey(inmap, d[0]): d[1] for d in indata.items()}
262
Harald Weltec91085e2022-02-10 18:05:45 +0100263
Harald Welteb2edd142021-01-08 23:29:35 +0100264def tlv_val_interpret(inmap, indata):
265 def newval(inmap, key, val):
266 if key in inmap:
267 return inmap[key](val)
268 else:
269 return val
270 return {d[0]: newval(inmap, d[0], d[1]) for d in indata.items()}
271
Harald Welte4ae228a2021-05-02 21:29:04 +0200272# ETSI TS 102 221 Section 9.2.7 + ISO7816-4 9.3.3/9.3.4
Harald Welte4ae228a2021-05-02 21:29:04 +0200273class _AM_DO_DF(DataObject):
274 def __init__(self):
275 super().__init__('access_mode', 'Access Mode', tag=0x80)
276
Harald Weltec91085e2022-02-10 18:05:45 +0100277 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200278 res = []
279 if len(do) != 1:
280 raise ValueError("We only support single-byte AMF inside AM-DO")
281 amf = do[0]
282 # tables 17..29 and 41..44 of 7816-4
283 if amf & 0x80 == 0:
284 if amf & 0x40:
285 res.append('delete_file')
286 if amf & 0x20:
287 res.append('terminate_df')
288 if amf & 0x10:
289 res.append('activate_file')
290 if amf & 0x08:
291 res.append('deactivate_file')
292 if amf & 0x04:
293 res.append('create_file_df')
294 if amf & 0x02:
295 res.append('create_file_ef')
296 if amf & 0x01:
297 res.append('delete_file_child')
298 self.decoded = res
299
300 def to_bytes(self):
301 val = 0
302 if 'delete_file' in self.decoded:
303 val |= 0x40
304 if 'terminate_df' in self.decoded:
305 val |= 0x20
306 if 'activate_file' in self.decoded:
307 val |= 0x10
308 if 'deactivate_file' in self.decoded:
309 val |= 0x08
310 if 'create_file_df' in self.decoded:
311 val |= 0x04
312 if 'create_file_ef' in self.decoded:
313 val |= 0x02
314 if 'delete_file_child' in self.decoded:
315 val |= 0x01
316 return val.to_bytes(1, 'big')
317
318
319class _AM_DO_EF(DataObject):
320 """ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31"""
Harald Weltec91085e2022-02-10 18:05:45 +0100321
Harald Welte4ae228a2021-05-02 21:29:04 +0200322 def __init__(self):
323 super().__init__('access_mode', 'Access Mode', tag=0x80)
324
Harald Weltec91085e2022-02-10 18:05:45 +0100325 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200326 res = []
327 if len(do) != 1:
328 raise ValueError("We only support single-byte AMF inside AM-DO")
329 amf = do[0]
330 # tables 17..29 and 41..44 of 7816-4
331 if amf & 0x80 == 0:
332 if amf & 0x40:
333 res.append('delete_file')
334 if amf & 0x20:
335 res.append('terminate_ef')
336 if amf & 0x10:
337 res.append('activate_file_or_record')
338 if amf & 0x08:
339 res.append('deactivate_file_or_record')
340 if amf & 0x04:
341 res.append('write_append')
342 if amf & 0x02:
343 res.append('update_erase')
344 if amf & 0x01:
345 res.append('read_search_compare')
346 self.decoded = res
347
348 def to_bytes(self):
349 val = 0
350 if 'delete_file' in self.decoded:
351 val |= 0x40
352 if 'terminate_ef' in self.decoded:
353 val |= 0x20
354 if 'activate_file_or_record' in self.decoded:
355 val |= 0x10
356 if 'deactivate_file_or_record' in self.decoded:
357 val |= 0x08
358 if 'write_append' in self.decoded:
359 val |= 0x04
360 if 'update_erase' in self.decoded:
361 val |= 0x02
362 if 'read_search_compare' in self.decoded:
363 val |= 0x01
364 return val.to_bytes(1, 'big')
365
Harald Weltec91085e2022-02-10 18:05:45 +0100366
Harald Welte4ae228a2021-05-02 21:29:04 +0200367class _AM_DO_CHDR(DataObject):
368 """Command Header Access Mode DO according to ISO 7816-4 Table 32."""
Harald Weltec91085e2022-02-10 18:05:45 +0100369
Harald Welte4ae228a2021-05-02 21:29:04 +0200370 def __init__(self, tag):
371 super().__init__('command_header', 'Command Header Description', tag=tag)
372
Harald Weltec91085e2022-02-10 18:05:45 +0100373 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200374 res = {}
375 i = 0
376 if self.tag & 0x08:
377 res['CLA'] = do[i]
378 i += 1
379 if self.tag & 0x04:
380 res['INS'] = do[i]
381 i += 1
382 if self.tag & 0x02:
383 res['P1'] = do[i]
384 i += 1
385 if self.tag & 0x01:
386 res['P2'] = do[i]
387 i += 1
388 self.decoded = res
389
390 def _compute_tag(self):
391 """Override to encode the tag, as it depends on the value."""
392 tag = 0x80
393 if 'CLA' in self.decoded:
394 tag |= 0x08
395 if 'INS' in self.decoded:
396 tag |= 0x04
397 if 'P1' in self.decoded:
398 tag |= 0x02
399 if 'P2' in self.decoded:
400 tag |= 0x01
401 return tag
402
403 def to_bytes(self):
404 res = bytearray()
405 if 'CLA' in self.decoded:
406 res.append(self.decoded['CLA'])
407 if 'INS' in self.decoded:
408 res.append(self.decoded['INS'])
409 if 'P1' in self.decoded:
410 res.append(self.decoded['P1'])
411 if 'P2' in self.decoded:
412 res.append(self.decoded['P2'])
413 return res
414
Harald Weltec91085e2022-02-10 18:05:45 +0100415
Harald Welte4ae228a2021-05-02 21:29:04 +0200416AM_DO_CHDR = DataObjectChoice('am_do_chdr', members=[
Harald Weltec91085e2022-02-10 18:05:45 +0100417 _AM_DO_CHDR(0x81), _AM_DO_CHDR(0x82), _AM_DO_CHDR(0x83), _AM_DO_CHDR(0x84),
418 _AM_DO_CHDR(0x85), _AM_DO_CHDR(0x86), _AM_DO_CHDR(0x87), _AM_DO_CHDR(0x88),
419 _AM_DO_CHDR(0x89), _AM_DO_CHDR(0x8a), _AM_DO_CHDR(0x8b), _AM_DO_CHDR(0x8c),
420 _AM_DO_CHDR(0x8d), _AM_DO_CHDR(0x8e), _AM_DO_CHDR(0x8f)])
Harald Welte4ae228a2021-05-02 21:29:04 +0200421
422AM_DO_DF = AM_DO_CHDR | _AM_DO_DF()
423AM_DO_EF = AM_DO_CHDR | _AM_DO_EF()
424
425
426# TS 102 221 Section 9.5.1 / Table 9.3
427pin_names = bidict({
428 0x01: 'PIN1',
429 0x02: 'PIN2',
430 0x03: 'PIN3',
431 0x04: 'PIN4',
432 0x05: 'PIN5',
433 0x06: 'PIN6',
434 0x07: 'PIN7',
435 0x08: 'PIN8',
436 0x0a: 'ADM1',
437 0x0b: 'ADM2',
438 0x0c: 'ADM3',
439 0x0d: 'ADM4',
440 0x0e: 'ADM5',
441
442 0x11: 'UNIVERSAL_PIN',
443 0x81: '2PIN1',
444 0x82: '2PIN2',
445 0x83: '2PIN3',
446 0x84: '2PIN4',
447 0x85: '2PIN5',
448 0x86: '2PIN6',
449 0x87: '2PIN7',
450 0x88: '2PIN8',
451 0x8a: 'ADM6',
452 0x8b: 'ADM7',
453 0x8c: 'ADM8',
454 0x8d: 'ADM9',
455 0x8e: 'ADM10',
Harald Weltec91085e2022-02-10 18:05:45 +0100456})
457
Harald Welte4ae228a2021-05-02 21:29:04 +0200458
459class CRT_DO(DataObject):
460 """Control Reference Template as per TS 102 221 9.5.1"""
Harald Weltec91085e2022-02-10 18:05:45 +0100461
Harald Welte4ae228a2021-05-02 21:29:04 +0200462 def __init__(self):
Harald Weltec91085e2022-02-10 18:05:45 +0100463 super().__init__('control_reference_template',
464 'Control Reference Template', tag=0xA4)
Harald Welte4ae228a2021-05-02 21:29:04 +0200465
466 def from_bytes(self, do: bytes):
467 """Decode a Control Reference Template DO."""
468 if len(do) != 6:
469 raise ValueError('Unsupported CRT DO length: %s', do)
470 if do[0] != 0x83 or do[1] != 0x01:
471 raise ValueError('Unsupported Key Ref Tag or Len in CRT DO %s', do)
472 if do[3:] != b'\x95\x01\x08':
Harald Weltec91085e2022-02-10 18:05:45 +0100473 raise ValueError(
474 'Unsupported Usage Qualifier Tag or Len in CRT DO %s', do)
Harald Welte4ae228a2021-05-02 21:29:04 +0200475 self.encoded = do[0:6]
476 self.decoded = pin_names[do[2]]
477 return do[6:]
478
479 def to_bytes(self):
480 pin = pin_names.inverse[self.decoded]
481 return b'\x83\x01' + pin.to_bytes(1, 'big') + b'\x95\x01\x08'
482
483# ISO7816-4 9.3.3 Table 33
484class SecCondByte_DO(DataObject):
485 def __init__(self, tag=0x9d):
486 super().__init__('security_condition_byte', tag=tag)
487
Harald Weltec91085e2022-02-10 18:05:45 +0100488 def from_bytes(self, binary: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200489 if len(binary) != 1:
490 raise ValueError
491 inb = binary[0]
492 if inb == 0:
493 cond = 'always'
494 if inb == 0xff:
495 cond = 'never'
496 res = []
497 if inb & 0x80:
498 cond = 'and'
499 else:
500 cond = 'or'
501 if inb & 0x40:
502 res.append('secure_messaging')
503 if inb & 0x20:
504 res.append('external_auth')
505 if inb & 0x10:
506 res.append('user_auth')
Harald Weltec91085e2022-02-10 18:05:45 +0100507 rd = {'mode': cond}
Harald Welte4ae228a2021-05-02 21:29:04 +0200508 if len(res):
509 rd['conditions'] = res
510 self.decoded = rd
511
512 def to_bytes(self):
513 mode = self.decoded['mode']
514 if mode == 'always':
515 res = 0
516 elif mode == 'never':
517 res = 0xff
518 else:
519 res = 0
520 if mode == 'and':
521 res |= 0x80
522 elif mode == 'or':
523 pass
524 else:
525 raise ValueError('Unknown mode %s' % mode)
526 for c in self.decoded['conditions']:
527 if c == 'secure_messaging':
528 res |= 0x40
529 elif c == 'external_auth':
530 res |= 0x20
531 elif c == 'user_auth':
532 res |= 0x10
533 else:
534 raise ValueError('Unknown condition %s' % c)
535 return res.to_bytes(1, 'big')
536
Harald Weltec91085e2022-02-10 18:05:45 +0100537
Harald Welte4ae228a2021-05-02 21:29:04 +0200538Always_DO = TL0_DataObject('always', 'Always', 0x90)
539Never_DO = TL0_DataObject('never', 'Never', 0x97)
Harald Welteb0608332022-02-10 12:45:37 +0100540
Harald Weltec91085e2022-02-10 18:05:45 +0100541
Harald Welteb0608332022-02-10 12:45:37 +0100542class Nested_DO(DataObject):
543 """A DO that nests another DO/Choice/Sequence"""
Harald Weltec91085e2022-02-10 18:05:45 +0100544
Harald Welteb0608332022-02-10 12:45:37 +0100545 def __init__(self, name, tag, choice):
546 super().__init__(name, tag=tag)
547 self.children = choice
Harald Weltec91085e2022-02-10 18:05:45 +0100548
549 def from_bytes(self, binary: bytes) -> list:
Harald Welteb0608332022-02-10 12:45:37 +0100550 remainder = binary
551 self.decoded = []
552 while remainder:
553 rc, remainder = self.children.decode(remainder)
554 self.decoded.append(rc)
555 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100556
Harald Welteb0608332022-02-10 12:45:37 +0100557 def to_bytes(self) -> bytes:
558 encoded = [self.children.encode(d) for d in self.decoded]
559 return b''.join(encoded)
560
Harald Weltec91085e2022-02-10 18:05:45 +0100561
Harald Welteb0608332022-02-10 12:45:37 +0100562OR_Template = DataObjectChoice('or_template', 'OR-Template',
563 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
564OR_DO = Nested_DO('or', 0xa0, OR_Template)
565AND_Template = DataObjectChoice('and_template', 'AND-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100566 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100567AND_DO = Nested_DO('and', 0xa7, AND_Template)
568NOT_Template = DataObjectChoice('not_template', 'NOT-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100569 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100570NOT_DO = Nested_DO('not', 0xaf, NOT_Template)
Harald Welte4ae228a2021-05-02 21:29:04 +0200571SC_DO = DataObjectChoice('security_condition', 'Security Condition',
Harald Welteb0608332022-02-10 12:45:37 +0100572 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO(),
573 OR_DO, AND_DO, NOT_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200574
Harald Welteb2edd142021-01-08 23:29:35 +0100575# TS 102 221 Section 13.1
576class EF_DIR(LinFixedEF):
Harald Welte181c7c52022-02-10 14:18:32 +0100577 class ApplicationLabel(BER_TLV_IE, tag=0x50):
578 # TODO: UCS-2 coding option as per Annex A of TS 102 221
579 _construct = GreedyString('ascii')
580
581 # see https://github.com/PyCQA/pylint/issues/5794
582 #pylint: disable=undefined-variable
583 class ApplicationTemplate(BER_TLV_IE, tag=0x61,
584 nested=[iso7816_4.ApplicationId, ApplicationLabel, iso7816_4.FileReference,
585 iso7816_4.CommandApdu, iso7816_4.DiscretionaryData,
586 iso7816_4.DiscretionaryTemplate, iso7816_4.URL,
587 iso7816_4.ApplicationRelatedDOSet]):
588 pass
589
Harald Welteb2edd142021-01-08 23:29:35 +0100590 def __init__(self, fid='2f00', sfid=0x1e, name='EF.DIR', desc='Application Directory'):
Harald Weltec91085e2022-02-10 18:05:45 +0100591 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len={5, 54})
Harald Welte181c7c52022-02-10 14:18:32 +0100592 self._tlv = EF_DIR.ApplicationTemplate
Harald Welteb2edd142021-01-08 23:29:35 +0100593
594# TS 102 221 Section 13.2
595class EF_ICCID(TransparentEF):
596 def __init__(self, fid='2fe2', sfid=0x02, name='EF.ICCID', desc='ICC Identification'):
Harald Weltec91085e2022-02-10 18:05:45 +0100597 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={10, 10})
Harald Welteb2edd142021-01-08 23:29:35 +0100598
599 def _decode_hex(self, raw_hex):
600 return {'iccid': dec_iccid(raw_hex)}
601
602 def _encode_hex(self, abstract):
603 return enc_iccid(abstract['iccid'])
604
605# TS 102 221 Section 13.3
606class EF_PL(TransRecEF):
607 def __init__(self, fid='2f05', sfid=0x05, name='EF.PL', desc='Preferred Languages'):
Harald Weltec91085e2022-02-10 18:05:45 +0100608 super().__init__(fid, sfid=sfid, name=name,
609 desc=desc, rec_len=2, size={2, None})
610
Harald Welte0c840f02022-01-21 15:42:22 +0100611 def _decode_record_bin(self, bin_data):
612 if bin_data == b'\xff\xff':
613 return None
614 else:
615 return bin_data.decode('ascii')
Harald Weltec91085e2022-02-10 18:05:45 +0100616
Harald Welte0c840f02022-01-21 15:42:22 +0100617 def _encode_record_bin(self, in_json):
618 if in_json is None:
619 return b'\xff\xff'
620 else:
621 return in_json.encode('ascii')
622
Harald Welteb2edd142021-01-08 23:29:35 +0100623
624# TS 102 221 Section 13.4
625class EF_ARR(LinFixedEF):
626 def __init__(self, fid='2f06', sfid=0x06, name='EF.ARR', desc='Access Rule Reference'):
627 super().__init__(fid, sfid=sfid, name=name, desc=desc)
Harald Welte4ae228a2021-05-02 21:29:04 +0200628 # add those commands to the general commands of a TransparentEF
629 self.shell_commands += [self.AddlShellCommands()]
630
631 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100632 def flatten(inp: list):
Harald Welte4ae228a2021-05-02 21:29:04 +0200633 """Flatten the somewhat deep/complex/nested data returned from decoder."""
634 def sc_abbreviate(sc):
635 if 'always' in sc:
636 return 'always'
637 elif 'never' in sc:
638 return 'never'
639 elif 'control_reference_template' in sc:
640 return sc['control_reference_template']
641 else:
642 return sc
643
644 by_mode = {}
645 for t in inp:
646 am = t[0]
647 sc = t[1]
648 sc_abbr = sc_abbreviate(sc)
649 if 'access_mode' in am:
650 for m in am['access_mode']:
651 by_mode[m] = sc_abbr
652 elif 'command_header' in am:
653 ins = am['command_header']['INS']
654 if 'CLA' in am['command_header']:
655 cla = am['command_header']['CLA']
656 else:
657 cla = None
658 cmd = ts_102_22x_cmdset.lookup(ins, cla)
659 if cmd:
Harald Weltec91085e2022-02-10 18:05:45 +0100660 name = cmd.name.lower().replace(' ', '_')
Harald Welte4ae228a2021-05-02 21:29:04 +0200661 by_mode[name] = sc_abbr
662 else:
663 raise ValueError
664 else:
665 raise ValueError
666 return by_mode
667
668 def _decode_record_bin(self, raw_bin_data):
669 # we can only guess if we should decode for EF or DF here :(
Harald Weltec91085e2022-02-10 18:05:45 +0100670 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200671 dec = arr_seq.decode_multi(raw_bin_data)
672 # we cannot pass the result through flatten() here, as we don't have a related
673 # 'un-flattening' decoder, and hence would be unable to encode :(
674 return dec[0]
675
Harald Weltec30bed22022-04-05 14:45:18 +0200676 def _encode_record_bin(self, in_json):
677 # we can only guess if we should decode for EF or DF here :(
678 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
679 return arr_seq.encode_multi(in_json)
680
Harald Welte4ae228a2021-05-02 21:29:04 +0200681 @with_default_category('File-Specific Commands')
682 class AddlShellCommands(CommandSet):
683 def __init__(self):
684 super().__init__()
685
686 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_rec_dec_parser)
687 def do_read_arr_record(self, opts):
688 """Read one EF.ARR record in flattened, human-friendly form."""
689 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
690 data = self._cmd.rs.selected_file.flatten(data)
691 self._cmd.poutput_json(data, opts.oneline)
692
693 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_recs_dec_parser)
694 def do_read_arr_records(self, opts):
695 """Read + decode all EF.ARR records in flattened, human-friendly form."""
Harald Welte747a9782022-02-13 17:52:28 +0100696 num_of_rec = self._cmd.rs.selected_file_num_of_rec()
Harald Welte4ae228a2021-05-02 21:29:04 +0200697 # collect all results in list so they are rendered as JSON list when printing
698 data_list = []
699 for recnr in range(1, 1 + num_of_rec):
700 (data, sw) = self._cmd.rs.read_record_dec(recnr)
701 data = self._cmd.rs.selected_file.flatten(data)
702 data_list.append(data)
703 self._cmd.poutput_json(data_list, opts.oneline)
704
Harald Welteb2edd142021-01-08 23:29:35 +0100705
706# TS 102 221 Section 13.6
707class EF_UMPC(TransparentEF):
708 def __init__(self, fid='2f08', sfid=0x08, name='EF.UMPC', desc='UICC Maximum Power Consumption'):
Harald Weltec91085e2022-02-10 18:05:45 +0100709 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={5, 5})
710 addl_info = FlagsEnum(Byte, req_inc_idle_current=1,
711 support_uicc_suspend=2)
712 self._construct = Struct(
713 'max_current_mA'/Int8ub, 't_op_s'/Int8ub, 'addl_info'/addl_info)
714
Harald Welteb2edd142021-01-08 23:29:35 +0100715
Harald Welteb2edd142021-01-08 23:29:35 +0100716class CardProfileUICC(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +0100717
718 ORDER = 1
719
Harald Weltec91085e2022-02-10 18:05:45 +0100720 def __init__(self, name='UICC'):
Harald Welteb2edd142021-01-08 23:29:35 +0100721 files = [
722 EF_DIR(),
723 EF_ICCID(),
724 EF_PL(),
725 EF_ARR(),
726 # FIXME: DF.CD
727 EF_UMPC(),
728 ]
729 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +0100730 'Normal': {
731 '9000': 'Normal ending of the command',
732 '91xx': 'Normal ending of the command, with extra information from the proactive UICC containing a command for the terminal',
733 '92xx': 'Normal ending of the command, with extra information concerning an ongoing data transfer session',
Harald Welteb2edd142021-01-08 23:29:35 +0100734 },
Harald Weltec91085e2022-02-10 18:05:45 +0100735 'Postponed processing': {
736 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Harald Welteb2edd142021-01-08 23:29:35 +0100737 },
Harald Weltec91085e2022-02-10 18:05:45 +0100738 'Warnings': {
739 '6200': 'No information given, state of non-volatile memory unchanged',
740 '6281': 'Part of returned data may be corrupted',
741 '6282': 'End of file/record reached before reading Le bytes or unsuccessful search',
742 '6283': 'Selected file invalidated',
743 '6284': 'Selected file in termination state',
744 '62f1': 'More data available',
745 '62f2': 'More data available and proactive command pending',
746 '62f3': 'Response data available',
747 '63f1': 'More data expected',
748 '63f2': 'More data expected and proactive command pending',
749 '63cx': 'Command successful but after using an internal update retry routine X times',
Harald Welteb2edd142021-01-08 23:29:35 +0100750 },
Harald Weltec91085e2022-02-10 18:05:45 +0100751 'Execution errors': {
752 '6400': 'No information given, state of non-volatile memory unchanged',
753 '6500': 'No information given, state of non-volatile memory changed',
754 '6581': 'Memory problem',
Harald Welteb2edd142021-01-08 23:29:35 +0100755 },
Harald Weltec91085e2022-02-10 18:05:45 +0100756 'Checking errors': {
757 '6700': 'Wrong length',
758 '67xx': 'The interpretation of this status word is command dependent',
759 '6b00': 'Wrong parameter(s) P1-P2',
760 '6d00': 'Instruction code not supported or invalid',
761 '6e00': 'Class not supported',
762 '6f00': 'Technical problem, no precise diagnosis',
763 '6fxx': 'The interpretation of this status word is command dependent',
Harald Welteb2edd142021-01-08 23:29:35 +0100764 },
Harald Weltec91085e2022-02-10 18:05:45 +0100765 'Functions in CLA not supported': {
766 '6800': 'No information given',
767 '6881': 'Logical channel not supported',
768 '6882': 'Secure messaging not supported',
Harald Welteb2edd142021-01-08 23:29:35 +0100769 },
Harald Weltec91085e2022-02-10 18:05:45 +0100770 'Command not allowed': {
771 '6900': 'No information given',
772 '6981': 'Command incompatible with file structure',
773 '6982': 'Security status not satisfied',
774 '6983': 'Authentication/PIN method blocked',
775 '6984': 'Referenced data invalidated',
776 '6985': 'Conditions of use not satisfied',
777 '6986': 'Command not allowed (no EF selected)',
778 '6989': 'Command not allowed - secure channel - security not satisfied',
Harald Welteb2edd142021-01-08 23:29:35 +0100779 },
Harald Weltec91085e2022-02-10 18:05:45 +0100780 'Wrong parameters': {
781 '6a80': 'Incorrect parameters in the data field',
782 '6a81': 'Function not supported',
783 '6a82': 'File not found',
784 '6a83': 'Record not found',
785 '6a84': 'Not enough memory space',
786 '6a86': 'Incorrect parameters P1 to P2',
787 '6a87': 'Lc inconsistent with P1 to P2',
788 '6a88': 'Referenced data not found',
Harald Welteb2edd142021-01-08 23:29:35 +0100789 },
Harald Weltec91085e2022-02-10 18:05:45 +0100790 'Application errors': {
791 '9850': 'INCREASE cannot be performed, max value reached',
792 '9862': 'Authentication error, application specific',
793 '9863': 'Security session or association expired',
794 '9864': 'Minimum UICC suspension time is too long',
Harald Welteb2edd142021-01-08 23:29:35 +0100795 },
Harald Weltec91085e2022-02-10 18:05:45 +0100796 }
Harald Welteb2edd142021-01-08 23:29:35 +0100797
Harald Weltec91085e2022-02-10 18:05:45 +0100798 super().__init__(name, desc='ETSI TS 102 221', cla="00",
799 sel_ctrl="0004", files_in_mf=files, sw=sw)
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100800
Philipp Maier5998a3a2021-11-16 15:16:39 +0100801 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100802 def decode_select_response(resp_hex: str) -> object:
Philipp Maier5998a3a2021-11-16 15:16:39 +0100803 """ETSI TS 102 221 Section 11.1.1.3"""
Harald Weltec8c33272022-02-11 14:45:23 +0100804 t = FcpTemplate()
805 t.from_tlv(h2b(resp_hex))
806 d = t.to_dict()
807 return flatten_dict_lists(d['fcp_template'])
Philipp Maiera028c7d2021-11-08 16:12:03 +0100808
809 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100810 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100811 return match_uicc(scc)
812
Harald Weltec91085e2022-02-10 18:05:45 +0100813
Philipp Maiera028c7d2021-11-08 16:12:03 +0100814class CardProfileUICCSIM(CardProfileUICC):
815 """Same as above, but including 2G SIM support"""
816
817 ORDER = 0
818
819 def __init__(self):
820 super().__init__('UICC-SIM')
821
822 # Add GSM specific files
823 self.files_in_mf.append(DF_TELECOM())
824 self.files_in_mf.append(DF_GSM())
825
826 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100827 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100828 return match_uicc(scc) and match_sim(scc)