blob: c81bfdfbacbc597bf445d6cd0f363bd0fe172921 [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
Harald Welte323a3502023-07-11 17:26:39 +020033from pySim.profile import CardProfile, CardProfileAddon
Harald Weltec91085e2022-02-10 18:05:45 +010034from 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 Welte323a3502023-07-11 17:26:39 +020036from pySim.gsm_r import AddonGSMR
Harald Weltec91085e2022-02-10 18:05:45 +010037import enum
38from pySim.construct import *
39from construct import Optional as COptional
40from construct import *
41from struct import pack, unpack
42from typing import Tuple
43from pySim.tlv import *
44from pySim.utils import *
Supreeth Herlebf5d6022020-03-20 15:18:27 +010045
46# Mapping between SIM Service Number and its description
47EF_SST_map = {
Harald Weltec91085e2022-02-10 18:05:45 +010048 1: 'CHV1 disable function',
49 2: 'Abbreviated Dialling Numbers (ADN)',
50 3: 'Fixed Dialling Numbers (FDN)',
51 4: 'Short Message Storage (SMS)',
52 5: 'Advice of Charge (AoC)',
53 6: 'Capability Configuration Parameters (CCP)',
54 7: 'PLMN selector',
55 8: 'RFU',
56 9: 'MSISDN',
57 10: 'Extension1',
58 11: 'Extension2',
59 12: 'SMS Parameters',
60 13: 'Last Number Dialled (LND)',
61 14: 'Cell Broadcast Message Identifier',
62 15: 'Group Identifier Level 1',
63 16: 'Group Identifier Level 2',
64 17: 'Service Provider Name',
65 18: 'Service Dialling Numbers (SDN)',
66 19: 'Extension3',
67 20: 'RFU',
68 21: 'VGCS Group Identifier List (EFVGCS and EFVGCSS)',
69 22: 'VBS Group Identifier List (EFVBS and EFVBSS)',
70 23: 'enhanced Multi-Level Precedence and Pre-emption Service',
71 24: 'Automatic Answer for eMLPP',
72 25: 'Data download via SMS-CB',
73 26: 'Data download via SMS-PP',
74 27: 'Menu selection',
75 28: 'Call control',
76 29: 'Proactive SIM',
77 30: 'Cell Broadcast Message Identifier Ranges',
78 31: 'Barred Dialling Numbers (BDN)',
79 32: 'Extension4',
80 33: 'De-personalization Control Keys',
81 34: 'Co-operative Network List',
82 35: 'Short Message Status Reports',
83 36: 'Network\'s indication of alerting in the MS',
84 37: 'Mobile Originated Short Message control by SIM',
85 38: 'GPRS',
86 39: 'Image (IMG)',
87 40: 'SoLSA (Support of Local Service Area)',
88 41: 'USSD string data object supported in Call Control',
89 42: 'RUN AT COMMAND command',
90 43: 'User controlled PLMN Selector with Access Technology',
91 44: 'Operator controlled PLMN Selector with Access Technology',
92 45: 'HPLMN Selector with Access Technology',
93 46: 'CPBCCH Information',
94 47: 'Investigation Scan',
95 48: 'Extended Capability Configuration Parameters',
96 49: 'MExE',
97 50: 'Reserved and shall be ignored',
98 51: 'PLMN Network Name',
99 52: 'Operator PLMN List',
100 53: 'Mailbox Dialling Numbers',
101 54: 'Message Waiting Indication Status',
102 55: 'Call Forwarding Indication Status',
103 56: 'Service Provider Display Information',
104 57: 'Multimedia Messaging Service (MMS)',
105 58: 'Extension 8',
106 59: 'MMS User Connectivity Parameters',
Vadim Yanitskiydfe3dbb2020-07-28 05:26:02 +0700107}
108
Harald Welteb2edd142021-01-08 23:29:35 +0100109
110######################################################################
111# DF.TELECOM
112######################################################################
113
Harald Weltef11f1302023-01-24 17:59:59 +0100114
115# TS 51.011 Section 10.5.1 / Table 12
116class ExtendedBcdAdapter(Adapter):
117 """Replace some hex-characters with other ASCII characters"""
118 # we only translate a=* / b=# as they habe a clear representation
119 # in terms of USSD / SS service codes
120 def _decode(self, obj, context, path):
121 if not isinstance(obj, str):
122 return obj
123 return obj.lower().replace("a","*").replace("b","#")
124
125 def _encode(self, obj, context, path):
126 if not isinstance(obj, str):
127 return obj
128 return obj.replace("*","a").replace("#","b")
129
Harald Welteb2edd142021-01-08 23:29:35 +0100130# TS 51.011 Section 10.5.1
131class EF_ADN(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100132 _test_decode = [
133 ( '42204841203120536963ffffffff06810628560810ffffffffffffff',
134 { "alpha_id": "B HA 1 Sic", "len_of_bcd": 6, "ton_npi": { "ext": True, "type_of_number":
135 "unknown", "numbering_plan_id":
136 "isdn_e164" }, "dialing_nr":
137 "6082658001", "cap_conf_id": 255, "ext1_record_id": 255 }),
138 ]
139
Harald Welte0dc6c202023-01-24 18:10:13 +0100140 def __init__(self, fid='6f3a', sfid=None, name='EF.ADN', desc='Abbreviated Dialing Numbers', ext=1, **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200141 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(14, 30), **kwargs)
Harald Welte0dc6c202023-01-24 18:10:13 +0100142 ext_name = 'ext%u_record_id' % ext
Harald Welte1e73d222022-02-13 11:32:50 +0100143 self._construct = Struct('alpha_id'/COptional(GsmStringAdapter(Rpad(Bytes(this._.total_len-14)), codec='ascii')),
144 'len_of_bcd'/Int8ub,
145 'ton_npi'/TonNpi,
Harald Weltef11f1302023-01-24 17:59:59 +0100146 'dialing_nr'/ExtendedBcdAdapter(BcdAdapter(Rpad(Bytes(10)))),
Harald Welte1e73d222022-02-13 11:32:50 +0100147 'cap_conf_id'/Int8ub,
Harald Welte0dc6c202023-01-24 18:10:13 +0100148 ext_name/Int8ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100149
150# TS 51.011 Section 10.5.5
Harald Welteec7d0da2021-04-02 22:01:19 +0200151class EF_SMS(LinFixedEF):
Harald Welte6169c722022-02-12 09:05:15 +0100152 def __init__(self, fid='6f3c', sfid=None, name='EF.SMS', desc='Short messages', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200153 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(176, 176), **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100154
Harald Weltef6b37af2023-01-24 15:42:26 +0100155 def _decode_record_bin(self, raw_bin_data, **kwargs):
Harald Welteec7d0da2021-04-02 22:01:19 +0200156 def decode_status(status):
157 if status & 0x01 == 0x00:
158 return (None, 'free_space')
159 elif status & 0x07 == 0x01:
160 return ('mt', 'message_read')
161 elif status & 0x07 == 0x03:
162 return ('mt', 'message_to_be_read')
163 elif status & 0x07 == 0x07:
164 return ('mo', 'message_to_be_sent')
165 elif status & 0x1f == 0x05:
166 return ('mo', 'sent_status_not_requested')
167 elif status & 0x1f == 0x0d:
168 return ('mo', 'sent_status_req_but_not_received')
169 elif status & 0x1f == 0x15:
170 return ('mo', 'sent_status_req_rx_not_stored_smsr')
171 elif status & 0x1f == 0x1d:
172 return ('mo', 'sent_status_req_rx_stored_smsr')
173 else:
174 return (None, 'rfu')
175
176 status = decode_status(raw_bin_data[0])
177 remainder = raw_bin_data[1:]
178 return {'direction': status[0], 'status': status[1], 'remainder': b2h(remainder)}
179
180
181# TS 51.011 Section 10.5.5
Harald Welteb2edd142021-01-08 23:29:35 +0100182class EF_MSISDN(LinFixedEF):
Harald Welte6169c722022-02-12 09:05:15 +0100183 def __init__(self, fid='6f40', sfid=None, name='EF.MSISDN', desc='MSISDN', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200184 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(15, 34), **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100185
Harald Weltef6b37af2023-01-24 15:42:26 +0100186 def _decode_record_hex(self, raw_hex_data, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100187 return {'msisdn': dec_msisdn(raw_hex_data)}
Harald Weltec91085e2022-02-10 18:05:45 +0100188
Harald Weltef6b37af2023-01-24 15:42:26 +0100189 def _encode_record_hex(self, abstract, **kwargs):
Philipp Maierf9cbe092021-04-23 19:37:36 +0200190 msisdn = abstract['msisdn']
191 if type(msisdn) == str:
192 encoded_msisdn = enc_msisdn(msisdn)
193 else:
Harald Weltec91085e2022-02-10 18:05:45 +0100194 encoded_msisdn = enc_msisdn(msisdn[2], msisdn[0], msisdn[1])
195 alpha_identifier = (list(self.rec_len)[
196 0] - len(encoded_msisdn) // 2) * "ff"
Philipp Maierb46cb3f2021-04-20 22:38:21 +0200197 return alpha_identifier + encoded_msisdn
Harald Welteb2edd142021-01-08 23:29:35 +0100198
199# TS 51.011 Section 10.5.6
200class EF_SMSP(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100201 # FIXME: re-encode fails / missing alpha_id at start of output
202 _test_decode = [
203 ( '454e6574776f726b73fffffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffff0000a7',
204 { "alpha_id": "ENetworks", "parameter_indicators": { "tp_dest_addr": False, "tp_sc_addr": True,
205 "tp_pid": True, "tp_dcs": True, "tp_vp": True },
206 "tp_dest_addr": { "length": 255, "ton_npi": { "ext": True, "type_of_number": "reserved_for_extension",
207 "numbering_plan_id": "reserved_for_extension" },
208 "call_number": "" },
209 "tp_sc_addr": { "length": 255, "ton_npi": { "ext": True, "type_of_number": "reserved_for_extension",
210 "numbering_plan_id": "reserved_for_extension" },
211 "call_number": "" },
212 "tp_pid": "00", "tp_dcs": "00", "tp_vp_minutes": 1440 } ),
213 ]
Harald Weltebc0e2092022-02-13 10:54:58 +0100214 class ValidityPeriodAdapter(Adapter):
215 def _decode(self, obj, context, path):
216 if obj <= 143:
217 return obj + 1 * 5
218 elif obj <= 167:
219 return 12 * 60 + ((obj - 143) * 30)
220 elif obj <= 196:
221 return (obj - 166) * (24 * 60)
222 elif obj <= 255:
223 return (obj - 192) * (7 * 24 * 60)
224 else:
225 raise ValueError
226 def _encode(self, obj, context, path):
227 if obj <= 12*60:
228 return obj/5 - 1
229 elif obj <= 24*60:
Harald Welte136bdb02023-01-31 16:23:32 +0100230 return 143 + ((obj - (12 * 60)) // 30)
Harald Weltebc0e2092022-02-13 10:54:58 +0100231 elif obj <= 30 * 24 * 60:
232 return 166 + (obj / (24 * 60))
233 elif obj <= 63 * 7 * 24 * 60:
Harald Welte136bdb02023-01-31 16:23:32 +0100234 return 192 + (obj // (7 * 24 * 60))
Harald Weltebc0e2092022-02-13 10:54:58 +0100235 else:
236 raise ValueError
237
Harald Welte6169c722022-02-12 09:05:15 +0100238 def __init__(self, fid='6f42', sfid=None, name='EF.SMSP', desc='Short message service parameters', **kwargs):
Harald Welte99e4cc02022-07-21 15:25:47 +0200239 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(28, None), **kwargs)
Harald Weltebc0e2092022-02-13 10:54:58 +0100240 ScAddr = Struct('length'/Int8ub, 'ton_npi'/TonNpi, 'call_number'/BcdAdapter(Rpad(Bytes(10))))
241 self._construct = Struct('alpha_id'/COptional(GsmStringAdapter(Rpad(Bytes(this._.total_len-28)))),
242 'parameter_indicators'/InvertAdapter(FlagsEnum(Byte, tp_dest_addr=1, tp_sc_addr=2,
243 tp_pid=3, tp_dcs=4, tp_vp=5)),
244 'tp_dest_addr'/ScAddr,
245 'tp_sc_addr'/ScAddr,
246
247 'tp_pid'/HexAdapter(Bytes(1)),
248 'tp_dcs'/HexAdapter(Bytes(1)),
249 'tp_vp_minutes'/EF_SMSP.ValidityPeriodAdapter(Byte))
Harald Welteb2edd142021-01-08 23:29:35 +0100250
Harald Welte790b2702021-04-11 00:01:35 +0200251# TS 51.011 Section 10.5.7
252class EF_SMSS(TransparentEF):
253 class MemCapAdapter(Adapter):
254 def _decode(self, obj, context, path):
255 return False if obj & 1 else True
Harald Weltec91085e2022-02-10 18:05:45 +0100256
Harald Welte790b2702021-04-11 00:01:35 +0200257 def _encode(self, obj, context, path):
258 return 0 if obj else 1
Harald Weltec91085e2022-02-10 18:05:45 +0100259
Harald Welte13edf302022-07-21 15:19:23 +0200260 def __init__(self, fid='6f43', sfid=None, name='EF.SMSS', desc='SMS status', size=(2, 8), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100261 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100262 self._construct = Struct(
263 'last_used_tpmr'/Int8ub, 'memory_capacity_exceeded'/self.MemCapAdapter(Int8ub))
Harald Welte790b2702021-04-11 00:01:35 +0200264
265# TS 51.011 Section 10.5.8
266class EF_SMSR(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200267 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 +0100268 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100269 self._construct = Struct(
270 'sms_record_id'/Int8ub, 'sms_status_report'/HexAdapter(Bytes(29)))
271
Harald Welte790b2702021-04-11 00:01:35 +0200272
273class EF_EXT(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200274 def __init__(self, fid, sfid=None, name='EF.EXT', desc='Extension', rec_len=(13, 13), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100275 super().__init__(fid=fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100276 self._construct = Struct(
277 'record_type'/Int8ub, 'extension_data'/HexAdapter(Bytes(11)), 'identifier'/Int8ub)
Harald Welte790b2702021-04-11 00:01:35 +0200278
279# TS 51.011 Section 10.5.16
280class EF_CMI(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200281 def __init__(self, fid='6f58', sfid=None, name='EF.CMI', rec_len=(2, 21),
Harald Welte6169c722022-02-12 09:05:15 +0100282 desc='Comparison Method Information', **kwargs):
283 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100284 self._construct = Struct(
Harald Welte540adb02022-02-13 11:33:21 +0100285 'alpha_id'/GsmStringAdapter(Rpad(Bytes(this._.total_len-1))), 'comparison_method_id'/Int8ub)
Harald Weltec91085e2022-02-10 18:05:45 +0100286
Harald Welte790b2702021-04-11 00:01:35 +0200287
Harald Welteb2edd142021-01-08 23:29:35 +0100288class DF_TELECOM(CardDF):
Harald Welte6169c722022-02-12 09:05:15 +0100289 def __init__(self, fid='7f10', name='DF.TELECOM', desc=None, **kwargs):
290 super().__init__(fid=fid, name=name, desc=desc, **kwargs)
Harald Welteb2edd142021-01-08 23:29:35 +0100291 files = [
Harald Weltec91085e2022-02-10 18:05:45 +0100292 EF_ADN(),
Harald Welte0dc6c202023-01-24 18:10:13 +0100293 EF_ADN(fid='6f3b', name='EF.FDN', desc='Fixed dialling numbers', ext=2),
Harald Weltec91085e2022-02-10 18:05:45 +0100294 EF_SMS(),
295 LinFixedEF(fid='6f3d', name='EF.CCP',
Harald Welte99e4cc02022-07-21 15:25:47 +0200296 desc='Capability Configuration Parameters', rec_len=(14, 14)),
Harald Weltec91085e2022-02-10 18:05:45 +0100297 LinFixedEF(fid='6f4f', name='EF.ECCP',
Harald Welte99e4cc02022-07-21 15:25:47 +0200298 desc='Extended Capability Configuration Parameters', rec_len=(15, 32)),
Harald Weltec91085e2022-02-10 18:05:45 +0100299 EF_MSISDN(),
300 EF_SMSP(),
301 EF_SMSS(),
Harald Weltea1bb3f72023-01-24 18:15:56 +0100302 EF_ADN('6f44', None, 'EF.LND', 'Last Number Dialled', ext=1),
Harald Welte0dc6c202023-01-24 18:10:13 +0100303 EF_ADN('6f49', None, 'EF.SDN', 'Service Dialling Numbers', ext=3),
Harald Weltec91085e2022-02-10 18:05:45 +0100304 EF_EXT('6f4a', None, 'EF.EXT1', 'Extension1 (ADN/SSC)'),
305 EF_EXT('6f4b', None, 'EF.EXT2', 'Extension2 (FDN/SSC)'),
306 EF_EXT('6f4c', None, 'EF.EXT3', 'Extension3 (SDN)'),
307 EF_ADN(fid='6f4d', name='EF.BDN', desc='Barred Dialling Numbers'),
308 EF_EXT('6f4e', None, 'EF.EXT4', 'Extension4 (BDN/SSC)'),
309 EF_SMSR(),
310 EF_CMI(),
Harald Weltede4c14c2022-07-16 11:53:59 +0200311 # not really part of 51.011 but something that TS 31.102 specifies may exist here.
312 DF_PHONEBOOK(),
Harald Weltea0452212022-07-17 21:23:21 +0200313 DF_MULTIMEDIA(),
Harald Welte650f6122022-07-17 21:42:50 +0200314 DF_MCS(),
Harald Welte228ae8e2022-07-17 22:01:04 +0200315 DF_V2X(),
Harald Weltec91085e2022-02-10 18:05:45 +0100316 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100317 self.add_files(files)
318
Harald Welteb2edd142021-01-08 23:29:35 +0100319######################################################################
320# DF.GSM
321######################################################################
322
323# TS 51.011 Section 10.3.1
324class EF_LP(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100325 _test_de_encode = [
326 ( "24", "24"),
327 ]
Harald Welte13edf302022-07-21 15:19:23 +0200328 def __init__(self, fid='6f05', sfid=None, name='EF.LP', size=(1, None), rec_len=1,
Harald Welteb2edd142021-01-08 23:29:35 +0100329 desc='Language Preference'):
330 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len)
Harald Weltec91085e2022-02-10 18:05:45 +0100331
Harald Weltef6b37af2023-01-24 15:42:26 +0100332 def _decode_record_bin(self, in_bin, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100333 return b2h(in_bin)
Harald Weltec91085e2022-02-10 18:05:45 +0100334
Harald Weltef6b37af2023-01-24 15:42:26 +0100335 def _encode_record_bin(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100336 return h2b(in_json)
337
338# TS 51.011 Section 10.3.2
339class EF_IMSI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100340 _test_de_encode = [
341 ( "082982608200002080", { "imsi": "228062800000208" } ),
342 ( "082926101160845740", { "imsi": "262011106487504" } ),
343 ]
Harald Welte13edf302022-07-21 15:19:23 +0200344 def __init__(self, fid='6f07', sfid=None, name='EF.IMSI', desc='IMSI', size=(9, 9)):
Harald Welteb2edd142021-01-08 23:29:35 +0100345 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Bjoern Riemere91405e2021-12-17 15:16:35 +0100346 # add those commands to the general commands of a TransparentEF
347 self.shell_commands += [self.AddlShellCommands(self)]
Harald Weltec91085e2022-02-10 18:05:45 +0100348
Harald Welteb2edd142021-01-08 23:29:35 +0100349 def _decode_hex(self, raw_hex):
350 return {'imsi': dec_imsi(raw_hex)}
Harald Weltec91085e2022-02-10 18:05:45 +0100351
Harald Welteb2edd142021-01-08 23:29:35 +0100352 def _encode_hex(self, abstract):
353 return enc_imsi(abstract['imsi'])
Harald Weltec91085e2022-02-10 18:05:45 +0100354
Bjoern Riemere91405e2021-12-17 15:16:35 +0100355 @with_default_category('File-Specific Commands')
356 class AddlShellCommands(CommandSet):
Harald Weltec91085e2022-02-10 18:05:45 +0100357 def __init__(self, ef: TransparentEF):
Bjoern Riemere91405e2021-12-17 15:16:35 +0100358 super().__init__()
Harald Weltec91085e2022-02-10 18:05:45 +0100359 self._ef = ef
Bjoern Riemere91405e2021-12-17 15:16:35 +0100360
361 def do_update_imsi_plmn(self, arg: str):
362 """Change the plmn part of the IMSI"""
363 plmn = arg.strip()
364 if len(plmn) == 5 or len(plmn) == 6:
Harald Weltea6c0f882022-07-17 14:23:17 +0200365 (data, sw) = self._cmd.lchan.read_binary_dec()
Bjoern Riemere91405e2021-12-17 15:16:35 +0100366 if sw == '9000' and len(data['imsi'])-len(plmn) == 10:
367 imsi = data['imsi']
368 msin = imsi[len(plmn):]
Harald Weltea6c0f882022-07-17 14:23:17 +0200369 (data, sw) = self._cmd.lchan.update_binary_dec(
Harald Weltec91085e2022-02-10 18:05:45 +0100370 {'imsi': plmn+msin})
Bjoern Riemere91405e2021-12-17 15:16:35 +0100371 if sw == '9000' and data:
Harald Weltec91085e2022-02-10 18:05:45 +0100372 self._cmd.poutput_json(
Harald Weltea6c0f882022-07-17 14:23:17 +0200373 self._cmd.lchan.selected_file.decode_hex(data))
Bjoern Riemere91405e2021-12-17 15:16:35 +0100374 else:
375 raise ValueError("PLMN length does not match IMSI length")
376 else:
377 raise ValueError("PLMN has wrong length!")
378
Harald Welteb2edd142021-01-08 23:29:35 +0100379
380# TS 51.011 Section 10.3.4
381class EF_PLMNsel(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100382 _test_de_encode = [
383 ( "22F860", { "mcc": "228", "mnc": "06" } ),
384 ( "330420", { "mcc": "334", "mnc": "020" } ),
385 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100386 def __init__(self, fid='6f30', sfid=None, name='EF.PLMNsel', desc='PLMN selector',
Harald Welte13edf302022-07-21 15:19:23 +0200387 size=(24, None), rec_len=3, **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100388 super().__init__(fid, name=name, sfid=sfid, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100389
Harald Weltef6b37af2023-01-24 15:42:26 +0100390 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100391 if in_hex[:6] == "ffffff":
392 return None
393 else:
394 return dec_plmn(in_hex)
Harald Weltec91085e2022-02-10 18:05:45 +0100395
Harald Weltef6b37af2023-01-24 15:42:26 +0100396 def _encode_record_hex(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100397 if in_json == None:
398 return "ffffff"
399 else:
400 return enc_plmn(in_json['mcc'], in_json['mnc'])
401
Harald Welte790b2702021-04-11 00:01:35 +0200402# TS 51.011 Section 10.3.6
403class EF_ACMmax(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100404 _test_de_encode = [
405 ( "000000", { "acm_max": 0 } ),
406 ]
Harald Welte13edf302022-07-21 15:19:23 +0200407 def __init__(self, fid='6f37', sfid=None, name='EF.ACMmax', size=(3, 3),
Harald Welte6169c722022-02-12 09:05:15 +0100408 desc='ACM maximum value', **kwargs):
409 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200410 self._construct = Struct('acm_max'/Int24ub)
411
Harald Welteb2edd142021-01-08 23:29:35 +0100412# TS 51.011 Section 10.3.7
413class EF_ServiceTable(TransparentEF):
414 def __init__(self, fid, sfid, name, desc, size, table):
415 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
416 self.table = table
Harald Weltec224b3b2023-05-23 18:44:44 +0200417 self.shell_commands += [self.AddlShellCommands()]
Harald Weltec91085e2022-02-10 18:05:45 +0100418
Harald Welte7a8aa862021-10-14 20:46:19 +0200419 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +0100420 def _bit_byte_offset_for_service(service: int) -> Tuple[int, int]:
Harald Welte7a8aa862021-10-14 20:46:19 +0200421 i = service - 1
422 byte_offset = i//4
423 bit_offset = (i % 4) * 2
424 return (byte_offset, bit_offset)
Harald Weltec91085e2022-02-10 18:05:45 +0100425
Harald Welteb2edd142021-01-08 23:29:35 +0100426 def _decode_bin(self, raw_bin):
427 ret = {}
428 for i in range(0, len(raw_bin)*4):
429 service_nr = i+1
430 byte = int(raw_bin[i//4])
431 bit_offset = (i % 4) * 2
432 bits = (byte >> bit_offset) & 3
433 ret[service_nr] = {
Harald Weltec91085e2022-02-10 18:05:45 +0100434 'description': self.table[service_nr] if service_nr in self.table else None,
435 'allocated': True if bits & 1 else False,
436 'activated': True if bits & 2 else False,
437 }
Harald Welteb2edd142021-01-08 23:29:35 +0100438 return ret
Harald Weltec91085e2022-02-10 18:05:45 +0100439
Harald Welte7a8aa862021-10-14 20:46:19 +0200440 def _encode_bin(self, in_json):
441 # compute the required binary size
442 bin_len = 0
443 for srv in in_json.keys():
444 service_nr = int(srv)
Vadim Yanitskiy6b19d802023-04-22 19:55:00 +0700445 (byte_offset, bit_offset) = self._bit_byte_offset_for_service(service_nr)
Harald Welte7a8aa862021-10-14 20:46:19 +0200446 if byte_offset >= bin_len:
447 bin_len = byte_offset+1
448 # encode the actual data
449 out = bytearray(b'\x00' * bin_len)
450 for srv in in_json.keys():
451 service_nr = int(srv)
Vadim Yanitskiy6b19d802023-04-22 19:55:00 +0700452 (byte_offset, bit_offset) = self._bit_byte_offset_for_service(service_nr)
Harald Welte7a8aa862021-10-14 20:46:19 +0200453 bits = 0
454 if in_json[srv]['allocated'] == True:
455 bits |= 1
456 if in_json[srv]['activated'] == True:
457 bits |= 2
458 out[byte_offset] |= ((bits & 3) << bit_offset)
459 return out
Harald Welteb2edd142021-01-08 23:29:35 +0100460
Harald Weltec224b3b2023-05-23 18:44:44 +0200461 @with_default_category('File-Specific Commands')
462 class AddlShellCommands(CommandSet):
463 def _adjust_service(self, service_nr: int, allocate: Optional[bool] = None, activate : Optional[bool] = None):
464 (byte_offset, bit_offset) = EF_ServiceTable._bit_byte_offset_for_service(service_nr)
465 hex_data, sw = self._cmd.lchan.read_binary(length=1, offset=byte_offset)
466 data = h2b(hex_data)
467 if allocate is not None:
468 if allocate:
469 data[0] |= (1 << bit_offset)
470 else:
471 data[0] &= ~(1 << bit_offset)
472 if activate is not None:
473 if activate:
474 data[0] |= (2 << bit_offset)
475 else:
476 data[0] &= ~(2 << bit_offset)
477 total_data, sw = self._cmd.lchan.update_binary(b2h(data), offset=byte_offset)
478 return sw
479
480 def do_sst_service_allocate(self, arg):
481 """Allocate a service within EF.SST"""
482 self._adjust_service(int(arg), allocate = True)
483
484 def do_sst_service_deallocate(self, arg):
485 """Deallocate a service within EF.SST"""
486 self._adjust_service(int(arg), allocate = False)
487
488 def do_sst_service_activate(self, arg):
489 """Activate a service within EF.SST"""
490 self._adjust_service(int(arg), activate = True)
491
492 def do_sst_service_deactivate(self, arg):
493 """Deactivate a service within EF.SST"""
494 self._adjust_service(int(arg), activate = False)
495
496
Harald Welteb2edd142021-01-08 23:29:35 +0100497# TS 51.011 Section 10.3.11
498class EF_SPN(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100499 _test_de_encode = [
500 ( "0147534d2d52204348ffffffffffffffff",
501 { "rfu": 0, "hide_in_oplmn": False, "show_in_hplmn": True, "spn": "GSM-R CH" } ),
502 ]
503
Harald Welte6169c722022-02-12 09:05:15 +0100504 def __init__(self, fid='6f46', sfid=None, name='EF.SPN',
Harald Welte13edf302022-07-21 15:19:23 +0200505 desc='Service Provider Name', size=(17, 17), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100506 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200507 self._construct = BitStruct(
508 # Byte 1
509 'rfu'/BitsRFU(6),
510 'hide_in_oplmn'/Flag,
511 'show_in_hplmn'/Flag,
512 # Bytes 2..17
513 'spn'/Bytewise(GsmString(16))
514 )
Harald Welteb2edd142021-01-08 23:29:35 +0100515
516# TS 51.011 Section 10.3.13
517class EF_CBMI(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100518 # TODO: Test vectors
Harald Welte13edf302022-07-21 15:19:23 +0200519 def __init__(self, fid='6f45', sfid=None, name='EF.CBMI', size=(2, None), rec_len=2,
Harald Welte6169c722022-02-12 09:05:15 +0100520 desc='Cell Broadcast message identifier selection', **kwargs):
521 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200522 self._construct = GreedyRange(Int16ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100523
524# TS 51.011 Section 10.3.15
525class EF_ACC(TransparentEF):
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700526 # example: acc_list(15) will produce a dict with only ACC15 being True
527 # example: acc_list(2, 4) will produce a dict with ACC2 and ACC4 being True
528 # example: acc_list() will produce a dict with all ACCs being False
529 acc_list = lambda *active: {'ACC{}'.format(c) : c in active for c in range(16)}
530
Harald Welte865eea62023-01-27 19:26:12 +0100531 _test_de_encode = [
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700532 ( "0000", acc_list() ),
533 ( "0001", acc_list(0) ),
534 ( "0002", acc_list(1) ),
535 ( "0100", acc_list(8) ),
536 ( "8000", acc_list(15) ),
537 ( "802b", acc_list(0,1,3,5,15) ),
Harald Welte865eea62023-01-27 19:26:12 +0100538 ]
Harald Welte6169c722022-02-12 09:05:15 +0100539 def __init__(self, fid='6f78', sfid=None, name='EF.ACC',
Harald Welte13edf302022-07-21 15:19:23 +0200540 desc='Access Control Class', size=(2, 2), **kwargs):
Harald Welte6169c722022-02-12 09:05:15 +0100541 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Vadim Yanitskiyb34f2342023-04-18 04:25:27 +0700542 # LSB of octet 2 is ACC=0 ... MSB of octet 1 is ACC=15
543 flags = ['ACC{}'.format(c) / Flag for c in range(16)]
544 self._construct = ByteSwapped(BitsSwapped(BitStruct(*flags)))
Harald Welteb2edd142021-01-08 23:29:35 +0100545
Harald Welte790b2702021-04-11 00:01:35 +0200546# TS 51.011 Section 10.3.16
547class EF_LOCI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100548 _test_de_encode = [
549 ( "7802570222f81009780000",
550 { "tmsi": "78025702", "lai": "22f8100978", "tmsi_time": 0, "lu_status": "updated" } ),
551 ]
Harald Welte13edf302022-07-21 15:19:23 +0200552 def __init__(self, fid='6f7e', sfid=None, name='EF.LOCI', desc='Location Information', size=(11, 11)):
Harald Welte790b2702021-04-11 00:01:35 +0200553 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200554 self._construct = Struct('tmsi'/HexAdapter(Bytes(4)), 'lai'/HexAdapter(Bytes(5)), 'tmsi_time'/Int8ub,
Harald Welte790b2702021-04-11 00:01:35 +0200555 'lu_status'/Enum(Byte, updated=0, not_updated=1, plmn_not_allowed=2,
556 location_area_not_allowed=3))
557
Harald Welteb2edd142021-01-08 23:29:35 +0100558# TS 51.011 Section 10.3.18
559class EF_AD(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100560 _test_de_encode = [
561 ( "00ffff",
562 { "ms_operation_mode": "normal", "rfu1": 255, "rfu2": 127, "ofm": True, "extensions": None } ),
563 ]
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200564 class OP_MODE(enum.IntEnum):
Harald Weltec91085e2022-02-10 18:05:45 +0100565 normal = 0x00
566 type_approval = 0x80
567 normal_and_specific_facilities = 0x01
568 type_approval_and_specific_facilities = 0x81
569 maintenance_off_line = 0x02
570 cell_test = 0x04
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200571 #OP_MODE_DICT = {int(v) : str(v) for v in EF_AD.OP_MODE}
572 #OP_MODE_DICT_REVERSED = {str(v) : int(v) for v in EF_AD.OP_MODE}
573
Harald Welte13edf302022-07-21 15:19:23 +0200574 def __init__(self, fid='6fad', sfid=None, name='EF.AD', desc='Administrative Data', size=(3, 4)):
Harald Welteb2edd142021-01-08 23:29:35 +0100575 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200576 self._construct = BitStruct(
577 # Byte 1
578 'ms_operation_mode'/Bytewise(Enum(Byte, EF_AD.OP_MODE)),
579 # Byte 2
580 'rfu1'/Bytewise(ByteRFU),
581 # Byte 3
582 'rfu2'/BitsRFU(7),
583 'ofm'/Flag,
584 # Byte 4 (optional),
585 'extensions'/COptional(Struct(
586 'rfu3'/BitsRFU(4),
587 'mnc_len'/BitsInteger(4),
588 # Byte 5..N-4 (optional, RFU)
589 'extensions'/Bytewise(GreedyBytesRFU)
590 ))
591 )
Harald Welteb2edd142021-01-08 23:29:35 +0100592
Harald Welte790b2702021-04-11 00:01:35 +0200593# TS 51.011 Section 10.3.20 / 10.3.22
594class EF_VGCS(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100595 _test_de_encode = [
596 ( "92f9ffff", "299fffff" ),
597 ]
Harald Welte13edf302022-07-21 15:19:23 +0200598 def __init__(self, fid='6fb1', sfid=None, name='EF.VGCS', size=(4, 200), rec_len=4,
Harald Welte6169c722022-02-12 09:05:15 +0100599 desc='Voice Group Call Service', **kwargs):
600 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200601 self._construct = BcdAdapter(Bytes(4))
602
603# TS 51.011 Section 10.3.21 / 10.3.23
604class EF_VGCSS(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100605 _test_decode = [
606 ( "010000004540fc",
607 { "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,
608 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 ] }
609 ),
610 ]
Harald Welte13edf302022-07-21 15:19:23 +0200611 def __init__(self, fid='6fb2', sfid=None, name='EF.VGCSS', size=(7, 7),
Harald Welte6169c722022-02-12 09:05:15 +0100612 desc='Voice Group Call Service Status', **kwargs):
613 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte5b9472d2023-01-24 17:26:59 +0100614 self._construct = BitsSwapped(BitStruct(
615 'flags'/Bit[50], Padding(6, pattern=b'\xff')))
Harald Welte790b2702021-04-11 00:01:35 +0200616
617# TS 51.011 Section 10.3.24
618class EF_eMLPP(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100619 _test_de_encode = [
620 ( "7c04", { "levels": { "A": False, "B": False, "zero": True, "one": True,
621 "two": True, "three": True, "four": True },
622 "fast_call_setup_cond": { "A": False, "B": False, "zero": True, "one": False,
623 "two": False, "three": False, "four": False }
624 }),
625 ]
Harald Welte13edf302022-07-21 15:19:23 +0200626 def __init__(self, fid='6fb5', sfid=None, name='EF.eMLPP', size=(2, 2),
Harald Welte6169c722022-02-12 09:05:15 +0100627 desc='enhanced Multi Level Pre-emption and Priority', **kwargs):
628 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100629 FlagsConstruct = FlagsEnum(
630 Byte, A=1, B=2, zero=4, one=8, two=16, three=32, four=64)
631 self._construct = Struct(
632 'levels'/FlagsConstruct, 'fast_call_setup_cond'/FlagsConstruct)
Harald Welte790b2702021-04-11 00:01:35 +0200633
634# TS 51.011 Section 10.3.25
635class EF_AAeM(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100636 _test_de_encode = [
637 ( "3c", { "auto_answer_prio_levels": { "A": False, "B": False, "zero": True, "one": True,
638 "two": True, "three": True, "four": False } } ),
639 ]
Harald Welte13edf302022-07-21 15:19:23 +0200640 def __init__(self, fid='6fb6', sfid=None, name='EF.AAeM', size=(1, 1),
Harald Welte6169c722022-02-12 09:05:15 +0100641 desc='Automatic Answer for eMLPP Service', **kwargs):
642 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100643 FlagsConstruct = FlagsEnum(
644 Byte, A=1, B=2, zero=4, one=8, two=16, three=32, four=64)
Harald Welte790b2702021-04-11 00:01:35 +0200645 self._construct = Struct('auto_answer_prio_levels'/FlagsConstruct)
646
647# TS 51.011 Section 10.3.26
Harald Welteb2edd142021-01-08 23:29:35 +0100648class EF_CBMID(EF_CBMI):
Harald Welte13edf302022-07-21 15:19:23 +0200649 def __init__(self, fid='6f48', sfid=None, name='EF.CBMID', size=(2, None), rec_len=2,
Harald Welte6169c722022-02-12 09:05:15 +0100650 desc='Cell Broadcast Message Identifier for Data Download', **kwargs):
651 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200652 self._construct = GreedyRange(Int16ub)
Harald Welteb2edd142021-01-08 23:29:35 +0100653
Harald Welte89e59542021-04-02 21:33:13 +0200654# TS 51.011 Section 10.3.27
655class EF_ECC(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200656 def __init__(self, fid='6fb7', sfid=None, name='EF.ECC', size=(3, 15), rec_len=3,
Harald Welte6169c722022-02-12 09:05:15 +0100657 desc='Emergency Call Codes', **kwargs):
658 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200659 self._construct = GreedyRange(BcdAdapter(Bytes(3)))
Harald Welteb2edd142021-01-08 23:29:35 +0100660
661# TS 51.011 Section 10.3.28
662class EF_CBMIR(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200663 def __init__(self, fid='6f50', sfid=None, name='EF.CBMIR', size=(4, None), rec_len=4,
Harald Welte6169c722022-02-12 09:05:15 +0100664 desc='Cell Broadcast message identifier range selection', **kwargs):
665 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200666 self._construct = GreedyRange(Struct('lower'/Int16ub, 'upper'/Int16ub))
Harald Welteb2edd142021-01-08 23:29:35 +0100667
Harald Welte790b2702021-04-11 00:01:35 +0200668# TS 51.011 Section 10.3.29
669class EF_DCK(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200670 def __init__(self, fid='6f2c', sfid=None, name='EF.DCK', size=(16, 16),
Harald Welte6169c722022-02-12 09:05:15 +0100671 desc='Depersonalisation Control Keys', **kwargs):
672 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200673 self._construct = Struct('network'/BcdAdapter(Bytes(4)),
674 'network_subset'/BcdAdapter(Bytes(4)),
675 'service_provider'/BcdAdapter(Bytes(4)),
676 'corporate'/BcdAdapter(Bytes(4)))
677# TS 51.011 Section 10.3.30
678class EF_CNL(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200679 def __init__(self, fid='6f32', sfid=None, name='EF.CNL', size=(6, None), rec_len=6,
Harald Welte6169c722022-02-12 09:05:15 +0100680 desc='Co-operative Network List', **kwargs):
681 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100682
Harald Weltef6b37af2023-01-24 15:42:26 +0100683 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welte790b2702021-04-11 00:01:35 +0200684 (in_plmn, sub, svp, corp) = unpack('!3sBBB', h2b(in_hex))
685 res = dec_plmn(b2h(in_plmn))
686 res['network_subset'] = sub
687 res['service_provider_id'] = svp
688 res['corporate_id'] = corp
689 return res
Harald Weltec91085e2022-02-10 18:05:45 +0100690
Harald Weltef6b37af2023-01-24 15:42:26 +0100691 def _encode_record_hex(self, in_json, **kwargs):
Harald Welte790b2702021-04-11 00:01:35 +0200692 plmn = enc_plmn(in_json['mcc'], in_json['mnc'])
Vadim Yanitskiy1a95d2b2021-05-02 01:42:09 +0200693 return b2h(pack('!3sBBB',
694 h2b(plmn),
695 in_json['network_subset'],
696 in_json['service_provider_id'],
697 in_json['corporate_id']))
Harald Welte790b2702021-04-11 00:01:35 +0200698
699# TS 51.011 Section 10.3.31
700class EF_NIA(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200701 def __init__(self, fid='6f51', sfid=None, name='EF.NIA', rec_len=(1, 32),
Harald Welte6169c722022-02-12 09:05:15 +0100702 desc='Network\'s Indication of Alerting', **kwargs):
703 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100704 self._construct = Struct(
705 'alerting_category'/Int8ub, 'category'/GreedyBytes)
Harald Welte790b2702021-04-11 00:01:35 +0200706
707# TS 51.011 Section 10.3.32
708class EF_Kc(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100709 _test_de_encode = [
710 ( "837d783609a3858f05", { "kc": "837d783609a3858f", "cksn": 5 } ),
711 ]
Harald Welte13edf302022-07-21 15:19:23 +0200712 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 +0200713 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200714 self._construct = Struct('kc'/HexAdapter(Bytes(8)), 'cksn'/Int8ub)
715
716# TS 51.011 Section 10.3.33
717class EF_LOCIGPRS(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100718 _test_de_encode = [
719 ( "ffffffffffffff22f8990000ff01",
720 { "ptmsi": "ffffffff", "ptmsi_sig": "ffffff", "rai": "22f8990000ff", "rau_status": "not_updated" } ),
721 ]
Harald Welte13edf302022-07-21 15:19:23 +0200722 def __init__(self, fid='6f53', sfid=None, name='EF.LOCIGPRS', desc='GPRS Location Information', size=(14, 14)):
Harald Welte790b2702021-04-11 00:01:35 +0200723 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size)
Harald Welted2edd412023-01-31 16:49:03 +0100724 self._construct = Struct('ptmsi'/HexAdapter(Bytes(4)), 'ptmsi_sig'/HexAdapter(Bytes(3)),
725 'rai'/HexAdapter(Bytes(6)),
Harald Welte790b2702021-04-11 00:01:35 +0200726 'rau_status'/Enum(Byte, updated=0, not_updated=1, plmn_not_allowed=2,
727 routing_area_not_allowed=3))
Harald Welteb2edd142021-01-08 23:29:35 +0100728
729# TS 51.011 Section 10.3.35..37
730class EF_xPLMNwAcT(TransRecEF):
Harald Welte865eea62023-01-27 19:26:12 +0100731 _test_de_encode = [
732 ( '62F2104000', { "mcc": "262", "mnc": "01", "act": [ "E-UTRAN" ] } ),
733 ( '62F2108000', { "mcc": "262", "mnc": "01", "act": [ "UTRAN" ] } ),
734 ]
735 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 +0100736 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100737
Harald Weltef6b37af2023-01-24 15:42:26 +0100738 def _decode_record_hex(self, in_hex, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100739 if in_hex[:6] == "ffffff":
740 return None
741 else:
742 return dec_xplmn_w_act(in_hex)
Harald Weltec91085e2022-02-10 18:05:45 +0100743
Harald Weltef6b37af2023-01-24 15:42:26 +0100744 def _encode_record_hex(self, in_json, **kwargs):
Harald Welteb2edd142021-01-08 23:29:35 +0100745 if in_json == None:
746 return "ffffff0000"
747 else:
748 hplmn = enc_plmn(in_json['mcc'], in_json['mnc'])
749 act = self.enc_act(in_json['act'])
750 return hplmn + act
Harald Weltec91085e2022-02-10 18:05:45 +0100751
Harald Welteb2edd142021-01-08 23:29:35 +0100752 @staticmethod
753 def enc_act(in_list):
754 u16 = 0
755 # first the simple ones
756 if 'UTRAN' in in_list:
757 u16 |= 0x8000
758 if 'NG-RAN' in in_list:
759 u16 |= 0x0800
760 if 'GSM COMPACT' in in_list:
761 u16 |= 0x0040
762 if 'cdma2000 HRPD' in in_list:
763 u16 |= 0x0020
764 if 'cdma2000 1xRTT' in in_list:
765 u16 |= 0x0010
766 # E-UTRAN
Philipp Maiere7d41792021-04-29 16:20:07 +0200767 if 'E-UTRAN' in in_list:
768 u16 |= 0x4000
Vadim Yanitskiy5452d642021-03-07 21:45:34 +0100769 if 'E-UTRAN WB-S1' in in_list:
770 u16 |= 0x6000
771 if 'E-UTRAN NB-S1' in in_list:
772 u16 |= 0x5000
Harald Welteb2edd142021-01-08 23:29:35 +0100773 # GSM mess
774 if 'GSM' in in_list and 'EC-GSM-IoT' in in_list:
775 u16 |= 0x008C
776 elif 'GSM' in in_list:
777 u16 |= 0x0084
778 elif 'EC-GSM-IuT' in in_list:
779 u16 |= 0x0088
Harald Weltec91085e2022-02-10 18:05:45 +0100780 return '%04X' % (u16)
Harald Welteb2edd142021-01-08 23:29:35 +0100781
Harald Welte790b2702021-04-11 00:01:35 +0200782# TS 51.011 Section 10.3.38
783class EF_CPBCCH(TransRecEF):
Harald Welte13edf302022-07-21 15:19:23 +0200784 def __init__(self, fid='6f63', sfid=None, name='EF.CPBCCH', size=(2, 14), rec_len=2,
Harald Welted90ceb82022-07-17 22:10:58 +0200785 desc='CPBCCH Information', **kwargs):
786 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200787 self._construct = Struct('cpbcch'/Int16ub)
788
789# TS 51.011 Section 10.3.39
790class EF_InvScan(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200791 def __init__(self, fid='6f64', sfid=None, name='EF.InvScan', size=(1, 1),
Harald Welted90ceb82022-07-17 22:10:58 +0200792 desc='IOnvestigation Scan', **kwargs):
793 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Weltec91085e2022-02-10 18:05:45 +0100794 self._construct = FlagsEnum(
795 Byte, in_limited_service_mode=1, after_successful_plmn_selection=2)
Harald Welte790b2702021-04-11 00:01:35 +0200796
Harald Welte14105dc2021-05-31 08:48:51 +0200797# TS 51.011 Section 4.2.58
798class EF_PNN(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100799 # TODO: 430a82d432bbbc7eb75de432450a82d432bbbc7eb75de432ffffffff
800 # TODO: 430a82c596b34cbfbfe5eb39ffffffffffffffffffffffffffffffffffff
Harald Welte14105dc2021-05-31 08:48:51 +0200801 class FullNameForNetwork(BER_TLV_IE, tag=0x43):
802 # TS 24.008 10.5.3.5a
Harald Welte857f1102022-07-20 07:44:25 +0200803 # TODO: proper decode
804 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100805
Harald Welte14105dc2021-05-31 08:48:51 +0200806 class ShortNameForNetwork(BER_TLV_IE, tag=0x45):
807 # TS 24.008 10.5.3.5a
Harald Welte857f1102022-07-20 07:44:25 +0200808 # TODO: proper decode
809 _construct = HexAdapter(GreedyBytes)
Harald Weltec91085e2022-02-10 18:05:45 +0100810
Harald Welte14105dc2021-05-31 08:48:51 +0200811 class NetworkNameCollection(TLV_IE_Collection, nested=[FullNameForNetwork, ShortNameForNetwork]):
812 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100813
Harald Welte6169c722022-02-12 09:05:15 +0100814 def __init__(self, fid='6fc5', sfid=None, name='EF.PNN', desc='PLMN Network Name', **kwargs):
815 super().__init__(fid, sfid=sfid, name=name, desc=desc, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200816 self._tlv = EF_PNN.NetworkNameCollection
817
Harald Welte790b2702021-04-11 00:01:35 +0200818# TS 51.011 Section 10.3.42
819class EF_OPL(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100820 _test_de_encode = [
821 ( '62f2100000fffe01',
822 { "lai": { "mcc_mnc": "262f01", "lac_min": "0000", "lac_max": "fffe" }, "pnn_record_id": 1 } ),
823 ]
Harald Welte99e4cc02022-07-21 15:25:47 +0200824 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 +0100825 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200826 self._construct = Struct('lai'/Struct('mcc_mnc'/BcdAdapter(Bytes(3)),
827 'lac_min'/HexAdapter(Bytes(2)), 'lac_max'/HexAdapter(Bytes(2))), 'pnn_record_id'/Int8ub)
Harald Welte790b2702021-04-11 00:01:35 +0200828
829# TS 51.011 Section 10.3.44 + TS 31.102 4.2.62
830class EF_MBI(LinFixedEF):
Harald Welte865eea62023-01-27 19:26:12 +0100831 _test_de_encode = [
832 ( '0100000000',
833 { "mbi_voicemail": 1, "mbi_fax": 0, "mbi_email": 0, "mbi_other": 0, "mbi_videocall": 0 } ),
834 ]
Harald Welte99e4cc02022-07-21 15:25:47 +0200835 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 +0100836 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200837 self._construct = Struct('mbi_voicemail'/Int8ub, 'mbi_fax'/Int8ub, 'mbi_email'/Int8ub,
838 'mbi_other'/Int8ub, 'mbi_videocall'/COptional(Int8ub))
839
840# TS 51.011 Section 10.3.45 + TS 31.102 4.2.63
841class EF_MWIS(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200842 def __init__(self, fid='6fca', sfid=None, name='EF.MWIS', rec_len=(5, 6),
Harald Welte6169c722022-02-12 09:05:15 +0100843 desc='Message Waiting Indication Status', **kwargs):
844 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200845 self._construct = Struct('mwi_status'/FlagsEnum(Byte, voicemail=1, fax=2, email=4, other=8, videomail=16),
846 'num_waiting_voicemail'/Int8ub,
847 'num_waiting_fax'/Int8ub, 'num_waiting_email'/Int8ub,
848 'num_waiting_other'/Int8ub, 'num_waiting_videomail'/COptional(Int8ub))
849
Harald Welte14105dc2021-05-31 08:48:51 +0200850# TS 51.011 Section 10.3.66
851class EF_SPDI(TransparentEF):
Harald Welte865eea62023-01-27 19:26:12 +0100852 # TODO: a305800337f800ffffffffffffffffffffffffffffffffffffffffffffff
Harald Welte14105dc2021-05-31 08:48:51 +0200853 class ServiceProviderPLMN(BER_TLV_IE, tag=0x80):
854 # flexible numbers of 3-byte PLMN records
855 _construct = GreedyRange(BcdAdapter(Bytes(3)))
Harald Weltec91085e2022-02-10 18:05:45 +0100856
Harald Welte14105dc2021-05-31 08:48:51 +0200857 class SPDI(BER_TLV_IE, tag=0xA3, nested=[ServiceProviderPLMN]):
858 pass
859 def __init__(self, fid='6fcd', sfid=None, name='EF.SPDI',
Harald Welte6169c722022-02-12 09:05:15 +0100860 desc='Service Provider Display Information', **kwargs):
861 super().__init__(fid, sfid=sfid, name=name, desc=desc, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200862 self._tlv = EF_SPDI.SPDI
863
Harald Welte790b2702021-04-11 00:01:35 +0200864# TS 51.011 Section 10.3.51
865class EF_MMSN(LinFixedEF):
Harald Welte99e4cc02022-07-21 15:25:47 +0200866 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 +0100867 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte3c98d5e2022-07-20 07:40:05 +0200868 self._construct = Struct('mms_status'/HexAdapter(Bytes(2)), 'mms_implementation'/HexAdapter(Bytes(1)),
869 'mms_notification'/HexAdapter(Bytes(this._.total_len-4)), 'ext_record_nr'/Byte)
Harald Welte790b2702021-04-11 00:01:35 +0200870
Harald Welte14105dc2021-05-31 08:48:51 +0200871# TS 51.011 Annex K.1
872class MMS_Implementation(BER_TLV_IE, tag=0x80):
873 _construct = FlagsEnum(Byte, WAP=1)
874
Harald Welte790b2702021-04-11 00:01:35 +0200875# TS 51.011 Section 10.3.53
876class EF_MMSICP(TransparentEF):
Harald Welte14105dc2021-05-31 08:48:51 +0200877 class MMS_Relay_Server(BER_TLV_IE, tag=0x81):
878 # 3GPP TS 23.140
879 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100880
Harald Welte14105dc2021-05-31 08:48:51 +0200881 class Interface_to_CN(BER_TLV_IE, tag=0x82):
882 # 3GPP TS 23.140
883 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100884
Harald Welte14105dc2021-05-31 08:48:51 +0200885 class Gateway(BER_TLV_IE, tag=0x83):
886 # Address, Type of address, Port, Service, AuthType, AuthId, AuthPass / 3GPP TS 23.140
887 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100888
Harald Welte14105dc2021-05-31 08:48:51 +0200889 class MMS_ConnectivityParamters(TLV_IE_Collection,
Harald Weltec91085e2022-02-10 18:05:45 +0100890 nested=[MMS_Implementation, MMS_Relay_Server, Interface_to_CN, Gateway]):
Harald Welte14105dc2021-05-31 08:48:51 +0200891 pass
Harald Welte13edf302022-07-21 15:19:23 +0200892 def __init__(self, fid='6fd0', sfid=None, name='EF.MMSICP', size=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100893 desc='MMS Issuer Connectivity Parameters', **kwargs):
894 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte14105dc2021-05-31 08:48:51 +0200895 self._tlv = EF_MMSICP.MMS_ConnectivityParamters
Harald Welte790b2702021-04-11 00:01:35 +0200896
897# TS 51.011 Section 10.3.54
898class EF_MMSUP(LinFixedEF):
Harald Welte14105dc2021-05-31 08:48:51 +0200899 class MMS_UserPref_ProfileName(BER_TLV_IE, tag=0x81):
900 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100901
Harald Welte14105dc2021-05-31 08:48:51 +0200902 class MMS_UserPref_Info(BER_TLV_IE, tag=0x82):
903 pass
Harald Weltec91085e2022-02-10 18:05:45 +0100904
Harald Welte14105dc2021-05-31 08:48:51 +0200905 class MMS_User_Preferences(TLV_IE_Collection,
Harald Weltec91085e2022-02-10 18:05:45 +0100906 nested=[MMS_Implementation, MMS_UserPref_ProfileName, MMS_UserPref_Info]):
Harald Welte14105dc2021-05-31 08:48:51 +0200907 pass
Harald Welte99e4cc02022-07-21 15:25:47 +0200908 def __init__(self, fid='6fd1', sfid=None, name='EF.MMSUP', rec_len=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100909 desc='MMS User Preferences', **kwargs):
910 super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=rec_len, **kwargs)
Harald Welte6113fe92022-01-21 15:51:35 +0100911 self._tlv = EF_MMSUP.MMS_User_Preferences
Harald Welte790b2702021-04-11 00:01:35 +0200912
913# TS 51.011 Section 10.3.55
914class EF_MMSUCP(TransparentEF):
Harald Welte13edf302022-07-21 15:19:23 +0200915 def __init__(self, fid='6fd2', sfid=None, name='EF.MMSUCP', size=(1, None),
Harald Welte6169c722022-02-12 09:05:15 +0100916 desc='MMS User Connectivity Parameters', **kwargs):
917 super().__init__(fid, sfid=sfid, name=name, desc=desc, size=size, **kwargs)
Harald Welte790b2702021-04-11 00:01:35 +0200918
Harald Welteb2edd142021-01-08 23:29:35 +0100919
920class DF_GSM(CardDF):
921 def __init__(self, fid='7f20', name='DF.GSM', desc='GSM Network related files'):
922 super().__init__(fid=fid, name=name, desc=desc)
Harald Welte61ef1572023-03-09 19:42:38 +0100923 self.shell_commands += [self.AddlShellCommands()]
924
Harald Welteb2edd142021-01-08 23:29:35 +0100925 files = [
Harald Weltec91085e2022-02-10 18:05:45 +0100926 EF_LP(),
927 EF_IMSI(),
928 EF_Kc(),
929 EF_PLMNsel(),
930 TransparentEF('6f31', None, 'EF.HPPLMN',
931 'Higher Priority PLMN search period'),
932 EF_ACMmax(),
933 EF_ServiceTable('6f38', None, 'EF.SST',
Harald Welte13edf302022-07-21 15:19:23 +0200934 'SIM service table', table=EF_SST_map, size=(2, 16)),
Harald Weltec91085e2022-02-10 18:05:45 +0100935 CyclicEF('6f39', None, 'EF.ACM',
Harald Welte99e4cc02022-07-21 15:25:47 +0200936 'Accumulated call meter', rec_len=(3, 3)),
Harald Weltec91085e2022-02-10 18:05:45 +0100937 TransparentEF('6f3e', None, 'EF.GID1', 'Group Identifier Level 1'),
938 TransparentEF('6f3f', None, 'EF.GID2', 'Group Identifier Level 2'),
939 EF_SPN(),
940 TransparentEF('6f41', None, 'EF.PUCT',
Harald Welte13edf302022-07-21 15:19:23 +0200941 'Price per unit and currency table', size=(5, 5)),
Harald Weltec91085e2022-02-10 18:05:45 +0100942 EF_CBMI(),
Harald Welte10a1a0a2023-05-24 15:19:28 +0200943 TransparentEF('6f74', None, 'EF.BCCH',
Harald Welte13edf302022-07-21 15:19:23 +0200944 'Broadcast control channels', size=(16, 16)),
Harald Weltec91085e2022-02-10 18:05:45 +0100945 EF_ACC(),
946 EF_PLMNsel('6f7b', None, 'EF.FPLMN',
Harald Welte13edf302022-07-21 15:19:23 +0200947 'Forbidden PLMNs', size=(12, 12)),
Harald Weltec91085e2022-02-10 18:05:45 +0100948 EF_LOCI(),
949 EF_AD(),
Harald Welte33eef852023-05-24 15:20:34 +0200950 TransparentEF('6fae', None, 'EF.Phase',
Harald Welte13edf302022-07-21 15:19:23 +0200951 'Phase identification', size=(1, 1)),
Harald Weltec91085e2022-02-10 18:05:45 +0100952 EF_VGCS(),
953 EF_VGCSS(),
954 EF_VGCS('6fb3', None, 'EF.VBS', 'Voice Broadcast Service'),
955 EF_VGCSS('6fb4', None, 'EF.VBSS',
956 'Voice Broadcast Service Status'),
957 EF_eMLPP(),
958 EF_AAeM(),
959 EF_CBMID(),
960 EF_ECC(),
961 EF_CBMIR(),
962 EF_DCK(),
963 EF_CNL(),
964 EF_NIA(),
965 EF_Kc('6f52', None, 'EF.KcGPRS', 'GPRS Ciphering key KcGPRS'),
966 EF_LOCIGPRS(),
967 TransparentEF('6f54', None, 'EF.SUME', 'SetUpMenu Elements'),
968 EF_xPLMNwAcT('6f60', None, 'EF.PLMNwAcT',
969 'User controlled PLMN Selector with Access Technology'),
970 EF_xPLMNwAcT('6f61', None, 'EF.OPLMNwAcT',
971 'Operator controlled PLMN Selector with Access Technology'),
972 EF_xPLMNwAcT('6f62', None, 'EF.HPLMNwAcT',
973 'HPLMN Selector with Access Technology'),
974 EF_CPBCCH(),
975 EF_InvScan(),
976 EF_PNN(),
977 EF_OPL(),
978 EF_ADN('6fc7', None, 'EF.MBDN', 'Mailbox Dialling Numbers'),
979 EF_MBI(),
980 EF_MWIS(),
981 EF_ADN('6fcb', None, 'EF.CFIS',
982 'Call Forwarding Indication Status'),
983 EF_EXT('6fc8', None, 'EF.EXT6', 'Externsion6 (MBDN)'),
984 EF_EXT('6fcc', None, 'EF.EXT7', 'Externsion7 (CFIS)'),
985 EF_SPDI(),
986 EF_MMSN(),
987 EF_EXT('6fcf', None, 'EF.EXT8', 'Extension8 (MMSN)'),
988 EF_MMSICP(),
989 EF_MMSUP(),
990 EF_MMSUCP(),
991 ]
Harald Welteb2edd142021-01-08 23:29:35 +0100992 self.add_files(files)
993
Harald Welte61ef1572023-03-09 19:42:38 +0100994 @with_default_category('Application-Specific Commands')
995 class AddlShellCommands(CommandSet):
996 def __init__(self):
997 super().__init__()
998
999 authenticate_parser = argparse.ArgumentParser()
1000 authenticate_parser.add_argument('rand', help='Random challenge')
1001
1002 @cmd2.with_argparser(authenticate_parser)
1003 def do_authenticate(self, opts):
1004 """Perform GSM Authentication."""
1005 (data, sw) = self._cmd.card._scc.run_gsm(opts.rand)
1006 self._cmd.poutput_json(data)
1007
Harald Weltec91085e2022-02-10 18:05:45 +01001008
Philipp Maierc8387dc2021-10-29 17:59:50 +02001009class CardProfileSIM(CardProfile):
Philipp Maiera028c7d2021-11-08 16:12:03 +01001010
Vadim Yanitskiy87dd0202023-04-22 20:45:29 +07001011 ORDER = 3
Philipp Maiera028c7d2021-11-08 16:12:03 +01001012
Philipp Maierc8387dc2021-10-29 17:59:50 +02001013 def __init__(self):
Philipp Maiera4df9422021-11-10 17:13:40 +01001014 sw = {
Harald Weltec91085e2022-02-10 18:05:45 +01001015 'Normal': {
1016 '9000': 'Normal ending of the command',
1017 '91xx': 'normal ending of the command, with extra information from the proactive SIM containing a command for the ME',
1018 '9exx': 'length XX of the response data given in case of a SIM data download error',
1019 '9fxx': 'length XX of the response data',
Philipp Maiera4df9422021-11-10 17:13:40 +01001020 },
Harald Weltec91085e2022-02-10 18:05:45 +01001021 'Postponed processing': {
1022 '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed',
Philipp Maiera4df9422021-11-10 17:13:40 +01001023 },
Harald Weltec91085e2022-02-10 18:05:45 +01001024 'Memory management': {
1025 '920x': 'command successful but after using an internal update retry routine X times',
1026 '9240': 'memory problem',
Philipp Maiera4df9422021-11-10 17:13:40 +01001027 },
Harald Weltec91085e2022-02-10 18:05:45 +01001028 'Referencing management': {
1029 '9400': 'no EF selected',
1030 '9402': 'out of range (invalid address)',
1031 '9404': 'file ID not found or pattern not found',
1032 '9408': 'file is inconsistent with the command',
Philipp Maiera4df9422021-11-10 17:13:40 +01001033 },
Harald Weltec91085e2022-02-10 18:05:45 +01001034 'Security management': {
1035 '9802': 'no CHV initialized',
1036 '9804': 'access condition not fulfilled, unsuccessful CHV verification or authentication failed',
1037 '9808': 'in contradiction with CHV status',
1038 '9810': 'in contradiction with invalidation status',
1039 '9840': 'unsuccessful verification, CHV blocked, UNBLOCK CHV blocked',
1040 '9850': 'increase cannot be performed, Max value reached',
Philipp Maiera4df9422021-11-10 17:13:40 +01001041 },
Harald Weltec91085e2022-02-10 18:05:45 +01001042 'Application independent errors': {
1043 '67xx': 'incorrect parameter P3',
1044 '6bxx': 'incorrect parameter P1 or P2',
1045 '6dxx': 'unknown instruction code given in the command',
1046 '6exx': 'wrong instruction class given in the command',
1047 '6fxx': 'technical problem with no diagnostic given',
Philipp Maiera4df9422021-11-10 17:13:40 +01001048 },
Harald Weltec91085e2022-02-10 18:05:45 +01001049 }
Philipp Maiera4df9422021-11-10 17:13:40 +01001050
Harald Welte323a3502023-07-11 17:26:39 +02001051 addons = [
1052 AddonGSMR,
1053 ]
1054
Harald Weltec91085e2022-02-10 18:05:45 +01001055 super().__init__('SIM', desc='GSM SIM Card', cla="a0",
Harald Welte323a3502023-07-11 17:26:39 +02001056 sel_ctrl="0000", files_in_mf=[DF_TELECOM(), DF_GSM()], sw=sw, addons = addons)
Philipp Maier4ab971c2021-11-11 11:53:49 +01001057
Philipp Maier5998a3a2021-11-16 15:16:39 +01001058 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001059 def decode_select_response(resp_hex: str) -> object:
Harald Welte5924ec42023-01-24 19:49:24 +01001060 # we try to build something that resembles a dict resulting from the TLV decoder
1061 # of TS 102.221 (FcpTemplate), so that higher-level code only has to deal with one
1062 # format of SELECT response
Philipp Maier4ab971c2021-11-11 11:53:49 +01001063 resp_bin = h2b(resp_hex)
1064 struct_of_file_map = {
1065 0: 'transparent',
1066 1: 'linear_fixed',
1067 3: 'cyclic'
Harald Weltec91085e2022-02-10 18:05:45 +01001068 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001069 type_of_file_map = {
1070 1: 'mf',
1071 2: 'df',
1072 4: 'working_ef'
Harald Weltec91085e2022-02-10 18:05:45 +01001073 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001074 ret = {
Harald Welte747a9782022-02-13 17:52:28 +01001075 'file_descriptor': {
1076 'file_descriptor_byte': {},
1077 },
Philipp Maier4ab971c2021-11-11 11:53:49 +01001078 'proprietary_info': {},
Harald Weltec91085e2022-02-10 18:05:45 +01001079 }
Philipp Maier4ab971c2021-11-11 11:53:49 +01001080 ret['file_id'] = b2h(resp_bin[4:6])
Harald Weltec91085e2022-02-10 18:05:45 +01001081 file_type = type_of_file_map[resp_bin[6]
1082 ] if resp_bin[6] in type_of_file_map else resp_bin[6]
Harald Welte747a9782022-02-13 17:52:28 +01001083 ret['file_descriptor']['file_descriptor_byte']['file_type'] = file_type
Philipp Maier4ab971c2021-11-11 11:53:49 +01001084 if file_type in ['mf', 'df']:
Harald Welte5924ec42023-01-24 19:49:24 +01001085 ret['proprietary_info']['available_memory'] = int.from_bytes(resp_bin[2:4], 'big')
Philipp Maier4ab971c2021-11-11 11:53:49 +01001086 ret['file_characteristics'] = b2h(resp_bin[13:14])
1087 ret['num_direct_child_df'] = resp_bin[14]
1088 ret['num_direct_child_ef'] = resp_bin[15]
1089 ret['num_chv_unblock_adm_codes'] = int(resp_bin[16])
1090 # CHV / UNBLOCK CHV stats
1091 elif file_type in ['working_ef']:
Harald Welte5924ec42023-01-24 19:49:24 +01001092 ret['file_size'] = int.from_bytes(resp_bin[2:4], 'big')
Harald Weltec91085e2022-02-10 18:05:45 +01001093 file_struct = struct_of_file_map[resp_bin[13]
1094 ] if resp_bin[13] in struct_of_file_map else resp_bin[13]
Harald Welte747a9782022-02-13 17:52:28 +01001095 ret['file_descriptor']['file_descriptor_byte']['structure'] = file_struct
Harald Welte5924ec42023-01-24 19:49:24 +01001096 if file_struct != 'transparent':
1097 record_len = resp_bin[14]
1098 ret['file_descriptor']['record_len'] = record_len
1099 ret['file_descriptor']['num_of_rec'] = ret['file_size'] // record_len
Philipp Maier4ab971c2021-11-11 11:53:49 +01001100 ret['access_conditions'] = b2h(resp_bin[8:10])
1101 if resp_bin[11] & 0x01 == 0:
1102 ret['life_cycle_status_int'] = 'operational_activated'
1103 elif resp_bin[11] & 0x04:
1104 ret['life_cycle_status_int'] = 'operational_deactivated'
1105 else:
1106 ret['life_cycle_status_int'] = 'terminated'
1107 return ret
Philipp Maiera028c7d2021-11-08 16:12:03 +01001108
1109 @staticmethod
Harald Weltec91085e2022-02-10 18:05:45 +01001110 def match_with_card(scc: SimCardCommands) -> bool:
Philipp Maiera028c7d2021-11-08 16:12:03 +01001111 return match_sim(scc)
Harald Welte323a3502023-07-11 17:26:39 +02001112
1113
1114class AddonSIM(CardProfileAddon):
1115 """An add-on that can be found on a UICC in order to support classic GSM SIM."""
1116 def __init__(self):
1117 files = [
1118 DF_GSM(),
1119 DF_TELECOM(),
1120 ]
1121 super().__init__('SIM', desc='GSM SIM', files_in_mf=files)
1122
1123 def probe(self, card:'CardBase') -> bool:
1124 # we assume the add-on to be present in case DF.GSM is found on the card
1125 return card.file_exists(self.files_in_mf[0].fid)