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