blob: ac2a60e4a7375b08016fe25b94e19c055e70f37c [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):
83 _construct = GreedyInteger()
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):
87 _construct = GreedyInteger()
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'),
106 'record_len'/COptional(Int16ub), 'num_of_rec'/COptional(Int16ub))
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 Welte3c9b7842021-10-19 21:44:24 +0200189 _construct = HexAdapter(COptional(Bytes(1)))
Harald Welteb2edd142021-01-08 23:29:35 +0100190
191# ETSI TS 102 221 11.1.1.4.9
Harald Weltec8c33272022-02-11 14:45:23 +0100192class LifeCycleStatusInteger(BER_TLV_IE, tag=0x8A):
193 def _from_bytes(self, do: bytes):
194 lcsi = int.from_bytes(do, 'big')
195 if lcsi == 0x00:
196 ret = 'no_information'
197 elif lcsi == 0x01:
198 ret = 'creation'
199 elif lcsi == 0x03:
200 ret = 'initialization'
201 elif lcsi & 0x05 == 0x05:
202 ret = 'operational_activated'
203 elif lcsi & 0x05 == 0x04:
204 ret = 'operational_deactivated'
205 elif lcsi & 0xc0 == 0xc0:
206 ret = 'termination'
207 else:
208 ret = lcsi
209 self.decoded = ret
210 return self.decoded
Harald Welte3c9b7842021-10-19 21:44:24 +0200211 def _to_bytes(self):
212 if self.decoded == 'no_information':
213 return b'\x00'
214 elif self.decoded == 'creation':
215 return b'\x01'
216 elif self.decoded == 'initialization':
217 return b'\x03'
218 elif self.decoded == 'operational_activated':
219 return b'\x05'
220 elif self.decoded == 'operational_deactivated':
221 return b'\x04'
222 elif self.decoded == 'termination':
223 return b'\x0c'
224 elif isinstance(self.decoded, int):
225 return self.decoded.to_bytes(1, 'big')
226 else:
227 raise ValueError
Harald Weltec91085e2022-02-10 18:05:45 +0100228
Harald Weltec8c33272022-02-11 14:45:23 +0100229# ETSI TS 102 221 11.1.1.4.9
230class PS_DO(BER_TLV_IE, tag=0x90):
231 _construct = GreedyBytes
232class UsageQualifier_DO(BER_TLV_IE, tag=0x95):
233 _construct = GreedyBytes
234class KeyReference(BER_TLV_IE, tag=0x83):
235 _construct = Byte
236class PinStatusTemplate_DO(BER_TLV_IE, tag=0xC6, nested=[PS_DO, UsageQualifier_DO, KeyReference]):
237 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100238
Harald Weltec8c33272022-02-11 14:45:23 +0100239class FcpTemplate(BER_TLV_IE, tag=0x62, nested=[FileSize, TotalFileSize, FileDescriptor, FileIdentifier,
240 DfName, ProprietaryInformation, SecurityAttribCompact,
241 SecurityAttribExpanded, SecurityAttribReferenced,
242 ShortFileIdentifier, LifeCycleStatusInteger,
243 PinStatusTemplate_DO]):
244 pass
Harald Welteb2edd142021-01-08 23:29:35 +0100245
246
247def tlv_key_replace(inmap, indata):
248 def newkey(inmap, key):
249 if key in inmap:
250 return inmap[key]
251 else:
252 return key
253 return {newkey(inmap, d[0]): d[1] for d in indata.items()}
254
Harald Weltec91085e2022-02-10 18:05:45 +0100255
Harald Welteb2edd142021-01-08 23:29:35 +0100256def tlv_val_interpret(inmap, indata):
257 def newval(inmap, key, val):
258 if key in inmap:
259 return inmap[key](val)
260 else:
261 return val
262 return {d[0]: newval(inmap, d[0], d[1]) for d in indata.items()}
263
Harald Welte4ae228a2021-05-02 21:29:04 +0200264# ETSI TS 102 221 Section 9.2.7 + ISO7816-4 9.3.3/9.3.4
Harald Welte4ae228a2021-05-02 21:29:04 +0200265class _AM_DO_DF(DataObject):
266 def __init__(self):
267 super().__init__('access_mode', 'Access Mode', tag=0x80)
268
Harald Weltec91085e2022-02-10 18:05:45 +0100269 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200270 res = []
271 if len(do) != 1:
272 raise ValueError("We only support single-byte AMF inside AM-DO")
273 amf = do[0]
274 # tables 17..29 and 41..44 of 7816-4
275 if amf & 0x80 == 0:
276 if amf & 0x40:
277 res.append('delete_file')
278 if amf & 0x20:
279 res.append('terminate_df')
280 if amf & 0x10:
281 res.append('activate_file')
282 if amf & 0x08:
283 res.append('deactivate_file')
284 if amf & 0x04:
285 res.append('create_file_df')
286 if amf & 0x02:
287 res.append('create_file_ef')
288 if amf & 0x01:
289 res.append('delete_file_child')
290 self.decoded = res
291
292 def to_bytes(self):
293 val = 0
294 if 'delete_file' in self.decoded:
295 val |= 0x40
296 if 'terminate_df' in self.decoded:
297 val |= 0x20
298 if 'activate_file' in self.decoded:
299 val |= 0x10
300 if 'deactivate_file' in self.decoded:
301 val |= 0x08
302 if 'create_file_df' in self.decoded:
303 val |= 0x04
304 if 'create_file_ef' in self.decoded:
305 val |= 0x02
306 if 'delete_file_child' in self.decoded:
307 val |= 0x01
308 return val.to_bytes(1, 'big')
309
310
311class _AM_DO_EF(DataObject):
312 """ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31"""
Harald Weltec91085e2022-02-10 18:05:45 +0100313
Harald Welte4ae228a2021-05-02 21:29:04 +0200314 def __init__(self):
315 super().__init__('access_mode', 'Access Mode', tag=0x80)
316
Harald Weltec91085e2022-02-10 18:05:45 +0100317 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200318 res = []
319 if len(do) != 1:
320 raise ValueError("We only support single-byte AMF inside AM-DO")
321 amf = do[0]
322 # tables 17..29 and 41..44 of 7816-4
323 if amf & 0x80 == 0:
324 if amf & 0x40:
325 res.append('delete_file')
326 if amf & 0x20:
327 res.append('terminate_ef')
328 if amf & 0x10:
329 res.append('activate_file_or_record')
330 if amf & 0x08:
331 res.append('deactivate_file_or_record')
332 if amf & 0x04:
333 res.append('write_append')
334 if amf & 0x02:
335 res.append('update_erase')
336 if amf & 0x01:
337 res.append('read_search_compare')
338 self.decoded = res
339
340 def to_bytes(self):
341 val = 0
342 if 'delete_file' in self.decoded:
343 val |= 0x40
344 if 'terminate_ef' in self.decoded:
345 val |= 0x20
346 if 'activate_file_or_record' in self.decoded:
347 val |= 0x10
348 if 'deactivate_file_or_record' in self.decoded:
349 val |= 0x08
350 if 'write_append' in self.decoded:
351 val |= 0x04
352 if 'update_erase' in self.decoded:
353 val |= 0x02
354 if 'read_search_compare' in self.decoded:
355 val |= 0x01
356 return val.to_bytes(1, 'big')
357
Harald Weltec91085e2022-02-10 18:05:45 +0100358
Harald Welte4ae228a2021-05-02 21:29:04 +0200359class _AM_DO_CHDR(DataObject):
360 """Command Header Access Mode DO according to ISO 7816-4 Table 32."""
Harald Weltec91085e2022-02-10 18:05:45 +0100361
Harald Welte4ae228a2021-05-02 21:29:04 +0200362 def __init__(self, tag):
363 super().__init__('command_header', 'Command Header Description', tag=tag)
364
Harald Weltec91085e2022-02-10 18:05:45 +0100365 def from_bytes(self, do: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200366 res = {}
367 i = 0
368 if self.tag & 0x08:
369 res['CLA'] = do[i]
370 i += 1
371 if self.tag & 0x04:
372 res['INS'] = do[i]
373 i += 1
374 if self.tag & 0x02:
375 res['P1'] = do[i]
376 i += 1
377 if self.tag & 0x01:
378 res['P2'] = do[i]
379 i += 1
380 self.decoded = res
381
382 def _compute_tag(self):
383 """Override to encode the tag, as it depends on the value."""
384 tag = 0x80
385 if 'CLA' in self.decoded:
386 tag |= 0x08
387 if 'INS' in self.decoded:
388 tag |= 0x04
389 if 'P1' in self.decoded:
390 tag |= 0x02
391 if 'P2' in self.decoded:
392 tag |= 0x01
393 return tag
394
395 def to_bytes(self):
396 res = bytearray()
397 if 'CLA' in self.decoded:
398 res.append(self.decoded['CLA'])
399 if 'INS' in self.decoded:
400 res.append(self.decoded['INS'])
401 if 'P1' in self.decoded:
402 res.append(self.decoded['P1'])
403 if 'P2' in self.decoded:
404 res.append(self.decoded['P2'])
405 return res
406
Harald Weltec91085e2022-02-10 18:05:45 +0100407
Harald Welte4ae228a2021-05-02 21:29:04 +0200408AM_DO_CHDR = DataObjectChoice('am_do_chdr', members=[
Harald Weltec91085e2022-02-10 18:05:45 +0100409 _AM_DO_CHDR(0x81), _AM_DO_CHDR(0x82), _AM_DO_CHDR(0x83), _AM_DO_CHDR(0x84),
410 _AM_DO_CHDR(0x85), _AM_DO_CHDR(0x86), _AM_DO_CHDR(0x87), _AM_DO_CHDR(0x88),
411 _AM_DO_CHDR(0x89), _AM_DO_CHDR(0x8a), _AM_DO_CHDR(0x8b), _AM_DO_CHDR(0x8c),
412 _AM_DO_CHDR(0x8d), _AM_DO_CHDR(0x8e), _AM_DO_CHDR(0x8f)])
Harald Welte4ae228a2021-05-02 21:29:04 +0200413
414AM_DO_DF = AM_DO_CHDR | _AM_DO_DF()
415AM_DO_EF = AM_DO_CHDR | _AM_DO_EF()
416
417
418# TS 102 221 Section 9.5.1 / Table 9.3
419pin_names = bidict({
420 0x01: 'PIN1',
421 0x02: 'PIN2',
422 0x03: 'PIN3',
423 0x04: 'PIN4',
424 0x05: 'PIN5',
425 0x06: 'PIN6',
426 0x07: 'PIN7',
427 0x08: 'PIN8',
428 0x0a: 'ADM1',
429 0x0b: 'ADM2',
430 0x0c: 'ADM3',
431 0x0d: 'ADM4',
432 0x0e: 'ADM5',
433
434 0x11: 'UNIVERSAL_PIN',
435 0x81: '2PIN1',
436 0x82: '2PIN2',
437 0x83: '2PIN3',
438 0x84: '2PIN4',
439 0x85: '2PIN5',
440 0x86: '2PIN6',
441 0x87: '2PIN7',
442 0x88: '2PIN8',
443 0x8a: 'ADM6',
444 0x8b: 'ADM7',
445 0x8c: 'ADM8',
446 0x8d: 'ADM9',
447 0x8e: 'ADM10',
Harald Weltec91085e2022-02-10 18:05:45 +0100448})
449
Harald Welte4ae228a2021-05-02 21:29:04 +0200450
451class CRT_DO(DataObject):
452 """Control Reference Template as per TS 102 221 9.5.1"""
Harald Weltec91085e2022-02-10 18:05:45 +0100453
Harald Welte4ae228a2021-05-02 21:29:04 +0200454 def __init__(self):
Harald Weltec91085e2022-02-10 18:05:45 +0100455 super().__init__('control_reference_template',
456 'Control Reference Template', tag=0xA4)
Harald Welte4ae228a2021-05-02 21:29:04 +0200457
458 def from_bytes(self, do: bytes):
459 """Decode a Control Reference Template DO."""
460 if len(do) != 6:
461 raise ValueError('Unsupported CRT DO length: %s', do)
462 if do[0] != 0x83 or do[1] != 0x01:
463 raise ValueError('Unsupported Key Ref Tag or Len in CRT DO %s', do)
464 if do[3:] != b'\x95\x01\x08':
Harald Weltec91085e2022-02-10 18:05:45 +0100465 raise ValueError(
466 'Unsupported Usage Qualifier Tag or Len in CRT DO %s', do)
Harald Welte4ae228a2021-05-02 21:29:04 +0200467 self.encoded = do[0:6]
468 self.decoded = pin_names[do[2]]
469 return do[6:]
470
471 def to_bytes(self):
472 pin = pin_names.inverse[self.decoded]
473 return b'\x83\x01' + pin.to_bytes(1, 'big') + b'\x95\x01\x08'
474
475# ISO7816-4 9.3.3 Table 33
476class SecCondByte_DO(DataObject):
477 def __init__(self, tag=0x9d):
478 super().__init__('security_condition_byte', tag=tag)
479
Harald Weltec91085e2022-02-10 18:05:45 +0100480 def from_bytes(self, binary: bytes):
Harald Welte4ae228a2021-05-02 21:29:04 +0200481 if len(binary) != 1:
482 raise ValueError
483 inb = binary[0]
484 if inb == 0:
485 cond = 'always'
486 if inb == 0xff:
487 cond = 'never'
488 res = []
489 if inb & 0x80:
490 cond = 'and'
491 else:
492 cond = 'or'
493 if inb & 0x40:
494 res.append('secure_messaging')
495 if inb & 0x20:
496 res.append('external_auth')
497 if inb & 0x10:
498 res.append('user_auth')
Harald Weltec91085e2022-02-10 18:05:45 +0100499 rd = {'mode': cond}
Harald Welte4ae228a2021-05-02 21:29:04 +0200500 if len(res):
501 rd['conditions'] = res
502 self.decoded = rd
503
504 def to_bytes(self):
505 mode = self.decoded['mode']
506 if mode == 'always':
507 res = 0
508 elif mode == 'never':
509 res = 0xff
510 else:
511 res = 0
512 if mode == 'and':
513 res |= 0x80
514 elif mode == 'or':
515 pass
516 else:
517 raise ValueError('Unknown mode %s' % mode)
518 for c in self.decoded['conditions']:
519 if c == 'secure_messaging':
520 res |= 0x40
521 elif c == 'external_auth':
522 res |= 0x20
523 elif c == 'user_auth':
524 res |= 0x10
525 else:
526 raise ValueError('Unknown condition %s' % c)
527 return res.to_bytes(1, 'big')
528
Harald Weltec91085e2022-02-10 18:05:45 +0100529
Harald Welte4ae228a2021-05-02 21:29:04 +0200530Always_DO = TL0_DataObject('always', 'Always', 0x90)
531Never_DO = TL0_DataObject('never', 'Never', 0x97)
Harald Welteb0608332022-02-10 12:45:37 +0100532
Harald Weltec91085e2022-02-10 18:05:45 +0100533
Harald Welteb0608332022-02-10 12:45:37 +0100534class Nested_DO(DataObject):
535 """A DO that nests another DO/Choice/Sequence"""
Harald Weltec91085e2022-02-10 18:05:45 +0100536
Harald Welteb0608332022-02-10 12:45:37 +0100537 def __init__(self, name, tag, choice):
538 super().__init__(name, tag=tag)
539 self.children = choice
Harald Weltec91085e2022-02-10 18:05:45 +0100540
541 def from_bytes(self, binary: bytes) -> list:
Harald Welteb0608332022-02-10 12:45:37 +0100542 remainder = binary
543 self.decoded = []
544 while remainder:
545 rc, remainder = self.children.decode(remainder)
546 self.decoded.append(rc)
547 return self.decoded
Harald Weltec91085e2022-02-10 18:05:45 +0100548
Harald Welteb0608332022-02-10 12:45:37 +0100549 def to_bytes(self) -> bytes:
550 encoded = [self.children.encode(d) for d in self.decoded]
551 return b''.join(encoded)
552
Harald Weltec91085e2022-02-10 18:05:45 +0100553
Harald Welteb0608332022-02-10 12:45:37 +0100554OR_Template = DataObjectChoice('or_template', 'OR-Template',
555 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
556OR_DO = Nested_DO('or', 0xa0, OR_Template)
557AND_Template = DataObjectChoice('and_template', 'AND-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100558 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100559AND_DO = Nested_DO('and', 0xa7, AND_Template)
560NOT_Template = DataObjectChoice('not_template', 'NOT-Template',
Harald Weltec91085e2022-02-10 18:05:45 +0100561 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()])
Harald Welteb0608332022-02-10 12:45:37 +0100562NOT_DO = Nested_DO('not', 0xaf, NOT_Template)
Harald Welte4ae228a2021-05-02 21:29:04 +0200563SC_DO = DataObjectChoice('security_condition', 'Security Condition',
Harald Welteb0608332022-02-10 12:45:37 +0100564 members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO(),
565 OR_DO, AND_DO, NOT_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200566
Harald Welteb2edd142021-01-08 23:29:35 +0100567# TS 102 221 Section 13.1
568class EF_DIR(LinFixedEF):
Harald Welte181c7c52022-02-10 14:18:32 +0100569 class ApplicationLabel(BER_TLV_IE, tag=0x50):
570 # TODO: UCS-2 coding option as per Annex A of TS 102 221
571 _construct = GreedyString('ascii')
572
573 # see https://github.com/PyCQA/pylint/issues/5794
574 #pylint: disable=undefined-variable
575 class ApplicationTemplate(BER_TLV_IE, tag=0x61,
576 nested=[iso7816_4.ApplicationId, ApplicationLabel, iso7816_4.FileReference,
577 iso7816_4.CommandApdu, iso7816_4.DiscretionaryData,
578 iso7816_4.DiscretionaryTemplate, iso7816_4.URL,
579 iso7816_4.ApplicationRelatedDOSet]):
580 pass
581
Harald Welteb2edd142021-01-08 23:29:35 +0100582 def __init__(self, fid='2f00', sfid=0x1e, name='EF.DIR', desc='Application Directory'):
Harald Weltec91085e2022-02-10 18:05:45 +0100583 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len={5, 54})
Harald Welte181c7c52022-02-10 14:18:32 +0100584 self._tlv = EF_DIR.ApplicationTemplate
Harald Welteb2edd142021-01-08 23:29:35 +0100585
586# TS 102 221 Section 13.2
587class EF_ICCID(TransparentEF):
588 def __init__(self, fid='2fe2', sfid=0x02, name='EF.ICCID', desc='ICC Identification'):
Harald Weltec91085e2022-02-10 18:05:45 +0100589 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={10, 10})
Harald Welteb2edd142021-01-08 23:29:35 +0100590
591 def _decode_hex(self, raw_hex):
592 return {'iccid': dec_iccid(raw_hex)}
593
594 def _encode_hex(self, abstract):
595 return enc_iccid(abstract['iccid'])
596
597# TS 102 221 Section 13.3
598class EF_PL(TransRecEF):
599 def __init__(self, fid='2f05', sfid=0x05, name='EF.PL', desc='Preferred Languages'):
Harald Weltec91085e2022-02-10 18:05:45 +0100600 super().__init__(fid, sfid=sfid, name=name,
601 desc=desc, rec_len=2, size={2, None})
602
Harald Welte0c840f02022-01-21 15:42:22 +0100603 def _decode_record_bin(self, bin_data):
604 if bin_data == b'\xff\xff':
605 return None
606 else:
607 return bin_data.decode('ascii')
Harald Weltec91085e2022-02-10 18:05:45 +0100608
Harald Welte0c840f02022-01-21 15:42:22 +0100609 def _encode_record_bin(self, in_json):
610 if in_json is None:
611 return b'\xff\xff'
612 else:
613 return in_json.encode('ascii')
614
Harald Welteb2edd142021-01-08 23:29:35 +0100615
616# TS 102 221 Section 13.4
617class EF_ARR(LinFixedEF):
618 def __init__(self, fid='2f06', sfid=0x06, name='EF.ARR', desc='Access Rule Reference'):
619 super().__init__(fid, sfid=sfid, name=name, desc=desc)
Harald Welte4ae228a2021-05-02 21:29:04 +0200620 # add those commands to the general commands of a TransparentEF
621 self.shell_commands += [self.AddlShellCommands()]
622
623 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100624 def flatten(inp: list):
Harald Welte4ae228a2021-05-02 21:29:04 +0200625 """Flatten the somewhat deep/complex/nested data returned from decoder."""
626 def sc_abbreviate(sc):
627 if 'always' in sc:
628 return 'always'
629 elif 'never' in sc:
630 return 'never'
631 elif 'control_reference_template' in sc:
632 return sc['control_reference_template']
633 else:
634 return sc
635
636 by_mode = {}
637 for t in inp:
638 am = t[0]
639 sc = t[1]
640 sc_abbr = sc_abbreviate(sc)
641 if 'access_mode' in am:
642 for m in am['access_mode']:
643 by_mode[m] = sc_abbr
644 elif 'command_header' in am:
645 ins = am['command_header']['INS']
646 if 'CLA' in am['command_header']:
647 cla = am['command_header']['CLA']
648 else:
649 cla = None
650 cmd = ts_102_22x_cmdset.lookup(ins, cla)
651 if cmd:
Harald Weltec91085e2022-02-10 18:05:45 +0100652 name = cmd.name.lower().replace(' ', '_')
Harald Welte4ae228a2021-05-02 21:29:04 +0200653 by_mode[name] = sc_abbr
654 else:
655 raise ValueError
656 else:
657 raise ValueError
658 return by_mode
659
660 def _decode_record_bin(self, raw_bin_data):
661 # we can only guess if we should decode for EF or DF here :(
Harald Weltec91085e2022-02-10 18:05:45 +0100662 arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO])
Harald Welte4ae228a2021-05-02 21:29:04 +0200663 dec = arr_seq.decode_multi(raw_bin_data)
664 # we cannot pass the result through flatten() here, as we don't have a related
665 # 'un-flattening' decoder, and hence would be unable to encode :(
666 return dec[0]
667
668 @with_default_category('File-Specific Commands')
669 class AddlShellCommands(CommandSet):
670 def __init__(self):
671 super().__init__()
672
673 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_rec_dec_parser)
674 def do_read_arr_record(self, opts):
675 """Read one EF.ARR record in flattened, human-friendly form."""
676 (data, sw) = self._cmd.rs.read_record_dec(opts.record_nr)
677 data = self._cmd.rs.selected_file.flatten(data)
678 self._cmd.poutput_json(data, opts.oneline)
679
680 @cmd2.with_argparser(LinFixedEF.ShellCommands.read_recs_dec_parser)
681 def do_read_arr_records(self, opts):
682 """Read + decode all EF.ARR records in flattened, human-friendly form."""
Harald Welte747a9782022-02-13 17:52:28 +0100683 num_of_rec = self._cmd.rs.selected_file_num_of_rec()
Harald Welte4ae228a2021-05-02 21:29:04 +0200684 # collect all results in list so they are rendered as JSON list when printing
685 data_list = []
686 for recnr in range(1, 1 + num_of_rec):
687 (data, sw) = self._cmd.rs.read_record_dec(recnr)
688 data = self._cmd.rs.selected_file.flatten(data)
689 data_list.append(data)
690 self._cmd.poutput_json(data_list, opts.oneline)
691
Harald Welteb2edd142021-01-08 23:29:35 +0100692
693# TS 102 221 Section 13.6
694class EF_UMPC(TransparentEF):
695 def __init__(self, fid='2f08', sfid=0x08, name='EF.UMPC', desc='UICC Maximum Power Consumption'):
Harald Weltec91085e2022-02-10 18:05:45 +0100696 super().__init__(fid, sfid=sfid, name=name, desc=desc, size={5, 5})
697 addl_info = FlagsEnum(Byte, req_inc_idle_current=1,
698 support_uicc_suspend=2)
699 self._construct = Struct(
700 'max_current_mA'/Int8ub, 't_op_s'/Int8ub, 'addl_info'/addl_info)
701
Harald Welteb2edd142021-01-08 23:29:35 +0100702
Harald Welteb2edd142021-01-08 23:29:35 +0100703class CardProfileUICC(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +0100704
705 ORDER = 1
706
Harald Weltec91085e2022-02-10 18:05:45 +0100707 def __init__(self, name='UICC'):
Harald Welteb2edd142021-01-08 23:29:35 +0100708 files = [
709 EF_DIR(),
710 EF_ICCID(),
711 EF_PL(),
712 EF_ARR(),
713 # FIXME: DF.CD
714 EF_UMPC(),
715 ]
716 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +0100717 'Normal': {
718 '9000': 'Normal ending of the command',
719 '91xx': 'Normal ending of the command, with extra information from the proactive UICC containing a command for the terminal',
720 '92xx': 'Normal ending of the command, with extra information concerning an ongoing data transfer session',
Harald Welteb2edd142021-01-08 23:29:35 +0100721 },
Harald Weltec91085e2022-02-10 18:05:45 +0100722 'Postponed processing': {
723 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Harald Welteb2edd142021-01-08 23:29:35 +0100724 },
Harald Weltec91085e2022-02-10 18:05:45 +0100725 'Warnings': {
726 '6200': 'No information given, state of non-volatile memory unchanged',
727 '6281': 'Part of returned data may be corrupted',
728 '6282': 'End of file/record reached before reading Le bytes or unsuccessful search',
729 '6283': 'Selected file invalidated',
730 '6284': 'Selected file in termination state',
731 '62f1': 'More data available',
732 '62f2': 'More data available and proactive command pending',
733 '62f3': 'Response data available',
734 '63f1': 'More data expected',
735 '63f2': 'More data expected and proactive command pending',
736 '63cx': 'Command successful but after using an internal update retry routine X times',
Harald Welteb2edd142021-01-08 23:29:35 +0100737 },
Harald Weltec91085e2022-02-10 18:05:45 +0100738 'Execution errors': {
739 '6400': 'No information given, state of non-volatile memory unchanged',
740 '6500': 'No information given, state of non-volatile memory changed',
741 '6581': 'Memory problem',
Harald Welteb2edd142021-01-08 23:29:35 +0100742 },
Harald Weltec91085e2022-02-10 18:05:45 +0100743 'Checking errors': {
744 '6700': 'Wrong length',
745 '67xx': 'The interpretation of this status word is command dependent',
746 '6b00': 'Wrong parameter(s) P1-P2',
747 '6d00': 'Instruction code not supported or invalid',
748 '6e00': 'Class not supported',
749 '6f00': 'Technical problem, no precise diagnosis',
750 '6fxx': 'The interpretation of this status word is command dependent',
Harald Welteb2edd142021-01-08 23:29:35 +0100751 },
Harald Weltec91085e2022-02-10 18:05:45 +0100752 'Functions in CLA not supported': {
753 '6800': 'No information given',
754 '6881': 'Logical channel not supported',
755 '6882': 'Secure messaging not supported',
Harald Welteb2edd142021-01-08 23:29:35 +0100756 },
Harald Weltec91085e2022-02-10 18:05:45 +0100757 'Command not allowed': {
758 '6900': 'No information given',
759 '6981': 'Command incompatible with file structure',
760 '6982': 'Security status not satisfied',
761 '6983': 'Authentication/PIN method blocked',
762 '6984': 'Referenced data invalidated',
763 '6985': 'Conditions of use not satisfied',
764 '6986': 'Command not allowed (no EF selected)',
765 '6989': 'Command not allowed - secure channel - security not satisfied',
Harald Welteb2edd142021-01-08 23:29:35 +0100766 },
Harald Weltec91085e2022-02-10 18:05:45 +0100767 'Wrong parameters': {
768 '6a80': 'Incorrect parameters in the data field',
769 '6a81': 'Function not supported',
770 '6a82': 'File not found',
771 '6a83': 'Record not found',
772 '6a84': 'Not enough memory space',
773 '6a86': 'Incorrect parameters P1 to P2',
774 '6a87': 'Lc inconsistent with P1 to P2',
775 '6a88': 'Referenced data not found',
Harald Welteb2edd142021-01-08 23:29:35 +0100776 },
Harald Weltec91085e2022-02-10 18:05:45 +0100777 'Application errors': {
778 '9850': 'INCREASE cannot be performed, max value reached',
779 '9862': 'Authentication error, application specific',
780 '9863': 'Security session or association expired',
781 '9864': 'Minimum UICC suspension time is too long',
Harald Welteb2edd142021-01-08 23:29:35 +0100782 },
Harald Weltec91085e2022-02-10 18:05:45 +0100783 }
Harald Welteb2edd142021-01-08 23:29:35 +0100784
Harald Weltec91085e2022-02-10 18:05:45 +0100785 super().__init__(name, desc='ETSI TS 102 221', cla="00",
786 sel_ctrl="0004", files_in_mf=files, sw=sw)
Philipp Maier5af7bdf2021-11-04 12:48:41 +0100787
Philipp Maier5998a3a2021-11-16 15:16:39 +0100788 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100789 def decode_select_response(resp_hex: str) -> object:
Philipp Maier5998a3a2021-11-16 15:16:39 +0100790 """ETSI TS 102 221 Section 11.1.1.3"""
Harald Weltec8c33272022-02-11 14:45:23 +0100791 t = FcpTemplate()
792 t.from_tlv(h2b(resp_hex))
793 d = t.to_dict()
794 return flatten_dict_lists(d['fcp_template'])
Philipp Maiera028c7d2021-11-08 16:12:03 +0100795
796 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100797 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100798 return match_uicc(scc)
799
Harald Weltec91085e2022-02-10 18:05:45 +0100800
Philipp Maiera028c7d2021-11-08 16:12:03 +0100801class CardProfileUICCSIM(CardProfileUICC):
802 """Same as above, but including 2G SIM support"""
803
804 ORDER = 0
805
806 def __init__(self):
807 super().__init__('UICC-SIM')
808
809 # Add GSM specific files
810 self.files_in_mf.append(DF_TELECOM())
811 self.files_in_mf.append(DF_GSM())
812
813 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100814 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +0100815 return match_uicc(scc) and match_sim(scc)