blob: 1f98e724fd051ffda82224588cfa56f2ec2a8b2c [file] [log] [blame]
Alexander Chemeris067f69c2017-07-18 16:44:26 +03001# -*- coding: utf-8 -*-
2
Harald Welte14105dc2021-05-31 08:48:51 +02003# without this, pylint will fail when inner classes are used
4# within the 'nested' kwarg of our TlvMeta metaclass on python 3.7 :(
5# pylint: disable=undefined-variable
6
Harald Welteb2edd142021-01-08 23:29:35 +01007""" Various constants from ETSI TS 151.011 +
8Representation of the GSM SIM/USIM/ISIM filesystem hierarchy.
9
10The File (and its derived classes) uses the classes of pySim.filesystem in
11order to describe the files specified in the relevant ETSI + 3GPP specifications.
Alexander Chemeris067f69c2017-07-18 16:44:26 +030012"""
13
14#
15# Copyright (C) 2017 Alexander.Chemeris <Alexander.Chemeris@gmail.com>
Harald Welteb2edd142021-01-08 23:29:35 +010016# Copyright (C) 2021 Harald Welte <laforge@osmocom.org>
Alexander Chemeris067f69c2017-07-18 16:44:26 +030017#
18# This program is free software: you can redistribute it and/or modify
19# it under the terms of the GNU General Public License as published by
20# the Free Software Foundation, either version 2 of the License, or
21# (at your option) any later version.
22#
23# This program is distributed in the hope that it will be useful,
24# but WITHOUT ANY WARRANTY; without even the implied warranty of
25# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26# GNU General Public License for more details.
27#
28# You should have received a copy of the GNU General Public License
29# along with this program. If not, see <http://www.gnu.org/licenses/>.
30#
31
Harald Weltec91085e2022-02-10 18:05:45 +010032from pySim.profile import match_sim
33from pySim.profile import CardProfile
34from pySim.filesystem import *
Harald Welte228ae8e2022-07-17 22:01:04 +020035from pySim.ts_31_102_telecom import DF_PHONEBOOK, DF_MULTIMEDIA, DF_MCS, DF_V2X
Harald Weltec91085e2022-02-10 18:05:45 +010036import enum
37from pySim.construct import *
38from construct import Optional as COptional
39from construct import *
40from struct import pack, unpack
41from typing import Tuple
42from pySim.tlv import *
43from pySim.utils import *
Supreeth Herlebf5d6022020-03-20 15:18:27 +010044
45# Mapping between SIM Service Number and its description
46EF_SST_map = {
Harald Weltec91085e2022-02-10 18:05:45 +010047 1: 'CHV1 disable function',
48 2: 'Abbreviated Dialling Numbers (ADN)',
49 3: 'Fixed Dialling Numbers (FDN)',
50 4: 'Short Message Storage (SMS)',
51 5: 'Advice of Charge (AoC)',
52 6: 'Capability Configuration Parameters (CCP)',
53 7: 'PLMN selector',
54 8: 'RFU',
55 9: 'MSISDN',
56 10: 'Extension1',
57 11: 'Extension2',
58 12: 'SMS Parameters',
59 13: 'Last Number Dialled (LND)',
60 14: 'Cell Broadcast Message Identifier',
61 15: 'Group Identifier Level 1',
62 16: 'Group Identifier Level 2',
63 17: 'Service Provider Name',
64 18: 'Service Dialling Numbers (SDN)',
65 19: 'Extension3',
66 20: 'RFU',
67 21: 'VGCS Group Identifier List (EFVGCS and EFVGCSS)',
68 22: 'VBS Group Identifier List (EFVBS and EFVBSS)',
69 23: 'enhanced Multi-Level Precedence and Pre-emption Service',
70 24: 'Automatic Answer for eMLPP',
71 25: 'Data download via SMS-CB',
72 26: 'Data download via SMS-PP',
73 27: 'Menu selection',
74 28: 'Call control',
75 29: 'Proactive SIM',
76 30: 'Cell Broadcast Message Identifier Ranges',
77 31: 'Barred Dialling Numbers (BDN)',
78 32: 'Extension4',
79 33: 'De-personalization Control Keys',
80 34: 'Co-operative Network List',
81 35: 'Short Message Status Reports',
82 36: 'Network\'s indication of alerting in the MS',
83 37: 'Mobile Originated Short Message control by SIM',
84 38: 'GPRS',
85 39: 'Image (IMG)',
86 40: 'SoLSA (Support of Local Service Area)',
87 41: 'USSD string data object supported in Call Control',
88 42: 'RUN AT COMMAND command',
89 43: 'User controlled PLMN Selector with Access Technology',
90 44: 'Operator controlled PLMN Selector with Access Technology',
91 45: 'HPLMN Selector with Access Technology',
92 46: 'CPBCCH Information',
93 47: 'Investigation Scan',
94 48: 'Extended Capability Configuration Parameters',
95 49: 'MExE',
96 50: 'Reserved and shall be ignored',
97 51: 'PLMN Network Name',
98 52: 'Operator PLMN List',
99 53: 'Mailbox Dialling Numbers',
100 54: 'Message Waiting Indication Status',
101 55: 'Call Forwarding Indication Status',
102 56: 'Service Provider Display Information',
103 57: 'Multimedia Messaging Service (MMS)',
104 58: 'Extension 8',
105 59: 'MMS User Connectivity Parameters',
Vadim Yanitskiydfe3dbb2020-07-28 05:26:02 +0700106}
107
Harald Welteb2edd142021-01-08 23:29:35 +0100108
109######################################################################
110# DF.TELECOM
111######################################################################
112
Harald Weltef11f1302023-01-24 17:59:59 +0100113
114# TS 51.011 Section 10.5.1 / Table 12
115class ExtendedBcdAdapter(Adapter):
116 """Replace some hex-characters with other ASCII characters"""
117 # we only translate a=* / b=# as they habe a clear representation
118 # in terms of USSD / SS service codes
119 def _decode(self, obj, context, path):
120 if not isinstance(obj, str):
121 return obj
122 return obj.lower().replace("a","*").replace("b","#")
123
124 def _encode(self, obj, context, path):
125 if not isinstance(obj, str):
126 return obj
127 return obj.replace("*","a").replace("#","b")
128
Harald Welteb2edd142021-01-08 23:29:35 +0100129# TS 51.011 Section 10.5.1
130class EF_ADN(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100131 _test_decode = [
132 ( '42204841203120536963ffffffff06810628560810ffffffffffffff',
133 { "alpha_id": "B HA 1 Sic", "len_of_bcd": 6, "ton_npi": { "ext": True, "type_of_number":
134 "unknown", "numbering_plan_id":
135 "isdn_e164" }, "dialing_nr":
136 "6082658001", "cap_conf_id": 255, "ext1_record_id": 255 }),
137 ]
138
Harald Welte0dc6c202023-01-24 18:10:13 +0100139 def __init__(self, fid='6f3a', sfid=None, name='EF.ADN', desc='Abbreviated Dialing Numbers', ext=1, **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200140 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(14, 30), **kwargs)
Harald Welte0dc6c202023-01-24 18:10:13 +0100141 ext_name = 'ext%u_record_id' % ext
Harald Welte1e73d222022-02-13 11:32:50 +0100142 self._construct = Struct('alpha_id'/COptional(GsmStringAdapter(Rpad(Bytes(this._.total_len-14)), codec='ascii')),
143 'len_of_bcd'/Int8ub,
144 'ton_npi'/TonNpi,
Harald Weltef11f1302023-01-24 17:59:59 +0100145 'dialing_nr'/ExtendedBcdAdapter(BcdAdapter(Rpad(Bytes(10)))),
Harald Welte1e73d222022-02-13 11:32:50 +0100146 'cap_conf_id'/Int8ub,
Harald Welte0dc6c202023-01-24 18:10:13 +0100147 ext_name/Int8ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100148
149# TS 51.011 Section 10.5.5
Harald Welteec7d0da2021-04-02 22:01:19 +0200150class EF_SMS(LinFixedEF):
Harald Welte6169c722022-02-12 09:05:15 +0100151 def __init__(self, fid='6f3c', sfid=None, name='EF.SMS', desc='Short messages', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200152 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(176, 176), **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100153
Harald Weltef6b37af2023-01-24 15:42:26 +0100154 def _decode_record_bin(self, raw_bin_data, **kwargs):
Harald Welteec7d0da2021-04-02 22:01:19 +0200155 def decode_status(status):
156 if status & 0x01 == 0x00:
157 return (None, 'free_space')
158 elif status & 0x07 == 0x01:
159 return ('mt', 'message_read')
160 elif status & 0x07 == 0x03:
161 return ('mt', 'message_to_be_read')
162 elif status & 0x07 == 0x07:
163 return ('mo', 'message_to_be_sent')
164 elif status & 0x1f == 0x05:
165 return ('mo', 'sent_status_not_requested')
166 elif status & 0x1f == 0x0d:
167 return ('mo', 'sent_status_req_but_not_received')
168 elif status & 0x1f == 0x15:
169 return ('mo', 'sent_status_req_rx_not_stored_smsr')
170 elif status & 0x1f == 0x1d:
171 return ('mo', 'sent_status_req_rx_stored_smsr')
172 else:
173 return (None, 'rfu')
174
175 status = decode_status(raw_bin_data[0])
176 remainder = raw_bin_data[1:]
177 return {'direction': status[0], 'status': status[1], 'remainder': b2h(remainder)}
178
179
180# TS 51.011 Section 10.5.5
Harald Welteb2edd142021-01-08 23:29:35 +0100181class EF_MSISDN(LinFixedEF):
Harald Welte6169c722022-02-12 09:05:15 +0100182 def __init__(self, fid='6f40', sfid=None, name='EF.MSISDN', desc='MSISDN', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200183 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(15, 34), **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100184
Harald Weltef6b37af2023-01-24 15:42:26 +0100185 def _decode_record_hex(self, raw_hex_data, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100186 return {'msisdn': dec_msisdn(raw_hex_data)}
Harald Weltec91085e2022-02-10 18:05:45 +0100187
Harald Weltef6b37af2023-01-24 15:42:26 +0100188 def _encode_record_hex(self, abstract, **kwargs):
Philipp Maierf9cbe092021-04-23 19:37:36 +0200189 msisdn = abstract['msisdn']
190 if type(msisdn) == str:
191 encoded_msisdn = enc_msisdn(msisdn)
192 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100193 encoded_msisdn = enc_msisdn(msisdn[2], msisdn[0], msisdn[1])
194 alpha_identifier = (list(self.rec_len)[
195 0] - len(encoded_msisdn) // 2) * "ff"
Philipp Maierb46cb3f2021-04-20 22:38:21 +0200196 return alpha_identifier + encoded_msisdn
Harald Welteb2edd142021-01-08 23:29:35 +0100197
198# TS 51.011 Section 10.5.6
199class EF_SMSP(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100200 # FIXME: re-encode fails / missing alpha_id at start of output
201 _test_decode = [
202 ( '454e6574776f726b73fffffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffff0000a7',
203 { "alpha_id": "ENetworks", "parameter_indicators": { "tp_dest_addr": False, "tp_sc_addr": True,
204 "tp_pid": True, "tp_dcs": True, "tp_vp": True },
205 "tp_dest_addr": { "length": 255, "ton_npi": { "ext": True, "type_of_number": "reserved_for_extension",
206 "numbering_plan_id": "reserved_for_extension" },
207 "call_number": "" },
208 "tp_sc_addr": { "length": 255, "ton_npi": { "ext": True, "type_of_number": "reserved_for_extension",
209 "numbering_plan_id": "reserved_for_extension" },
210 "call_number": "" },
211 "tp_pid": "00", "tp_dcs": "00", "tp_vp_minutes": 1440 } ),
212 ]
Harald Weltebc0e2092022-02-13 10:54:58 +0100213 class ValidityPeriodAdapter(Adapter):
214 def _decode(self, obj, context, path):
215 if obj <= 143:
216 return obj + 1 * 5
217 elif obj <= 167:
218 return 12 * 60 + ((obj - 143) * 30)
219 elif obj <= 196:
220 return (obj - 166) * (24 * 60)
221 elif obj <= 255:
222 return (obj - 192) * (7 * 24 * 60)
223 else:
224 raise ValueError
225 def _encode(self, obj, context, path):
226 if obj <= 12*60:
227 return obj/5 - 1
228 elif obj <= 24*60:
Harald Welte136bdb02023-01-31 16:23:32 +0100229 return 143 + ((obj - (12 * 60)) // 30)
Harald Weltebc0e2092022-02-13 10:54:58 +0100230 elif obj <= 30 * 24 * 60:
231 return 166 + (obj / (24 * 60))
232 elif obj <= 63 * 7 * 24 * 60:
Harald Welte136bdb02023-01-31 16:23:32 +0100233 return 192 + (obj // (7 * 24 * 60))
Harald Weltebc0e2092022-02-13 10:54:58 +0100234 else:
235 raise ValueError
236
Harald Welte6169c722022-02-12 09:05:15 +0100237 def __init__(self, fid='6f42', sfid=None, name='EF.SMSP', desc='Short message service parameters', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200238 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(28, None), **kwargs)
Harald Weltebc0e2092022-02-13 10:54:58 +0100239 ScAddr = Struct('length'/Int8ub, 'ton_npi'/TonNpi, 'call_number'/BcdAdapter(Rpad(Bytes(10))))
240 self._construct = Struct('alpha_id'/COptional(GsmStringAdapter(Rpad(Bytes(this._.total_len-28)))),
241 'parameter_indicators'/InvertAdapter(FlagsEnum(Byte, tp_dest_addr=1, tp_sc_addr=2,
242 tp_pid=3, tp_dcs=4, tp_vp=5)),
243 'tp_dest_addr'/ScAddr,
244 'tp_sc_addr'/ScAddr,
245
246 'tp_pid'/HexAdapter(Bytes(1)),
247 'tp_dcs'/HexAdapter(Bytes(1)),
248 'tp_vp_minutes'/EF_SMSP.ValidityPeriodAdapter(Byte))
Harald Welteb2edd142021-01-08 23:29:35 +0100249
Harald Welte790b2702021-04-11 00:01:35 +0200250# TS 51.011 Section 10.5.7
251class EF_SMSS(TransparentEF):
252 class MemCapAdapter(Adapter):
253 def _decode(self, obj, context, path):
254 return False if obj & 1 else True
Harald Weltec91085e2022-02-10 18:05:45 +0100255
Harald Welte790b2702021-04-11 00:01:35 +0200256 def _encode(self, obj, context, path):
257 return 0 if obj else 1
Harald Weltec91085e2022-02-10 18:05:45 +0100258
Harald Welte13edf302022-07-21 15:19:23 +0200259 def __init__(self, fid='6f43', sfid=None, name='EF.SMSS', desc='SMS status', size=(2, 8), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100260 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100261 self._construct = Struct(
262 'last_used_tpmr'/Int8ub, 'memory_capacity_exceeded'/self.MemCapAdapter(Int8ub))
Harald Welte790b2702021-04-11 00:01:35 +0200263
264# TS 51.011 Section 10.5.8
265class EF_SMSR(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200266 def __init__(self, fid='6f47', sfid=None, name='EF.SMSR', desc='SMS status reports', rec_len=(30, 30), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100267 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100268 self._construct = Struct(
269 'sms_record_id'/Int8ub, 'sms_status_report'/HexAdapter(Bytes(29)))
270
Harald Welte790b2702021-04-11 00:01:35 +0200271
272class EF_EXT(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200273 def __init__(self, fid, sfid=None, name='EF.EXT', desc='Extension', rec_len=(13, 13), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100274 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100275 self._construct = Struct(
276 'record_type'/Int8ub, 'extension_data'/HexAdapter(Bytes(11)), 'identifier'/Int8ub)
Harald Welte790b2702021-04-11 00:01:35 +0200277
278# TS 51.011 Section 10.5.16
279class EF_CMI(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200280 def __init__(self, fid='6f58', sfid=None, name='EF.CMI', rec_len=(2, 21),
Harald Welte6169c722022-02-12 09:05:15 +0100281 desc='Comparison Method Information', **kwargs):
282 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100283 self._construct = Struct(
Harald Welte540adb02022-02-13 11:33:21 +0100284 'alpha_id'/GsmStringAdapter(Rpad(Bytes(this._.total_len-1))), 'comparison_method_id'/Int8ub)
Harald Weltec91085e2022-02-10 18:05:45 +0100285
Harald Welte790b2702021-04-11 00:01:35 +0200286
Harald Welteb2edd142021-01-08 23:29:35 +0100287class DF_TELECOM(CardDF):
Harald Welte6169c722022-02-12 09:05:15 +0100288 def __init__(self, fid='7f10', name='DF.TELECOM', desc=None, **kwargs):
289 super().__init__(fid=fid, name=name, desc=desc, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100290 files = [
Harald Weltec91085e2022-02-10 18:05:45 +0100291 EF_ADN(),
Harald Welte0dc6c202023-01-24 18:10:13 +0100292 EF_ADN(fid='6f3b', name='EF.FDN', desc='Fixed dialling numbers', ext=2),
Harald Weltec91085e2022-02-10 18:05:45 +0100293 EF_SMS(),
294 LinFixedEF(fid='6f3d', name='EF.CCP',
Harald Welte99e4cc02022-07-21 15:25:47 +0200295 desc='Capability Configuration Parameters', rec_len=(14, 14)),
Harald Weltec91085e2022-02-10 18:05:45 +0100296 LinFixedEF(fid='6f4f', name='EF.ECCP',
Harald Welte99e4cc02022-07-21 15:25:47 +0200297 desc='Extended Capability Configuration Parameters', rec_len=(15, 32)),
Harald Weltec91085e2022-02-10 18:05:45 +0100298 EF_MSISDN(),
299 EF_SMSP(),
300 EF_SMSS(),
Harald Weltea1bb3f72023-01-24 18:15:56 +0100301 EF_ADN('6f44', None, 'EF.LND', 'Last Number Dialled', ext=1),
Harald Welte0dc6c202023-01-24 18:10:13 +0100302 EF_ADN('6f49', None, 'EF.SDN', 'Service Dialling Numbers', ext=3),
Harald Weltec91085e2022-02-10 18:05:45 +0100303 EF_EXT('6f4a', None, 'EF.EXT1', 'Extension1 (ADN/SSC)'),
304 EF_EXT('6f4b', None, 'EF.EXT2', 'Extension2 (FDN/SSC)'),
305 EF_EXT('6f4c', None, 'EF.EXT3', 'Extension3 (SDN)'),
306 EF_ADN(fid='6f4d', name='EF.BDN', desc='Barred Dialling Numbers'),
307 EF_EXT('6f4e', None, 'EF.EXT4', 'Extension4 (BDN/SSC)'),
308 EF_SMSR(),
309 EF_CMI(),
Harald Weltede4c14c2022-07-16 11:53:59 +0200310 # not really part of 51.011 but something that TS 31.102 specifies may exist here.
311 DF_PHONEBOOK(),
Harald Weltea0452212022-07-17 21:23:21 +0200312 DF_MULTIMEDIA(),
Harald Welte650f6122022-07-17 21:42:50 +0200313 DF_MCS(),
Harald Welte228ae8e2022-07-17 22:01:04 +0200314 DF_V2X(),
Harald Weltec91085e2022-02-10 18:05:45 +0100315 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100316 self.add_files(files)
317
Harald Welteb2edd142021-01-08 23:29:35 +0100318######################################################################
319# DF.GSM
320######################################################################
321
322# TS 51.011 Section 10.3.1
323class EF_LP(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100324 _test_de_encode = [
325 ( "24", "24"),
326 ]
Harald Welte13edf302022-07-21 15:19:23 +0200327 def __init__(self, fid='6f05', sfid=None, name='EF.LP', size=(1, None), rec_len=1,
Harald Welteb2edd142021-01-08 23:29:35 +0100328 desc='Language Preference'):
329 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len)
Harald Weltec91085e2022-02-10 18:05:45 +0100330
Harald Weltef6b37af2023-01-24 15:42:26 +0100331 def _decode_record_bin(self, in_bin, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100332 return b2h(in_bin)
Harald Weltec91085e2022-02-10 18:05:45 +0100333
Harald Weltef6b37af2023-01-24 15:42:26 +0100334 def _encode_record_bin(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100335 return h2b(in_json)
336
337# TS 51.011 Section 10.3.2
338class EF_IMSI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100339 _test_de_encode = [
340 ( "082982608200002080", { "imsi": "228062800000208" } ),
341 ( "082926101160845740", { "imsi": "262011106487504" } ),
342 ]
Harald Welte13edf302022-07-21 15:19:23 +0200343 def __init__(self, fid='6f07', sfid=None, name='EF.IMSI', desc='IMSI', size=(9, 9)):
Harald Welteb2edd142021-01-08 23:29:35 +0100344 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Bjoern Riemere91405e2021-12-17 15:16:35 +0100345 # add those commands to the general commands of a TransparentEF
346 self.shell_commands += [self.AddlShellCommands(self)]
Harald Weltec91085e2022-02-10 18:05:45 +0100347
Harald Welteb2edd142021-01-08 23:29:35 +0100348 def _decode_hex(self, raw_hex):
349 return {'imsi': dec_imsi(raw_hex)}
Harald Weltec91085e2022-02-10 18:05:45 +0100350
Harald Welteb2edd142021-01-08 23:29:35 +0100351 def _encode_hex(self, abstract):
352 return enc_imsi(abstract['imsi'])
Harald Weltec91085e2022-02-10 18:05:45 +0100353
Bjoern Riemere91405e2021-12-17 15:16:35 +0100354 @with_default_category('File-Specific Commands')
355 class AddlShellCommands(CommandSet):
Harald Weltec91085e2022-02-10 18:05:45 +0100356 def __init__(self, ef: TransparentEF):
Bjoern Riemere91405e2021-12-17 15:16:35 +0100357 super().__init__()
Harald Weltec91085e2022-02-10 18:05:45 +0100358 self._ef = ef
Bjoern Riemere91405e2021-12-17 15:16:35 +0100359
360 def do_update_imsi_plmn(self, arg: str):
361 """Change the plmn part of the IMSI"""
362 plmn = arg.strip()
363 if len(plmn) == 5 or len(plmn) == 6:
Harald Weltea6c0f882022-07-17 14:23:17 +0200364 (data, sw) = self._cmd.lchan.read_binary_dec()
Bjoern Riemere91405e2021-12-17 15:16:35 +0100365 if sw == '9000' and len(data['imsi'])-len(plmn) == 10:
366 imsi = data['imsi']
367 msin = imsi[len(plmn):]
Harald Weltea6c0f882022-07-17 14:23:17 +0200368 (data, sw) = self._cmd.lchan.update_binary_dec(
Harald Weltec91085e2022-02-10 18:05:45 +0100369 {'imsi': plmn+msin})
Bjoern Riemere91405e2021-12-17 15:16:35 +0100370 if sw == '9000' and data:
Harald Weltec91085e2022-02-10 18:05:45 +0100371 self._cmd.poutput_json(
Harald Weltea6c0f882022-07-17 14:23:17 +0200372 self._cmd.lchan.selected_file.decode_hex(data))
Bjoern Riemere91405e2021-12-17 15:16:35 +0100373 else:
374 raise ValueError("PLMN length does not match IMSI length")
375 else:
376 raise ValueError("PLMN has wrong length!")
377
Harald Welteb2edd142021-01-08 23:29:35 +0100378
379# TS 51.011 Section 10.3.4
380class EF_PLMNsel(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100381 _test_de_encode = [
382 ( "22F860", { "mcc": "228", "mnc": "06" } ),
383 ( "330420", { "mcc": "334", "mnc": "020" } ),
384 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100385 def __init__(self, fid='6f30', sfid=None, name='EF.PLMNsel', desc='PLMN selector',
Harald Welte13edf302022-07-21 15:19:23 +0200386 size=(24, None), rec_len=3, **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100387 super().__init__(fid, name=name, sfid=sfid, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100388
Harald Weltef6b37af2023-01-24 15:42:26 +0100389 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100390 if in_hex[:6] == "ffffff":
391 return None
392 else:
393 return dec_plmn(in_hex)
Harald Weltec91085e2022-02-10 18:05:45 +0100394
Harald Weltef6b37af2023-01-24 15:42:26 +0100395 def _encode_record_hex(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100396 if in_json == None:
397 return "ffffff"
398 else:
399 return enc_plmn(in_json['mcc'], in_json['mnc'])
400
Harald Welte790b2702021-04-11 00:01:35 +0200401# TS 51.011 Section 10.3.6
402class EF_ACMmax(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100403 _test_de_encode = [
404 ( "000000", { "acm_max": 0 } ),
405 ]
Harald Welte13edf302022-07-21 15:19:23 +0200406 def __init__(self, fid='6f37', sfid=None, name='EF.ACMmax', size=(3, 3),
Harald Welte6169c722022-02-12 09:05:15 +0100407 desc='ACM maximum value', **kwargs):
408 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200409 self._construct = Struct('acm_max'/Int24ub)
410
Harald Welteb2edd142021-01-08 23:29:35 +0100411# TS 51.011 Section 10.3.7
412class EF_ServiceTable(TransparentEF):
413 def __init__(self, fid, sfid, name, desc, size, table):
414 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
415 self.table = table
Harald Weltec224b3b2023-05-23 18:44:44 +0200416 self.shell_commands += [self.AddlShellCommands()]
Harald Weltec91085e2022-02-10 18:05:45 +0100417
Harald Welte7a8aa862021-10-14 20:46:19 +0200418 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100419 def _bit_byte_offset_for_service(service: int) -> Tuple[int, int]:
Harald Welte7a8aa862021-10-14 20:46:19 +0200420 i = service - 1
421 byte_offset = i//4
422 bit_offset = (i % 4) * 2
423 return (byte_offset, bit_offset)
Harald Weltec91085e2022-02-10 18:05:45 +0100424
Harald Welteb2edd142021-01-08 23:29:35 +0100425 def _decode_bin(self, raw_bin):
426 ret = {}
427 for i in range(0, len(raw_bin)*4):
428 service_nr = i+1
429 byte = int(raw_bin[i//4])
430 bit_offset = (i % 4) * 2
431 bits = (byte >> bit_offset) & 3
432 ret[service_nr] = {
Harald Weltec91085e2022-02-10 18:05:45 +0100433 'description': self.table[service_nr] if service_nr in self.table else None,
434 'allocated': True if bits & 1 else False,
435 'activated': True if bits & 2 else False,
436 }
Harald Welteb2edd142021-01-08 23:29:35 +0100437 return ret
Harald Weltec91085e2022-02-10 18:05:45 +0100438
Harald Welte7a8aa862021-10-14 20:46:19 +0200439 def _encode_bin(self, in_json):
440 # compute the required binary size
441 bin_len = 0
442 for srv in in_json.keys():
443 service_nr = int(srv)
Vadim Yanitskiy6b19d802023-04-22 19:55:00 +0700444 (byte_offset, bit_offset) = self._bit_byte_offset_for_service(service_nr)
Harald Welte7a8aa862021-10-14 20:46:19 +0200445 if byte_offset >= bin_len:
446 bin_len = byte_offset+1
447 # encode the actual data
448 out = bytearray(b'\x00' * bin_len)
449 for srv in in_json.keys():
450 service_nr = int(srv)
Vadim Yanitskiy6b19d802023-04-22 19:55:00 +0700451 (byte_offset, bit_offset) = self._bit_byte_offset_for_service(service_nr)
Harald Welte7a8aa862021-10-14 20:46:19 +0200452 bits = 0
453 if in_json[srv]['allocated'] == True:
454 bits |= 1
455 if in_json[srv]['activated'] == True:
456 bits |= 2
457 out[byte_offset] |= ((bits & 3) << bit_offset)
458 return out
Harald Welteb2edd142021-01-08 23:29:35 +0100459
Harald Weltec224b3b2023-05-23 18:44:44 +0200460 @with_default_category('File-Specific Commands')
461 class AddlShellCommands(CommandSet):
462 def _adjust_service(self, service_nr: int, allocate: Optional[bool] = None, activate : Optional[bool] = None):
463 (byte_offset, bit_offset) = EF_ServiceTable._bit_byte_offset_for_service(service_nr)
464 hex_data, sw = self._cmd.lchan.read_binary(length=1, offset=byte_offset)
465 data = h2b(hex_data)
466 if allocate is not None:
467 if allocate:
468 data[0] |= (1 << bit_offset)
469 else:
470 data[0] &= ~(1 << bit_offset)
471 if activate is not None:
472 if activate:
473 data[0] |= (2 << bit_offset)
474 else:
475 data[0] &= ~(2 << bit_offset)
476 total_data, sw = self._cmd.lchan.update_binary(b2h(data), offset=byte_offset)
477 return sw
478
479 def do_sst_service_allocate(self, arg):
480 """Allocate a service within EF.SST"""
481 self._adjust_service(int(arg), allocate = True)
482
483 def do_sst_service_deallocate(self, arg):
484 """Deallocate a service within EF.SST"""
485 self._adjust_service(int(arg), allocate = False)
486
487 def do_sst_service_activate(self, arg):
488 """Activate a service within EF.SST"""
489 self._adjust_service(int(arg), activate = True)
490
491 def do_sst_service_deactivate(self, arg):
492 """Deactivate a service within EF.SST"""
493 self._adjust_service(int(arg), activate = False)
494
495
Harald Welteb2edd142021-01-08 23:29:35 +0100496# TS 51.011 Section 10.3.11
497class EF_SPN(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100498 _test_de_encode = [
499 ( "0147534d2d52204348ffffffffffffffff",
500 { "rfu": 0, "hide_in_oplmn": False, "show_in_hplmn": True, "spn": "GSM-R CH" } ),
501 ]
502
Harald Welte6169c722022-02-12 09:05:15 +0100503 def __init__(self, fid='6f46', sfid=None, name='EF.SPN',
Harald Welte13edf302022-07-21 15:19:23 +0200504 desc='Service Provider Name', size=(17, 17), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100505 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200506 self._construct = BitStruct(
507 # Byte 1
508 'rfu'/BitsRFU(6),
509 'hide_in_oplmn'/Flag,
510 'show_in_hplmn'/Flag,
511 # Bytes 2..17
512 'spn'/Bytewise(GsmString(16))
513 )
Harald Welteb2edd142021-01-08 23:29:35 +0100514
515# TS 51.011 Section 10.3.13
516class EF_CBMI(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100517 # TODO: Test vectors
Harald Welte13edf302022-07-21 15:19:23 +0200518 def __init__(self, fid='6f45', sfid=None, name='EF.CBMI', size=(2, None), rec_len=2,
Harald Welte6169c722022-02-12 09:05:15 +0100519 desc='Cell Broadcast message identifier selection', **kwargs):
520 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200521 self._construct = GreedyRange(Int16ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100522
523# TS 51.011 Section 10.3.15
524class EF_ACC(TransparentEF):
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700525 # example: acc_list(15) will produce a dict with only ACC15 being True
526 # example: acc_list(2, 4) will produce a dict with ACC2 and ACC4 being True
527 # example: acc_list() will produce a dict with all ACCs being False
528 acc_list = lambda *active: {'ACC{}'.format(c) : c in active for c in range(16)}
529
Harald Welte865eea62023-01-27 19:26:12 +0100530 _test_de_encode = [
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700531 ( "0000", acc_list() ),
532 ( "0001", acc_list(0) ),
533 ( "0002", acc_list(1) ),
534 ( "0100", acc_list(8) ),
535 ( "8000", acc_list(15) ),
536 ( "802b", acc_list(0,1,3,5,15) ),
Harald Welte865eea62023-01-27 19:26:12 +0100537 ]
Harald Welte6169c722022-02-12 09:05:15 +0100538 def __init__(self, fid='6f78', sfid=None, name='EF.ACC',
Harald Welte13edf302022-07-21 15:19:23 +0200539 desc='Access Control Class', size=(2, 2), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100540 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700541 # LSB of octet 2 is ACC=0 ... MSB of octet 1 is ACC=15
542 flags = ['ACC{}'.format(c) / Flag for c in range(16)]
543 self._construct = ByteSwapped(BitsSwapped(BitStruct(*flags)))
Harald Welteb2edd142021-01-08 23:29:35 +0100544
Harald Welte790b2702021-04-11 00:01:35 +0200545# TS 51.011 Section 10.3.16
546class EF_LOCI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100547 _test_de_encode = [
548 ( "7802570222f81009780000",
549 { "tmsi": "78025702", "lai": "22f8100978", "tmsi_time": 0, "lu_status": "updated" } ),
550 ]
Harald Welte13edf302022-07-21 15:19:23 +0200551 def __init__(self, fid='6f7e', sfid=None, name='EF.LOCI', desc='Location Information', size=(11, 11)):
Harald Welte790b2702021-04-11 00:01:35 +0200552 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200553 self._construct = Struct('tmsi'/HexAdapter(Bytes(4)), 'lai'/HexAdapter(Bytes(5)), 'tmsi_time'/Int8ub,
Harald Welte790b2702021-04-11 00:01:35 +0200554 'lu_status'/Enum(Byte, updated=0, not_updated=1, plmn_not_allowed=2,
555 location_area_not_allowed=3))
556
Harald Welteb2edd142021-01-08 23:29:35 +0100557# TS 51.011 Section 10.3.18
558class EF_AD(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100559 _test_de_encode = [
560 ( "00ffff",
561 { "ms_operation_mode": "normal", "rfu1": 255, "rfu2": 127, "ofm": True, "extensions": None } ),
562 ]
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200563 class OP_MODE(enum.IntEnum):
Harald Weltec91085e2022-02-10 18:05:45 +0100564 normal = 0x00
565 type_approval = 0x80
566 normal_and_specific_facilities = 0x01
567 type_approval_and_specific_facilities = 0x81
568 maintenance_off_line = 0x02
569 cell_test = 0x04
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200570 #OP_MODE_DICT = {int(v) : str(v) for v in EF_AD.OP_MODE}
571 #OP_MODE_DICT_REVERSED = {str(v) : int(v) for v in EF_AD.OP_MODE}
572
Harald Welte13edf302022-07-21 15:19:23 +0200573 def __init__(self, fid='6fad', sfid=None, name='EF.AD', desc='Administrative Data', size=(3, 4)):
Harald Welteb2edd142021-01-08 23:29:35 +0100574 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200575 self._construct = BitStruct(
576 # Byte 1
577 'ms_operation_mode'/Bytewise(Enum(Byte, EF_AD.OP_MODE)),
578 # Byte 2
579 'rfu1'/Bytewise(ByteRFU),
580 # Byte 3
581 'rfu2'/BitsRFU(7),
582 'ofm'/Flag,
583 # Byte 4 (optional),
584 'extensions'/COptional(Struct(
585 'rfu3'/BitsRFU(4),
586 'mnc_len'/BitsInteger(4),
587 # Byte 5..N-4 (optional, RFU)
588 'extensions'/Bytewise(GreedyBytesRFU)
589 ))
590 )
Harald Welteb2edd142021-01-08 23:29:35 +0100591
Harald Welte790b2702021-04-11 00:01:35 +0200592# TS 51.011 Section 10.3.20 / 10.3.22
593class EF_VGCS(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100594 _test_de_encode = [
595 ( "92f9ffff", "299fffff" ),
596 ]
Harald Welte13edf302022-07-21 15:19:23 +0200597 def __init__(self, fid='6fb1', sfid=None, name='EF.VGCS', size=(4, 200), rec_len=4,
Harald Welte6169c722022-02-12 09:05:15 +0100598 desc='Voice Group Call Service', **kwargs):
599 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200600 self._construct = BcdAdapter(Bytes(4))
601
602# TS 51.011 Section 10.3.21 / 10.3.23
603class EF_VGCSS(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100604 _test_decode = [
605 ( "010000004540fc",
606 { "flags": [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
607 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ] }
608 ),
609 ]
Harald Welte13edf302022-07-21 15:19:23 +0200610 def __init__(self, fid='6fb2', sfid=None, name='EF.VGCSS', size=(7, 7),
Harald Welte6169c722022-02-12 09:05:15 +0100611 desc='Voice Group Call Service Status', **kwargs):
612 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte5b9472d2023-01-24 17:26:59 +0100613 self._construct = BitsSwapped(BitStruct(
614 'flags'/Bit[50], Padding(6, pattern=b'\xff')))
Harald Welte790b2702021-04-11 00:01:35 +0200615
616# TS 51.011 Section 10.3.24
617class EF_eMLPP(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100618 _test_de_encode = [
619 ( "7c04", { "levels": { "A": False, "B": False, "zero": True, "one": True,
620 "two": True, "three": True, "four": True },
621 "fast_call_setup_cond": { "A": False, "B": False, "zero": True, "one": False,
622 "two": False, "three": False, "four": False }
623 }),
624 ]
Harald Welte13edf302022-07-21 15:19:23 +0200625 def __init__(self, fid='6fb5', sfid=None, name='EF.eMLPP', size=(2, 2),
Harald Welte6169c722022-02-12 09:05:15 +0100626 desc='enhanced Multi Level Pre-emption and Priority', **kwargs):
627 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100628 FlagsConstruct = FlagsEnum(
629 Byte, A=1, B=2, zero=4, one=8, two=16, three=32, four=64)
630 self._construct = Struct(
631 'levels'/FlagsConstruct, 'fast_call_setup_cond'/FlagsConstruct)
Harald Welte790b2702021-04-11 00:01:35 +0200632
633# TS 51.011 Section 10.3.25
634class EF_AAeM(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100635 _test_de_encode = [
636 ( "3c", { "auto_answer_prio_levels": { "A": False, "B": False, "zero": True, "one": True,
637 "two": True, "three": True, "four": False } } ),
638 ]
Harald Welte13edf302022-07-21 15:19:23 +0200639 def __init__(self, fid='6fb6', sfid=None, name='EF.AAeM', size=(1, 1),
Harald Welte6169c722022-02-12 09:05:15 +0100640 desc='Automatic Answer for eMLPP Service', **kwargs):
641 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100642 FlagsConstruct = FlagsEnum(
643 Byte, A=1, B=2, zero=4, one=8, two=16, three=32, four=64)
Harald Welte790b2702021-04-11 00:01:35 +0200644 self._construct = Struct('auto_answer_prio_levels'/FlagsConstruct)
645
646# TS 51.011 Section 10.3.26
Harald Welteb2edd142021-01-08 23:29:35 +0100647class EF_CBMID(EF_CBMI):
Harald Welte13edf302022-07-21 15:19:23 +0200648 def __init__(self, fid='6f48', sfid=None, name='EF.CBMID', size=(2, None), rec_len=2,
Harald Welte6169c722022-02-12 09:05:15 +0100649 desc='Cell Broadcast Message Identifier for Data Download', **kwargs):
650 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200651 self._construct = GreedyRange(Int16ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100652
Harald Welte89e59542021-04-02 21:33:13 +0200653# TS 51.011 Section 10.3.27
654class EF_ECC(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200655 def __init__(self, fid='6fb7', sfid=None, name='EF.ECC', size=(3, 15), rec_len=3,
Harald Welte6169c722022-02-12 09:05:15 +0100656 desc='Emergency Call Codes', **kwargs):
657 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200658 self._construct = GreedyRange(BcdAdapter(Bytes(3)))
Harald Welteb2edd142021-01-08 23:29:35 +0100659
660# TS 51.011 Section 10.3.28
661class EF_CBMIR(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200662 def __init__(self, fid='6f50', sfid=None, name='EF.CBMIR', size=(4, None), rec_len=4,
Harald Welte6169c722022-02-12 09:05:15 +0100663 desc='Cell Broadcast message identifier range selection', **kwargs):
664 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200665 self._construct = GreedyRange(Struct('lower'/Int16ub, 'upper'/Int16ub))
Harald Welteb2edd142021-01-08 23:29:35 +0100666
Harald Welte790b2702021-04-11 00:01:35 +0200667# TS 51.011 Section 10.3.29
668class EF_DCK(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200669 def __init__(self, fid='6f2c', sfid=None, name='EF.DCK', size=(16, 16),
Harald Welte6169c722022-02-12 09:05:15 +0100670 desc='Depersonalisation Control Keys', **kwargs):
671 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200672 self._construct = Struct('network'/BcdAdapter(Bytes(4)),
673 'network_subset'/BcdAdapter(Bytes(4)),
674 'service_provider'/BcdAdapter(Bytes(4)),
675 'corporate'/BcdAdapter(Bytes(4)))
676# TS 51.011 Section 10.3.30
677class EF_CNL(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200678 def __init__(self, fid='6f32', sfid=None, name='EF.CNL', size=(6, None), rec_len=6,
Harald Welte6169c722022-02-12 09:05:15 +0100679 desc='Co-operative Network List', **kwargs):
680 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100681
Harald Weltef6b37af2023-01-24 15:42:26 +0100682 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welte790b2702021-04-11 00:01:35 +0200683 (in_plmn, sub, svp, corp) = unpack('!3sBBB', h2b(in_hex))
684 res = dec_plmn(b2h(in_plmn))
685 res['network_subset'] = sub
686 res['service_provider_id'] = svp
687 res['corporate_id'] = corp
688 return res
Harald Weltec91085e2022-02-10 18:05:45 +0100689
Harald Weltef6b37af2023-01-24 15:42:26 +0100690 def _encode_record_hex(self, in_json, **kwargs):
Harald Welte790b2702021-04-11 00:01:35 +0200691 plmn = enc_plmn(in_json['mcc'], in_json['mnc'])
Vadim Yanitskiy1a95d2b2021-05-02 01:42:09 +0200692 return b2h(pack('!3sBBB',
693 h2b(plmn),
694 in_json['network_subset'],
695 in_json['service_provider_id'],
696 in_json['corporate_id']))
Harald Welte790b2702021-04-11 00:01:35 +0200697
698# TS 51.011 Section 10.3.31
699class EF_NIA(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200700 def __init__(self, fid='6f51', sfid=None, name='EF.NIA', rec_len=(1, 32),
Harald Welte6169c722022-02-12 09:05:15 +0100701 desc='Network\'s Indication of Alerting', **kwargs):
702 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100703 self._construct = Struct(
704 'alerting_category'/Int8ub, 'category'/GreedyBytes)
Harald Welte790b2702021-04-11 00:01:35 +0200705
706# TS 51.011 Section 10.3.32
707class EF_Kc(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100708 _test_de_encode = [
709 ( "837d783609a3858f05", { "kc": "837d783609a3858f", "cksn": 5 } ),
710 ]
Harald Welte13edf302022-07-21 15:19:23 +0200711 def __init__(self, fid='6f20', sfid=None, name='EF.Kc', desc='Ciphering key Kc', size=(9, 9), **kwargs):
Harald Welted90ceb82022-07-17 22:10:58 +0200712 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200713 self._construct = Struct('kc'/HexAdapter(Bytes(8)), 'cksn'/Int8ub)
714
715# TS 51.011 Section 10.3.33
716class EF_LOCIGPRS(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100717 _test_de_encode = [
718 ( "ffffffffffffff22f8990000ff01",
719 { "ptmsi": "ffffffff", "ptmsi_sig": "ffffff", "rai": "22f8990000ff", "rau_status": "not_updated" } ),
720 ]
Harald Welte13edf302022-07-21 15:19:23 +0200721 def __init__(self, fid='6f53', sfid=None, name='EF.LOCIGPRS', desc='GPRS Location Information', size=(14, 14)):
Harald Welte790b2702021-04-11 00:01:35 +0200722 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Harald Welted2edd412023-01-31 16:49:03 +0100723 self._construct = Struct('ptmsi'/HexAdapter(Bytes(4)), 'ptmsi_sig'/HexAdapter(Bytes(3)),
724 'rai'/HexAdapter(Bytes(6)),
Harald Welte790b2702021-04-11 00:01:35 +0200725 'rau_status'/Enum(Byte, updated=0, not_updated=1, plmn_not_allowed=2,
726 routing_area_not_allowed=3))
Harald Welteb2edd142021-01-08 23:29:35 +0100727
728# TS 51.011 Section 10.3.35..37
729class EF_xPLMNwAcT(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100730 _test_de_encode = [
731 ( '62F2104000', { "mcc": "262", "mnc": "01", "act": [ "E-UTRAN" ] } ),
732 ( '62F2108000', { "mcc": "262", "mnc": "01", "act": [ "UTRAN" ] } ),
733 ]
734 def __init__(self, fid='1234', sfid=None, name=None, desc=None, size=(40, None), rec_len=5, **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100735 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100736
Harald Weltef6b37af2023-01-24 15:42:26 +0100737 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100738 if in_hex[:6] == "ffffff":
739 return None
740 else:
741 return dec_xplmn_w_act(in_hex)
Harald Weltec91085e2022-02-10 18:05:45 +0100742
Harald Weltef6b37af2023-01-24 15:42:26 +0100743 def _encode_record_hex(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100744 if in_json == None:
745 return "ffffff0000"
746 else:
747 hplmn = enc_plmn(in_json['mcc'], in_json['mnc'])
748 act = self.enc_act(in_json['act'])
749 return hplmn + act
Harald Weltec91085e2022-02-10 18:05:45 +0100750
Harald Welteb2edd142021-01-08 23:29:35 +0100751 @staticmethod
752 def enc_act(in_list):
753 u16 = 0
754 # first the simple ones
755 if 'UTRAN' in in_list:
756 u16 |= 0x8000
757 if 'NG-RAN' in in_list:
758 u16 |= 0x0800
759 if 'GSM COMPACT' in in_list:
760 u16 |= 0x0040
761 if 'cdma2000 HRPD' in in_list:
762 u16 |= 0x0020
763 if 'cdma2000 1xRTT' in in_list:
764 u16 |= 0x0010
765 # E-UTRAN
Philipp Maiere7d41792021-04-29 16:20:07 +0200766 if 'E-UTRAN' in in_list:
767 u16 |= 0x4000
Vadim Yanitskiy5452d642021-03-07 21:45:34 +0100768 if 'E-UTRAN WB-S1' in in_list:
769 u16 |= 0x6000
770 if 'E-UTRAN NB-S1' in in_list:
771 u16 |= 0x5000
Harald Welteb2edd142021-01-08 23:29:35 +0100772 # GSM mess
773 if 'GSM' in in_list and 'EC-GSM-IoT' in in_list:
774 u16 |= 0x008C
775 elif 'GSM' in in_list:
776 u16 |= 0x0084
777 elif 'EC-GSM-IuT' in in_list:
778 u16 |= 0x0088
Harald Weltec91085e2022-02-10 18:05:45 +0100779 return '%04X' % (u16)
Harald Welteb2edd142021-01-08 23:29:35 +0100780
Harald Welte790b2702021-04-11 00:01:35 +0200781# TS 51.011 Section 10.3.38
782class EF_CPBCCH(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200783 def __init__(self, fid='6f63', sfid=None, name='EF.CPBCCH', size=(2, 14), rec_len=2,
Harald Welted90ceb82022-07-17 22:10:58 +0200784 desc='CPBCCH Information', **kwargs):
785 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200786 self._construct = Struct('cpbcch'/Int16ub)
787
788# TS 51.011 Section 10.3.39
789class EF_InvScan(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200790 def __init__(self, fid='6f64', sfid=None, name='EF.InvScan', size=(1, 1),
Harald Welted90ceb82022-07-17 22:10:58 +0200791 desc='IOnvestigation Scan', **kwargs):
792 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100793 self._construct = FlagsEnum(
794 Byte, in_limited_service_mode=1, after_successful_plmn_selection=2)
Harald Welte790b2702021-04-11 00:01:35 +0200795
Harald Welte14105dc2021-05-31 08:48:51 +0200796# TS 51.011 Section 4.2.58
797class EF_PNN(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100798 # TODO: 430a82d432bbbc7eb75de432450a82d432bbbc7eb75de432ffffffff
799 # TODO: 430a82c596b34cbfbfe5eb39ffffffffffffffffffffffffffffffffffff
Harald Welte14105dc2021-05-31 08:48:51 +0200800 class FullNameForNetwork(BER_TLV_IE, tag=0x43):
801 # TS 24.008 10.5.3.5a
Harald Welte857f1102022-07-20 07:44:25 +0200802 # TODO: proper decode
803 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100804
Harald Welte14105dc2021-05-31 08:48:51 +0200805 class ShortNameForNetwork(BER_TLV_IE, tag=0x45):
806 # TS 24.008 10.5.3.5a
Harald Welte857f1102022-07-20 07:44:25 +0200807 # TODO: proper decode
808 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100809
Harald Welte14105dc2021-05-31 08:48:51 +0200810 class NetworkNameCollection(TLV_IE_Collection, nested=[FullNameForNetwork, ShortNameForNetwork]):
811 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100812
Harald Welte6169c722022-02-12 09:05:15 +0100813 def __init__(self, fid='6fc5', sfid=None, name='EF.PNN', desc='PLMN Network Name', **kwargs):
814 super().__init__(fid, sfid=sfid, name=name, desc=desc, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200815 self._tlv = EF_PNN.NetworkNameCollection
816
Harald Welte790b2702021-04-11 00:01:35 +0200817# TS 51.011 Section 10.3.42
818class EF_OPL(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100819 _test_de_encode = [
820 ( '62f2100000fffe01',
821 { "lai": { "mcc_mnc": "262f01", "lac_min": "0000", "lac_max": "fffe" }, "pnn_record_id": 1 } ),
822 ]
Harald Welte99e4cc02022-07-21 15:25:47 +0200823 def __init__(self, fid='6fc6', sfid=None, name='EF.OPL', rec_len=(8, 8), desc='Operator PLMN List', **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100824 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200825 self._construct = Struct('lai'/Struct('mcc_mnc'/BcdAdapter(Bytes(3)),
826 'lac_min'/HexAdapter(Bytes(2)), 'lac_max'/HexAdapter(Bytes(2))), 'pnn_record_id'/Int8ub)
Harald Welte790b2702021-04-11 00:01:35 +0200827
828# TS 51.011 Section 10.3.44 + TS 31.102 4.2.62
829class EF_MBI(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100830 _test_de_encode = [
831 ( '0100000000',
832 { "mbi_voicemail": 1, "mbi_fax": 0, "mbi_email": 0, "mbi_other": 0, "mbi_videocall": 0 } ),
833 ]
Harald Welte99e4cc02022-07-21 15:25:47 +0200834 def __init__(self, fid='6fc9', sfid=None, name='EF.MBI', rec_len=(4, 5), desc='Mailbox Identifier', **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100835 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200836 self._construct = Struct('mbi_voicemail'/Int8ub, 'mbi_fax'/Int8ub, 'mbi_email'/Int8ub,
837 'mbi_other'/Int8ub, 'mbi_videocall'/COptional(Int8ub))
838
839# TS 51.011 Section 10.3.45 + TS 31.102 4.2.63
840class EF_MWIS(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200841 def __init__(self, fid='6fca', sfid=None, name='EF.MWIS', rec_len=(5, 6),
Harald Welte6169c722022-02-12 09:05:15 +0100842 desc='Message Waiting Indication Status', **kwargs):
843 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200844 self._construct = Struct('mwi_status'/FlagsEnum(Byte, voicemail=1, fax=2, email=4, other=8, videomail=16),
845 'num_waiting_voicemail'/Int8ub,
846 'num_waiting_fax'/Int8ub, 'num_waiting_email'/Int8ub,
847 'num_waiting_other'/Int8ub, 'num_waiting_videomail'/COptional(Int8ub))
848
Harald Welte14105dc2021-05-31 08:48:51 +0200849# TS 51.011 Section 10.3.66
850class EF_SPDI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100851 # TODO: a305800337f800ffffffffffffffffffffffffffffffffffffffffffffff
Harald Welte14105dc2021-05-31 08:48:51 +0200852 class ServiceProviderPLMN(BER_TLV_IE, tag=0x80):
853 # flexible numbers of 3-byte PLMN records
854 _construct = GreedyRange(BcdAdapter(Bytes(3)))
Harald Weltec91085e2022-02-10 18:05:45 +0100855
Harald Welte14105dc2021-05-31 08:48:51 +0200856 class SPDI(BER_TLV_IE, tag=0xA3, nested=[ServiceProviderPLMN]):
857 pass
858 def __init__(self, fid='6fcd', sfid=None, name='EF.SPDI',
Harald Welte6169c722022-02-12 09:05:15 +0100859 desc='Service Provider Display Information', **kwargs):
860 super().__init__(fid, sfid=sfid, name=name, desc=desc, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200861 self._tlv = EF_SPDI.SPDI
862
Harald Welte790b2702021-04-11 00:01:35 +0200863# TS 51.011 Section 10.3.51
864class EF_MMSN(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200865 def __init__(self, fid='6fce', sfid=None, name='EF.MMSN', rec_len=(4, 20), desc='MMS Notification', **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100866 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200867 self._construct = Struct('mms_status'/HexAdapter(Bytes(2)), 'mms_implementation'/HexAdapter(Bytes(1)),
868 'mms_notification'/HexAdapter(Bytes(this._.total_len-4)), 'ext_record_nr'/Byte)
Harald Welte790b2702021-04-11 00:01:35 +0200869
Harald Welte14105dc2021-05-31 08:48:51 +0200870# TS 51.011 Annex K.1
871class MMS_Implementation(BER_TLV_IE, tag=0x80):
872 _construct = FlagsEnum(Byte, WAP=1)
873
Harald Welte790b2702021-04-11 00:01:35 +0200874# TS 51.011 Section 10.3.53
875class EF_MMSICP(TransparentEF):
Harald Welte14105dc2021-05-31 08:48:51 +0200876 class MMS_Relay_Server(BER_TLV_IE, tag=0x81):
877 # 3GPP TS 23.140
878 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100879
Harald Welte14105dc2021-05-31 08:48:51 +0200880 class Interface_to_CN(BER_TLV_IE, tag=0x82):
881 # 3GPP TS 23.140
882 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100883
Harald Welte14105dc2021-05-31 08:48:51 +0200884 class Gateway(BER_TLV_IE, tag=0x83):
885 # Address, Type of address, Port, Service, AuthType, AuthId, AuthPass / 3GPP TS 23.140
886 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100887
Harald Welte14105dc2021-05-31 08:48:51 +0200888 class MMS_ConnectivityParamters(TLV_IE_Collection,
Harald Weltec91085e2022-02-10 18:05:45 +0100889 nested=[MMS_Implementation, MMS_Relay_Server, Interface_to_CN, Gateway]):
Harald Welte14105dc2021-05-31 08:48:51 +0200890 pass
Harald Welte13edf302022-07-21 15:19:23 +0200891 def __init__(self, fid='6fd0', sfid=None, name='EF.MMSICP', size=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100892 desc='MMS Issuer Connectivity Parameters', **kwargs):
893 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200894 self._tlv = EF_MMSICP.MMS_ConnectivityParamters
Harald Welte790b2702021-04-11 00:01:35 +0200895
896# TS 51.011 Section 10.3.54
897class EF_MMSUP(LinFixedEF):
Harald Welte14105dc2021-05-31 08:48:51 +0200898 class MMS_UserPref_ProfileName(BER_TLV_IE, tag=0x81):
899 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100900
Harald Welte14105dc2021-05-31 08:48:51 +0200901 class MMS_UserPref_Info(BER_TLV_IE, tag=0x82):
902 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100903
Harald Welte14105dc2021-05-31 08:48:51 +0200904 class MMS_User_Preferences(TLV_IE_Collection,
Harald Weltec91085e2022-02-10 18:05:45 +0100905 nested=[MMS_Implementation, MMS_UserPref_ProfileName, MMS_UserPref_Info]):
Harald Welte14105dc2021-05-31 08:48:51 +0200906 pass
Harald Welte99e4cc02022-07-21 15:25:47 +0200907 def __init__(self, fid='6fd1', sfid=None, name='EF.MMSUP', rec_len=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100908 desc='MMS User Preferences', **kwargs):
909 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte6113fe92022-01-21 15:51:35 +0100910 self._tlv = EF_MMSUP.MMS_User_Preferences
Harald Welte790b2702021-04-11 00:01:35 +0200911
912# TS 51.011 Section 10.3.55
913class EF_MMSUCP(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200914 def __init__(self, fid='6fd2', sfid=None, name='EF.MMSUCP', size=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100915 desc='MMS User Connectivity Parameters', **kwargs):
916 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200917
Harald Welteb2edd142021-01-08 23:29:35 +0100918
919class DF_GSM(CardDF):
920 def __init__(self, fid='7f20', name='DF.GSM', desc='GSM Network related files'):
921 super().__init__(fid=fid, name=name, desc=desc)
Harald Welte61ef1572023-03-09 19:42:38 +0100922 self.shell_commands += [self.AddlShellCommands()]
923
Harald Welteb2edd142021-01-08 23:29:35 +0100924 files = [
Harald Weltec91085e2022-02-10 18:05:45 +0100925 EF_LP(),
926 EF_IMSI(),
927 EF_Kc(),
928 EF_PLMNsel(),
929 TransparentEF('6f31', None, 'EF.HPPLMN',
930 'Higher Priority PLMN search period'),
931 EF_ACMmax(),
932 EF_ServiceTable('6f38', None, 'EF.SST',
Harald Welte13edf302022-07-21 15:19:23 +0200933 'SIM service table', table=EF_SST_map, size=(2, 16)),
Harald Weltec91085e2022-02-10 18:05:45 +0100934 CyclicEF('6f39', None, 'EF.ACM',
Harald Welte99e4cc02022-07-21 15:25:47 +0200935 'Accumulated call meter', rec_len=(3, 3)),
Harald Weltec91085e2022-02-10 18:05:45 +0100936 TransparentEF('6f3e', None, 'EF.GID1', 'Group Identifier Level 1'),
937 TransparentEF('6f3f', None, 'EF.GID2', 'Group Identifier Level 2'),
938 EF_SPN(),
939 TransparentEF('6f41', None, 'EF.PUCT',
Harald Welte13edf302022-07-21 15:19:23 +0200940 'Price per unit and currency table', size=(5, 5)),
Harald Weltec91085e2022-02-10 18:05:45 +0100941 EF_CBMI(),
Harald Welte10a1a0a2023-05-24 15:19:28 +0200942 TransparentEF('6f74', None, 'EF.BCCH',
Harald Welte13edf302022-07-21 15:19:23 +0200943 'Broadcast control channels', size=(16, 16)),
Harald Weltec91085e2022-02-10 18:05:45 +0100944 EF_ACC(),
945 EF_PLMNsel('6f7b', None, 'EF.FPLMN',
Harald Welte13edf302022-07-21 15:19:23 +0200946 'Forbidden PLMNs', size=(12, 12)),
Harald Weltec91085e2022-02-10 18:05:45 +0100947 EF_LOCI(),
948 EF_AD(),
Harald Welte33eef852023-05-24 15:20:34 +0200949 TransparentEF('6fae', None, 'EF.Phase',
Harald Welte13edf302022-07-21 15:19:23 +0200950 'Phase identification', size=(1, 1)),
Harald Weltec91085e2022-02-10 18:05:45 +0100951 EF_VGCS(),
952 EF_VGCSS(),
953 EF_VGCS('6fb3', None, 'EF.VBS', 'Voice Broadcast Service'),
954 EF_VGCSS('6fb4', None, 'EF.VBSS',
955 'Voice Broadcast Service Status'),
956 EF_eMLPP(),
957 EF_AAeM(),
958 EF_CBMID(),
959 EF_ECC(),
960 EF_CBMIR(),
961 EF_DCK(),
962 EF_CNL(),
963 EF_NIA(),
964 EF_Kc('6f52', None, 'EF.KcGPRS', 'GPRS Ciphering key KcGPRS'),
965 EF_LOCIGPRS(),
966 TransparentEF('6f54', None, 'EF.SUME', 'SetUpMenu Elements'),
967 EF_xPLMNwAcT('6f60', None, 'EF.PLMNwAcT',
968 'User controlled PLMN Selector with Access Technology'),
969 EF_xPLMNwAcT('6f61', None, 'EF.OPLMNwAcT',
970 'Operator controlled PLMN Selector with Access Technology'),
971 EF_xPLMNwAcT('6f62', None, 'EF.HPLMNwAcT',
972 'HPLMN Selector with Access Technology'),
973 EF_CPBCCH(),
974 EF_InvScan(),
975 EF_PNN(),
976 EF_OPL(),
977 EF_ADN('6fc7', None, 'EF.MBDN', 'Mailbox Dialling Numbers'),
978 EF_MBI(),
979 EF_MWIS(),
980 EF_ADN('6fcb', None, 'EF.CFIS',
981 'Call Forwarding Indication Status'),
982 EF_EXT('6fc8', None, 'EF.EXT6', 'Externsion6 (MBDN)'),
983 EF_EXT('6fcc', None, 'EF.EXT7', 'Externsion7 (CFIS)'),
984 EF_SPDI(),
985 EF_MMSN(),
986 EF_EXT('6fcf', None, 'EF.EXT8', 'Extension8 (MMSN)'),
987 EF_MMSICP(),
988 EF_MMSUP(),
989 EF_MMSUCP(),
990 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100991 self.add_files(files)
992
Harald Welte61ef1572023-03-09 19:42:38 +0100993 @with_default_category('Application-Specific Commands')
994 class AddlShellCommands(CommandSet):
995 def __init__(self):
996 super().__init__()
997
998 authenticate_parser = argparse.ArgumentParser()
999 authenticate_parser.add_argument('rand', help='Random challenge')
1000
1001 @cmd2.with_argparser(authenticate_parser)
1002 def do_authenticate(self, opts):
1003 """Perform GSM Authentication."""
1004 (data, sw) = self._cmd.card._scc.run_gsm(opts.rand)
1005 self._cmd.poutput_json(data)
1006
Harald Weltec91085e2022-02-10 18:05:45 +01001007
Philipp Maierc8387dc2021-10-29 17:59:50 +02001008class CardProfileSIM(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +01001009
Vadim Yanitskiy87dd0202023-04-22 20:45:29 +07001010 ORDER = 3
Philipp Maiera028c7d2021-11-08 16:12:03 +01001011
Philipp Maierc8387dc2021-10-29 17:59:50 +02001012 def __init__(self):
Philipp Maiera4df9422021-11-10 17:13:40 +01001013 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +01001014 'Normal': {
1015 '9000': 'Normal ending of the command',
1016 '91xx': 'normal ending of the command, with extra information from the proactive SIM containing a command for the ME',
1017 '9exx': 'length XX of the response data given in case of a SIM data download error',
1018 '9fxx': 'length XX of the response data',
Philipp Maiera4df9422021-11-10 17:13:40 +01001019 },
Harald Weltec91085e2022-02-10 18:05:45 +01001020 'Postponed processing': {
1021 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Philipp Maiera4df9422021-11-10 17:13:40 +01001022 },
Harald Weltec91085e2022-02-10 18:05:45 +01001023 'Memory management': {
1024 '920x': 'command successful but after using an internal update retry routine X times',
1025 '9240': 'memory problem',
Philipp Maiera4df9422021-11-10 17:13:40 +01001026 },
Harald Weltec91085e2022-02-10 18:05:45 +01001027 'Referencing management': {
1028 '9400': 'no EF selected',
1029 '9402': 'out of range (invalid address)',
1030 '9404': 'file ID not found or pattern not found',
1031 '9408': 'file is inconsistent with the command',
Philipp Maiera4df9422021-11-10 17:13:40 +01001032 },
Harald Weltec91085e2022-02-10 18:05:45 +01001033 'Security management': {
1034 '9802': 'no CHV initialized',
1035 '9804': 'access condition not fulfilled, unsuccessful CHV verification or authentication failed',
1036 '9808': 'in contradiction with CHV status',
1037 '9810': 'in contradiction with invalidation status',
1038 '9840': 'unsuccessful verification, CHV blocked, UNBLOCK CHV blocked',
1039 '9850': 'increase cannot be performed, Max value reached',
Philipp Maiera4df9422021-11-10 17:13:40 +01001040 },
Harald Weltec91085e2022-02-10 18:05:45 +01001041 'Application independent errors': {
1042 '67xx': 'incorrect parameter P3',
1043 '6bxx': 'incorrect parameter P1 or P2',
1044 '6dxx': 'unknown instruction code given in the command',
1045 '6exx': 'wrong instruction class given in the command',
1046 '6fxx': 'technical problem with no diagnostic given',
Philipp Maiera4df9422021-11-10 17:13:40 +01001047 },
Harald Weltec91085e2022-02-10 18:05:45 +01001048 }
Philipp Maiera4df9422021-11-10 17:13:40 +01001049
Harald Weltec91085e2022-02-10 18:05:45 +01001050 super().__init__('SIM', desc='GSM SIM Card', cla="a0",
1051 sel_ctrl="0000", files_in_mf=[DF_TELECOM(), DF_GSM()], sw=sw)
Philipp Maier4ab971c2021-11-11 11:53:49 +01001052
Philipp Maier5998a3a2021-11-16 15:16:39 +01001053 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001054 def decode_select_response(resp_hex: str) -> object:
Harald Welte5924ec42023-01-24 19:49:24 +01001055 # we try to build something that resembles a dict resulting from the TLV decoder
1056 # of TS 102.221 (FcpTemplate), so that higher-level code only has to deal with one
1057 # format of SELECT response
Philipp Maier4ab971c2021-11-11 11:53:49 +01001058 resp_bin = h2b(resp_hex)
1059 struct_of_file_map = {
1060 0: 'transparent',
1061 1: 'linear_fixed',
1062 3: 'cyclic'
Harald Weltec91085e2022-02-10 18:05:45 +01001063 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001064 type_of_file_map = {
1065 1: 'mf',
1066 2: 'df',
1067 4: 'working_ef'
Harald Weltec91085e2022-02-10 18:05:45 +01001068 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001069 ret = {
Harald Welte747a9782022-02-13 17:52:28 +01001070 'file_descriptor': {
1071 'file_descriptor_byte': {},
1072 },
Philipp Maier4ab971c2021-11-11 11:53:49 +01001073 'proprietary_info': {},
Harald Weltec91085e2022-02-10 18:05:45 +01001074 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001075 ret['file_id'] = b2h(resp_bin[4:6])
Harald Weltec91085e2022-02-10 18:05:45 +01001076 file_type = type_of_file_map[resp_bin[6]
1077 ] if resp_bin[6] in type_of_file_map else resp_bin[6]
Harald Welte747a9782022-02-13 17:52:28 +01001078 ret['file_descriptor']['file_descriptor_byte']['file_type'] = file_type
Philipp Maier4ab971c2021-11-11 11:53:49 +01001079 if file_type in ['mf', 'df']:
Harald Welte5924ec42023-01-24 19:49:24 +01001080 ret['proprietary_info']['available_memory'] = int.from_bytes(resp_bin[2:4], 'big')
Philipp Maier4ab971c2021-11-11 11:53:49 +01001081 ret['file_characteristics'] = b2h(resp_bin[13:14])
1082 ret['num_direct_child_df'] = resp_bin[14]
1083 ret['num_direct_child_ef'] = resp_bin[15]
1084 ret['num_chv_unblock_adm_codes'] = int(resp_bin[16])
1085 # CHV / UNBLOCK CHV stats
1086 elif file_type in ['working_ef']:
Harald Welte5924ec42023-01-24 19:49:24 +01001087 ret['file_size'] = int.from_bytes(resp_bin[2:4], 'big')
Harald Weltec91085e2022-02-10 18:05:45 +01001088 file_struct = struct_of_file_map[resp_bin[13]
1089 ] if resp_bin[13] in struct_of_file_map else resp_bin[13]
Harald Welte747a9782022-02-13 17:52:28 +01001090 ret['file_descriptor']['file_descriptor_byte']['structure'] = file_struct
Harald Welte5924ec42023-01-24 19:49:24 +01001091 if file_struct != 'transparent':
1092 record_len = resp_bin[14]
1093 ret['file_descriptor']['record_len'] = record_len
1094 ret['file_descriptor']['num_of_rec'] = ret['file_size'] // record_len
Philipp Maier4ab971c2021-11-11 11:53:49 +01001095 ret['access_conditions'] = b2h(resp_bin[8:10])
1096 if resp_bin[11] & 0x01 == 0:
1097 ret['life_cycle_status_int'] = 'operational_activated'
1098 elif resp_bin[11] & 0x04:
1099 ret['life_cycle_status_int'] = 'operational_deactivated'
1100 else:
1101 ret['life_cycle_status_int'] = 'terminated'
1102 return ret
Philipp Maiera028c7d2021-11-08 16:12:03 +01001103
1104 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001105 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +01001106 return match_sim(scc)