blob: dcba26ce855b9b286ded989c65a176cf21410575 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: Card programmation logic
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Welte3156d902011-03-22 21:48:19 +01008# Copyright (C) 2011 Harald Welte <laforge@gnumonks.org>
Alexander Chemeriseb6807d2017-07-18 17:04:38 +03009# Copyright (C) 2017 Alexander.Chemeris <Alexander.Chemeris@gmail.com>
Sylvain Munaut76504e02010-12-07 00:24:32 +010010#
11# This program is free software: you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation, either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program. If not, see <http://www.gnu.org/licenses/>.
23#
24
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020025from typing import Optional, Dict, Tuple
Vadim Yanitskiy85302d62021-05-02 02:18:42 +020026import abc
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020027
Robert Falkenbergb07a3e92021-05-07 15:23:20 +020028from pySim.ts_51_011 import EF, DF, EF_AD, EF_SPN
Harald Welteca673942020-06-03 15:19:40 +020029from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010030from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030031from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090032from smartcard.util import toBytes
Supreeth Herle79f43dd2020-03-25 11:43:19 +010033from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010034
35class Card(object):
36
37 def __init__(self, scc):
38 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030039 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010040 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010041
Sylvain Munaut76504e02010-12-07 00:24:32 +010042 def reset(self):
43 self._scc.reset_card()
44
Philipp Maierd58c6322020-05-12 16:47:45 +020045 def erase(self):
46 print("warning: erasing is not supported for specified card type!")
47 return
48
Harald Welteca673942020-06-03 15:19:40 +020049 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010050 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020051 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020052 if res[1] != '9000':
53 return False
Harald Welteca673942020-06-03 15:19:40 +020054 return True
55
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030056 def verify_adm(self, key):
57 '''
58 Authenticate with ADM key
59 '''
60 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
61 return sw
62
63 def read_iccid(self):
64 (res, sw) = self._scc.read_binary(EF['ICCID'])
65 if sw == '9000':
66 return (dec_iccid(res), sw)
67 else:
68 return (None, sw)
69
70 def read_imsi(self):
71 (res, sw) = self._scc.read_binary(EF['IMSI'])
72 if sw == '9000':
73 return (dec_imsi(res), sw)
74 else:
75 return (None, sw)
76
77 def update_imsi(self, imsi):
78 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
79 return sw
80
81 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +020082 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030083 return sw
84
Supreeth Herlea850a472020-03-19 12:44:11 +010085 def read_hplmn_act(self):
86 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
87 if sw == '9000':
88 return (format_xplmn_w_act(res), sw)
89 else:
90 return (None, sw)
91
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030092 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
93 """
94 Update Home PLMN with access technology bit-field
95
96 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
97 in ETSI TS 151 011 for the details of the access_tech field coding.
98 Some common values:
99 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +0200100 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300101 """
102 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100103 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700104 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300105 hplmn = enc_plmn(mcc, mnc)
106 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700107 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300108 return sw
109
Supreeth Herle1757b262020-03-19 12:43:11 +0100110 def read_oplmn_act(self):
111 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
112 if sw == '9000':
113 return (format_xplmn_w_act(res), sw)
114 else:
115 return (None, sw)
116
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200117 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
118 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200119 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200120 """
121 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200122 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700123 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200124 hplmn = enc_plmn(mcc, mnc)
125 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700126 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200127 return sw
128
Supreeth Herle14084402020-03-19 12:42:10 +0100129 def read_plmn_act(self):
130 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
131 if sw == '9000':
132 return (format_xplmn_w_act(res), sw)
133 else:
134 return (None, sw)
135
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200136 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
137 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200138 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200139 """
140 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200141 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700142 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200143 hplmn = enc_plmn(mcc, mnc)
144 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700145 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200146 return sw
147
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200148 def update_plmnsel(self, mcc, mnc):
149 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700150 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200151 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200152 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
153 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200154
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300155 def update_smsp(self, smsp):
156 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
157 return sw
158
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100159 def update_ad(self, mnc=None, opmode=None, ofm=None):
160 """
161 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100162
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100163 See Sec. "4.2.18 EF_AD (Administrative Data)"
164 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200165
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100166 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200167
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100168 Parameters:
169 mnc (str): MNC of IMSI
170 opmode (Hex-str, 1 Byte): MS Operation Mode
171 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
172
173 Returns:
174 str: Return code of write operation
175 """
176
177 ad = EF_AD()
178
179 # read from card
180 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200181 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100182
183 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200184 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100185 mnclen = len(str(mnc))
186 if mnclen == 1:
187 mnclen = 2
188 if mnclen > 3:
189 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200190 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100191 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200192 opmode_num = int(opmode, 16)
193 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
194 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100195 else:
196 raise RuntimeError('invalid opmode "{}"'.format(opmode))
197 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200198 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100199
200 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200201 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100202 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100203 return sw
204
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300205 def read_spn(self):
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200206 (content, sw) = self._scc.read_binary(EF['SPN'])
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300207 if sw == '9000':
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200208 abstract_data = EF_SPN().decode_hex(content)
209 show_in_hplmn = abstract_data['show_in_hplmn']
210 hide_in_oplmn = abstract_data['hide_in_oplmn']
211 name = abstract_data['spn']
212 return ((name, show_in_hplmn, hide_in_oplmn), sw)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300213 else:
214 return (None, sw)
215
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200216 def update_spn(self, name="", show_in_hplmn=False, hide_in_oplmn=False):
217 abstract_data = {
218 'hide_in_oplmn' : hide_in_oplmn,
219 'show_in_hplmn' : show_in_hplmn,
220 'spn' : name,
221 }
222 content = EF_SPN().encode_hex(abstract_data)
223 data, sw = self._scc.update_binary(EF['SPN'], content)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300224 return sw
225
Supreeth Herled21349a2020-04-01 08:37:47 +0200226 def read_binary(self, ef, length=None, offset=0):
227 ef_path = ef in EF and EF[ef] or ef
228 return self._scc.read_binary(ef_path, length, offset)
229
Supreeth Herlead10d662020-04-01 08:43:08 +0200230 def read_record(self, ef, rec_no):
231 ef_path = ef in EF and EF[ef] or ef
232 return self._scc.read_record(ef_path, rec_no)
233
Supreeth Herle98a69272020-03-18 12:14:48 +0100234 def read_gid1(self):
235 (res, sw) = self._scc.read_binary(EF['GID1'])
236 if sw == '9000':
237 return (res, sw)
238 else:
239 return (None, sw)
240
Supreeth Herle6d66af62020-03-19 12:49:16 +0100241 def read_msisdn(self):
242 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
243 if sw == '9000':
244 return (dec_msisdn(res), sw)
245 else:
246 return (None, sw)
247
Supreeth Herlee4e98312020-03-18 11:33:14 +0100248 # Fetch all the AIDs present on UICC
249 def read_aids(self):
Philipp Maier1e896f32021-03-10 17:02:53 +0100250 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100251 try:
252 # Find out how many records the EF.DIR has
253 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100254 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100255 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100256 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100257 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
258 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
259 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
260 except Exception as e:
261 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100262 self._aids = []
263 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100264
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100265 # Select ADF.U/ISIM in the Card using its full AID
266 def select_adf_by_aid(self, adf="usim"):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100267 # Find full AID by partial AID:
268 if is_hex(adf):
269 for aid in self._aids:
270 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
271 return self._scc.select_adf(aid)
272 # Find full AID by application name:
273 elif adf in ["usim", "isim"]:
274 # First (known) halves of the U/ISIM AID
275 aid_map = {}
276 aid_map["usim"] = "a0000000871002"
277 aid_map["isim"] = "a0000000871004"
278 for aid in self._aids:
279 if aid_map[adf] in aid:
280 return self._scc.select_adf(aid)
281 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100282
Philipp Maier5c2cc662020-05-12 16:27:12 +0200283 # Erase the contents of a file
284 def erase_binary(self, ef):
285 len = self._scc.binary_size(ef)
286 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
287
288 # Erase the contents of a single record
289 def erase_record(self, ef, rec_no):
290 len = self._scc.record_size(ef)
291 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
292
Harald Welteca673942020-06-03 15:19:40 +0200293class UsimCard(Card):
294 def __init__(self, ssc):
295 super(UsimCard, self).__init__(ssc)
296
297 def read_ehplmn(self):
298 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
299 if sw == '9000':
300 return (format_xplmn(res), sw)
301 else:
302 return (None, sw)
303
304 def update_ehplmn(self, mcc, mnc):
305 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
306 size = len(data[0]) // 2
307 ehplmn = enc_plmn(mcc, mnc)
308 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
309 return sw
310
herlesupreethf8232db2020-09-29 10:03:06 +0200311 def read_epdgid(self):
312 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
313 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100314 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200315 else:
316 return (None, sw)
317
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200318 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100319 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
320 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100321 addr_type = get_addr_type(epdgid)
322 if addr_type == None:
323 raise ValueError("Unknown ePDG Id address type or invalid address provided")
324 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100325 else:
326 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200327 data, sw = self._scc.update_binary(
328 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
329 return sw
Harald Welteca673942020-06-03 15:19:40 +0200330
Supreeth Herle99d55552020-03-24 13:03:43 +0100331 def read_ePDGSelection(self):
332 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
333 if sw == '9000':
334 return (format_ePDGSelection(res), sw)
335 else:
336 return (None, sw)
337
Supreeth Herlef964df42020-03-24 13:15:37 +0100338 def update_ePDGSelection(self, mcc, mnc):
339 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
340 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
341 # Reset contents
342 # 80 - Tag value
343 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
344 elif sw == '9000':
345 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
346 return sw
347
herlesupreeth4a3580b2020-09-29 10:11:36 +0200348 def read_ust(self):
349 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
350 if sw == '9000':
351 # Print those which are available
352 return ([res, dec_st(res, table="usim")], sw)
353 else:
354 return ([None, None], sw)
355
Supreeth Herleacc222f2020-03-24 13:26:53 +0100356 def update_ust(self, service, bit=1):
357 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
358 if sw == '9000':
359 content = enc_st(res, service, bit)
360 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
361 return sw
362
herlesupreethecbada92020-12-23 09:24:29 +0100363class IsimCard(Card):
364 def __init__(self, ssc):
365 super(IsimCard, self).__init__(ssc)
366
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100367 def read_pcscf(self):
368 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
369 pcscf_recs = ""
370 for i in range(0, rec_cnt):
371 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
372 if sw == '9000':
373 content = dec_addr_tlv(res)
374 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
375 else:
376 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
377 return pcscf_recs
378
Supreeth Herlecf727f22020-03-24 17:32:21 +0100379 def update_pcscf(self, pcscf):
380 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100381 addr_type = get_addr_type(pcscf)
382 if addr_type == None:
383 raise ValueError("Unknown PCSCF address type or invalid address provided")
384 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100385 else:
386 # Just the tag value
387 content = '80'
388 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100389 pcscf_tlv = rpad(content, rec_size_bytes*2)
390 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100391 return sw
392
Supreeth Herle05b28072020-03-25 10:23:48 +0100393 def read_domain(self):
394 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
395 if sw == '9000':
396 # Skip the inital tag value ('80') byte and get length of contents
397 length = int(res[2:4], 16)
398 content = h2s(res[4:4+(length*2)])
399 return (content, sw)
400 else:
401 return (None, sw)
402
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100403 def update_domain(self, domain=None, mcc=None, mnc=None):
404 hex_str = ""
405 if domain:
406 hex_str = s2h(domain)
407 elif mcc and mnc:
408 # MCC and MNC always has 3 digits in domain form
409 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
410 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
411
412 # Build TLV
413 tlv = TLV(['80'])
414 content = tlv.build({'80': hex_str})
415
416 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
417 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
418 return sw
419
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100420 def read_impi(self):
421 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
422 if sw == '9000':
423 # Skip the inital tag value ('80') byte and get length of contents
424 length = int(res[2:4], 16)
425 content = h2s(res[4:4+(length*2)])
426 return (content, sw)
427 else:
428 return (None, sw)
429
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100430 def update_impi(self, impi=None):
431 hex_str = ""
432 if impi:
433 hex_str = s2h(impi)
434 # Build TLV
435 tlv = TLV(['80'])
436 content = tlv.build({'80': hex_str})
437
438 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
439 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
440 return sw
441
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100442 def read_impu(self):
443 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
444 impu_recs = ""
445 for i in range(0, rec_cnt):
446 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
447 if sw == '9000':
448 # Skip the inital tag value ('80') byte and get length of contents
449 length = int(res[2:4], 16)
450 content = h2s(res[4:4+(length*2)])
451 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
452 else:
453 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
454 return impu_recs
455
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100456 def update_impu(self, impu=None):
457 hex_str = ""
458 if impu:
459 hex_str = s2h(impu)
460 # Build TLV
461 tlv = TLV(['80'])
462 content = tlv.build({'80': hex_str})
463
464 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
465 impu_tlv = rpad(content, rec_size_bytes*2)
466 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
467 return sw
468
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200469 def read_iari(self):
470 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
471 uiari_recs = ""
472 for i in range(0, rec_cnt):
473 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
474 if sw == '9000':
475 # Skip the inital tag value ('80') byte and get length of contents
476 length = int(res[2:4], 16)
477 content = h2s(res[4:4+(length*2)])
478 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
479 else:
480 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
481 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100482
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200483class MagicSimBase(abc.ABC, Card):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100484 """
485 Theses cards uses several record based EFs to store the provider infos,
486 each possible provider uses a specific record number in each EF. The
487 indexes used are ( where N is the number of providers supported ) :
488 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200489 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100490
491 * 3f00/7f4d/8f0c : Operator Name
492
493 bytes 0-15 : provider name, padded with 0xff
494 byte 16 : length of the provider name
495 byte 17 : 01 for valid records, 00 otherwise
496
497 * 3f00/7f4d/8f0d : Programmable Binary EFs
498
499 * 3f00/7f4d/8f0e : Programmable Record EFs
500
501 """
502
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200503 _files = { } # type: Dict[str, Tuple[str, int, bool]]
504 _ki_file = None # type: Optional[str]
505
Sylvain Munaut76504e02010-12-07 00:24:32 +0100506 @classmethod
507 def autodetect(kls, scc):
508 try:
509 for p, l, t in kls._files.values():
510 if not t:
511 continue
512 if scc.record_size(['3f00', '7f4d', p]) != l:
513 return None
514 except:
515 return None
516
517 return kls(scc)
518
519 def _get_count(self):
520 """
521 Selects the file and returns the total number of entries
522 and entry size
523 """
524 f = self._files['name']
525
Harald Weltec0499c82021-01-21 16:06:50 +0100526 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100527 rec_len = int(r[-1][28:30], 16)
528 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200529 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100530
531 if (rec_cnt < 1) or (rec_len != f[1]):
532 raise RuntimeError('Bad card type')
533
534 return rec_cnt
535
536 def program(self, p):
537 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100538 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100539
540 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400541 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100542
543 # Operator name ( 3f00/7f4d/8f0c )
544 self._scc.update_record(self._files['name'][0], 2,
545 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
546 )
547
548 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
549 v = ''
550
551 # inline Ki
552 if self._ki_file is None:
553 v += p['ki']
554
555 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400556 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100557
558 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400559 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100560
561 # Ki
562 if self._ki_file:
563 v += self._ki_file + '10' + p['ki']
564
565 # PLMN_Sel
566 v+= '6f30' + '18' + rpad(hplmn, 36)
567
Alexander Chemeris21885242013-07-02 16:56:55 +0400568 # ACC
569 # This doesn't work with "fake" SuperSIM cards,
570 # but will hopefully work with real SuperSIMs.
571 if p.get('acc') is not None:
572 v+= '6f78' + '02' + lpad(p['acc'], 4)
573
Sylvain Munaut76504e02010-12-07 00:24:32 +0100574 self._scc.update_record(self._files['b_ef'][0], 1,
575 rpad(v, self._files['b_ef'][1]*2)
576 )
577
578 # SMSP ( 3f00/7f4d/8f0e )
579 # FIXME
580
581 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100582 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100583 tl = int(r[-1][4:8], 16)
584
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400585 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100586 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
587
588 def erase(self):
589 # Dummy
590 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200591 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100592 ofs = 1
593 fv = v[1] * 'ff'
594 if k == 'name':
595 ofs = 2
596 fv = fv[0:-4] + '0000'
597 df[v[0]] = (fv, ofs)
598
599 # Write
600 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200601 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100602 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
603
604
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200605class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100606
607 name = 'supersim'
608
609 _files = {
610 'name' : ('8f0c', 18, True),
611 'b_ef' : ('8f0d', 74, True),
612 'r_ef' : ('8f0e', 50, True),
613 }
614
615 _ki_file = None
616
617
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200618class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100619
620 name = 'magicsim'
621
622 _files = {
623 'name' : ('8f0c', 18, True),
624 'b_ef' : ('8f0d', 130, True),
625 'r_ef' : ('8f0e', 102, False),
626 }
627
628 _ki_file = '6f1b'
629
630
631class FakeMagicSim(Card):
632 """
633 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200634 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100635 1 to N.
636 """
637
638 name = 'fakemagicsim'
639
640 @classmethod
641 def autodetect(kls, scc):
642 try:
643 if scc.record_size(['3f00', '000c']) != 0x5a:
644 return None
645 except:
646 return None
647
648 return kls(scc)
649
650 def _get_infos(self):
651 """
652 Selects the file and returns the total number of entries
653 and entry size
654 """
655
Harald Weltec0499c82021-01-21 16:06:50 +0100656 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100657 rec_len = int(r[-1][28:30], 16)
658 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200659 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100660
661 if (rec_cnt < 1) or (rec_len != 0x5a):
662 raise RuntimeError('Bad card type')
663
664 return rec_cnt, rec_len
665
666 def program(self, p):
667 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100668 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100669 tl = int(r[-1][4:8], 16)
670
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400671 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100672 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
673
674 # Get total number of entries and entry size
675 rec_cnt, rec_len = self._get_infos()
676
677 # Set first entry
678 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200679 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100680 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200681 enc_iccid(p['iccid']) + # 10b ICCID
682 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
683 p['ki'] + # 16b Ki
684 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100685 )
686 self._scc.update_record('000c', 1, entry)
687
688 def erase(self):
689 # Get total number of entries and entry size
690 rec_cnt, rec_len = self._get_infos()
691
692 # Erase all entries
693 entry = 'ff' * rec_len
694 for i in range(0, rec_cnt):
695 self._scc.update_record('000c', 1+i, entry)
696
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200697
Harald Welte3156d902011-03-22 21:48:19 +0100698class GrcardSim(Card):
699 """
700 Greencard (grcard.cn) HZCOS GSM SIM
701 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
702 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
703 """
704
705 name = 'grcardsim'
706
707 @classmethod
708 def autodetect(kls, scc):
709 return None
710
711 def program(self, p):
712 # We don't really know yet what ADM PIN 4 is about
713 #self._scc.verify_chv(4, h2b("4444444444444444"))
714
715 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100716 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200717 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100718 else:
719 pin = h2b("4444444444444444")
720 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100721
722 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100723 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400724 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100725
726 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100727 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400728 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100729
730 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400731 if p.get('acc') is not None:
732 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100733
734 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200735 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100736 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200737 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100738
739 # Set the Ki using proprietary command
740 pdu = '80d4020010' + p['ki']
741 data, sw = self._scc._tp.send_apdu(pdu)
742
743 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100744 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100745 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400746 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100747 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
748
749 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100750 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100751 size = int(r[-1][4:8], 16)
752 # FIXME
753
754 # FIXME: EF.MSISDN
755
Sylvain Munaut76504e02010-12-07 00:24:32 +0100756
Harald Weltee10394b2011-12-07 12:34:14 +0100757class SysmoSIMgr1(GrcardSim):
758 """
759 sysmocom sysmoSIM-GR1
760 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
761 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
762 """
763 name = 'sysmosim-gr1'
764
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200765 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200766 def autodetect(kls, scc):
767 try:
768 # Look for ATR
769 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
770 return kls(scc)
771 except:
772 return None
773 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200774
Harald Welteca673942020-06-03 15:19:40 +0200775class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100776 """
777 sysmocom sysmoUSIM-GR1
778 """
779 name = 'sysmoUSIM-GR1'
780
781 @classmethod
782 def autodetect(kls, scc):
783 # TODO: Access the ATR
784 return None
785
786 def program(self, p):
787 # TODO: check if verify_chv could be used or what it needs
788 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
789 # Unlock the card..
790 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
791
792 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100793 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400794 p['opc'] + # 32b OPC
795 enc_iccid(p['iccid']) + # 10b ICCID
796 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100797 )
798 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
799
Sylvain Munaut053c8952013-07-02 15:12:32 +0200800
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100801class SysmoSIMgr2(Card):
802 """
803 sysmocom sysmoSIM-GR2
804 """
805
806 name = 'sysmoSIM-GR2'
807
808 @classmethod
809 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900810 try:
811 # Look for ATR
812 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
813 return kls(scc)
814 except:
815 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100816 return None
817
818 def program(self, p):
819
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200820 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100821 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200822
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100823 # authenticate as SUPER ADM using default key
824 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
825
826 # set ADM pin using proprietary command
827 # INS: D4
828 # P1: 3A for PIN, 3B for PUK
829 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
830 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100831 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200832 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100833 else:
834 pin = h2b("4444444444444444")
835
836 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100837 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200838
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100839 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100840
841 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100842
843 # write EF.ICCID
844 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
845
846 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100847 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200848
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100849 # write EF.IMSI
850 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
851
852 # write EF.ACC
853 if p.get('acc') is not None:
854 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
855
856 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100857 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100858 size = int(r[-1][4:8], 16)
859 hplmn = enc_plmn(p['mcc'], p['mnc'])
860 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
861
862 # set COMP128 version 0 in proprietary file
863 data, sw = self._scc.update_binary('0001', '001000')
864
865 # set Ki in proprietary file
866 data, sw = self._scc.update_binary('0001', p['ki'], 3)
867
868 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100869 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200870
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100871 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200872 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200873 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100874
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100875
Harald Welteca673942020-06-03 15:19:40 +0200876class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100877 """
878 sysmocom sysmoUSIM-SJS1
879 """
880
881 name = 'sysmoUSIM-SJS1'
882
883 def __init__(self, ssc):
884 super(SysmoUSIMSJS1, self).__init__(ssc)
885 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100886 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100887
888 @classmethod
889 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900890 try:
891 # Look for ATR
892 if scc.get_atr() == toBytes("3B 9F 96 80 1F C7 80 31 A0 73 BE 21 13 67 43 20 07 18 00 00 01 A5"):
893 return kls(scc)
894 except:
895 return None
Jan Balke3e840672015-01-26 15:36:27 +0100896 return None
897
Harald Weltea6704252021-01-08 20:19:11 +0100898 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100899 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100900 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100901 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100902 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100903 return sw
904
905 def program(self, p):
906 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100907
908 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100909 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100910
Philipp Maiere9604882017-03-21 17:24:31 +0100911 # write EF.ICCID
912 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
913
Jan Balke3e840672015-01-26 15:36:27 +0100914 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100915 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100916
Jan Balke3e840672015-01-26 15:36:27 +0100917 # set Ki in proprietary file
918 data, sw = self._scc.update_binary('00FF', p['ki'])
919
Philipp Maier1be35bf2018-07-13 11:29:03 +0200920 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200921 if 'opc' in p:
922 content = "01" + p['opc']
923 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100924
Supreeth Herle7947d922019-06-08 07:50:53 +0200925 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100926 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200927 self.update_spn(p['name'], True, True)
Supreeth Herle7947d922019-06-08 07:50:53 +0200928
Supreeth Herlec8796a32019-12-23 12:23:42 +0100929 if p.get('acc') is not None:
930 self.update_acc(p['acc'])
931
Jan Balke3e840672015-01-26 15:36:27 +0100932 # write EF.IMSI
933 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
934
Philipp Maier2d15ea02019-03-20 12:40:36 +0100935 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200936 if p.get('mcc') and p.get('mnc'):
937 sw = self.update_plmnsel(p['mcc'], p['mnc'])
938 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100939 print("Programming PLMNsel failed with code %s"%sw)
940
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200941 # EF.PLMNwAcT
942 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100943 sw = self.update_plmn_act(p['mcc'], p['mnc'])
944 if sw != '9000':
945 print("Programming PLMNwAcT failed with code %s"%sw)
946
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200947 # EF.OPLMNwAcT
948 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100949 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
950 if sw != '9000':
951 print("Programming OPLMNwAcT failed with code %s"%sw)
952
Supreeth Herlef442fb42020-01-21 12:47:32 +0100953 # EF.HPLMNwAcT
954 if p.get('mcc') and p.get('mnc'):
955 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
956 if sw != '9000':
957 print("Programming HPLMNwAcT failed with code %s"%sw)
958
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200959 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100960 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
961 if p.get('mcc') and p.get('mnc'):
962 mnc = p['mnc']
963 else:
964 mnc = None
965 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +0100966 if sw != '9000':
967 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100968
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200969 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200970 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100971 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200972 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100973
Supreeth Herle5a541012019-12-22 08:59:16 +0100974 # EF.MSISDN
975 # TODO: Alpha Identifier (currently 'ff'O * 20)
976 # TODO: Capability/Configuration1 Record Identifier
977 # TODO: Extension1 Record Identifier
978 if p.get('msisdn') is not None:
979 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +0200980 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +0100981
Harald Weltec0499c82021-01-21 16:06:50 +0100982 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100983 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
984
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900985
herlesupreeth4a3580b2020-09-29 10:11:36 +0200986class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900987 """
988 FairwavesSIM
989
990 The SIM card is operating according to the standard.
991 For Ki/OP/OPC programming the following files are additionally open for writing:
992 3F00/7F20/FF01 – OP/OPC:
993 byte 1 = 0x01, bytes 2-17: OPC;
994 byte 1 = 0x00, bytes 2-17: OP;
995 3F00/7F20/FF02: Ki
996 """
997
Philipp Maier5a876312019-11-11 11:01:46 +0100998 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900999 # Propriatary files
1000 _EF_num = {
1001 'Ki': 'FF02',
1002 'OP/OPC': 'FF01',
1003 }
1004 _EF = {
1005 'Ki': DF['GSM']+[_EF_num['Ki']],
1006 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
1007 }
1008
1009 def __init__(self, ssc):
1010 super(FairwavesSIM, self).__init__(ssc)
1011 self._adm_chv_num = 0x11
1012 self._adm2_chv_num = 0x12
1013
1014
1015 @classmethod
1016 def autodetect(kls, scc):
1017 try:
1018 # Look for ATR
1019 if scc.get_atr() == toBytes("3B 9F 96 80 1F C7 80 31 A0 73 BE 21 13 67 44 22 06 10 00 00 01 A9"):
1020 return kls(scc)
1021 except:
1022 return None
1023 return None
1024
1025
1026 def verify_adm2(self, key):
1027 '''
1028 Authenticate with ADM2 key.
1029
1030 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1031 is a key which has access to proprietary files (Ki and OP/OPC).
1032 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1033 need ADM2 key per se.
1034 '''
1035 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1036 return sw
1037
1038
1039 def read_ki(self):
1040 """
1041 Read Ki in proprietary file.
1042
1043 Requires ADM1 access level
1044 """
1045 return self._scc.read_binary(self._EF['Ki'])
1046
1047
1048 def update_ki(self, ki):
1049 """
1050 Set Ki in proprietary file.
1051
1052 Requires ADM1 access level
1053 """
1054 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1055 return sw
1056
1057
1058 def read_op_opc(self):
1059 """
1060 Read Ki in proprietary file.
1061
1062 Requires ADM1 access level
1063 """
1064 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1065 type = 'OP' if ef[0:2] == '00' else 'OPC'
1066 return ((type, ef[2:]), sw)
1067
1068
1069 def update_op(self, op):
1070 """
1071 Set OP in proprietary file.
1072
1073 Requires ADM1 access level
1074 """
1075 content = '00' + op
1076 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1077 return sw
1078
1079
1080 def update_opc(self, opc):
1081 """
1082 Set OPC in proprietary file.
1083
1084 Requires ADM1 access level
1085 """
1086 content = '01' + opc
1087 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1088 return sw
1089
1090
1091 def program(self, p):
1092 # authenticate as ADM1
1093 if not p['pin_adm']:
1094 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001095 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001096
1097 # TODO: Set operator name
1098 if p.get('smsp') is not None:
1099 sw = self.update_smsp(p['smsp'])
1100 if sw != '9000':
1101 print("Programming SMSP failed with code %s"%sw)
1102 # This SIM doesn't support changing ICCID
1103 if p.get('mcc') is not None and p.get('mnc') is not None:
1104 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1105 if sw != '9000':
1106 print("Programming MCC/MNC failed with code %s"%sw)
1107 if p.get('imsi') is not None:
1108 sw = self.update_imsi(p['imsi'])
1109 if sw != '9000':
1110 print("Programming IMSI failed with code %s"%sw)
1111 if p.get('ki') is not None:
1112 sw = self.update_ki(p['ki'])
1113 if sw != '9000':
1114 print("Programming Ki failed with code %s"%sw)
1115 if p.get('opc') is not None:
1116 sw = self.update_opc(p['opc'])
1117 if sw != '9000':
1118 print("Programming OPC failed with code %s"%sw)
1119 if p.get('acc') is not None:
1120 sw = self.update_acc(p['acc'])
1121 if sw != '9000':
1122 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001123
Todd Neal9eeadfc2018-04-25 15:36:29 -05001124class OpenCellsSim(Card):
1125 """
1126 OpenCellsSim
1127
1128 """
1129
Philipp Maier5a876312019-11-11 11:01:46 +01001130 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001131
1132 def __init__(self, ssc):
1133 super(OpenCellsSim, self).__init__(ssc)
1134 self._adm_chv_num = 0x0A
1135
1136
1137 @classmethod
1138 def autodetect(kls, scc):
1139 try:
1140 # Look for ATR
1141 if scc.get_atr() == toBytes("3B 9F 95 80 1F C3 80 31 E0 73 FE 21 13 57 86 81 02 86 98 44 18 A8"):
1142 return kls(scc)
1143 except:
1144 return None
1145 return None
1146
1147
1148 def program(self, p):
1149 if not p['pin_adm']:
1150 raise ValueError("Please provide a PIN-ADM as there is no default one")
1151 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1152
1153 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001154 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001155
1156 # write EF.ICCID
1157 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1158
Harald Weltec0499c82021-01-21 16:06:50 +01001159 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001160
1161 # set Ki in proprietary file
1162 data, sw = self._scc.update_binary('FF02', p['ki'])
1163
1164 # set OPC in proprietary file
1165 data, sw = self._scc.update_binary('FF01', p['opc'])
1166
1167 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001168 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001169
1170 # write EF.IMSI
1171 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1172
herlesupreeth4a3580b2020-09-29 10:11:36 +02001173class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001174 """
1175 WavemobileSim
1176
1177 """
1178
1179 name = 'Wavemobile-SIM'
1180
1181 def __init__(self, ssc):
1182 super(WavemobileSim, self).__init__(ssc)
1183 self._adm_chv_num = 0x0A
1184 self._scc.cla_byte = "00"
1185 self._scc.sel_ctrl = "0004" #request an FCP
1186
1187 @classmethod
1188 def autodetect(kls, scc):
1189 try:
1190 # Look for ATR
1191 if scc.get_atr() == toBytes("3B 9F 95 80 1F C7 80 31 E0 73 F6 21 13 67 4D 45 16 00 43 01 00 8F"):
1192 return kls(scc)
1193 except:
1194 return None
1195 return None
1196
1197 def program(self, p):
1198 if not p['pin_adm']:
1199 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001200 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001201
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001202 # EF.ICCID
1203 # TODO: Add programming of the ICCID
1204 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001205 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1206
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001207 # KI (Presumably a propritary file)
1208 # TODO: Add programming of KI
1209 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001210 print("Warning: Programming of the KI is not implemented for this type of card.")
1211
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001212 # OPc (Presumably a propritary file)
1213 # TODO: Add programming of OPc
1214 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001215 print("Warning: Programming of the OPc is not implemented for this type of card.")
1216
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001217 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001218 if p.get('smsp'):
1219 sw = self.update_smsp(p['smsp'])
1220 if sw != '9000':
1221 print("Programming SMSP failed with code %s"%sw)
1222
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001223 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001224 if p.get('imsi'):
1225 sw = self.update_imsi(p['imsi'])
1226 if sw != '9000':
1227 print("Programming IMSI failed with code %s"%sw)
1228
1229 # EF.ACC
1230 if p.get('acc'):
1231 sw = self.update_acc(p['acc'])
1232 if sw != '9000':
1233 print("Programming ACC failed with code %s"%sw)
1234
1235 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001236 if p.get('mcc') and p.get('mnc'):
1237 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1238 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001239 print("Programming PLMNsel failed with code %s"%sw)
1240
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001241 # EF.PLMNwAcT
1242 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001243 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1244 if sw != '9000':
1245 print("Programming PLMNwAcT failed with code %s"%sw)
1246
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001247 # EF.OPLMNwAcT
1248 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001249 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1250 if sw != '9000':
1251 print("Programming OPLMNwAcT failed with code %s"%sw)
1252
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001253 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001254 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1255 if p.get('mcc') and p.get('mnc'):
1256 mnc = p['mnc']
1257 else:
1258 mnc = None
1259 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001260 if sw != '9000':
1261 print("Programming AD failed with code %s"%sw)
1262
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001263 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001264
Todd Neal9eeadfc2018-04-25 15:36:29 -05001265
herlesupreethb0c7d122020-12-23 09:25:46 +01001266class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001267 """
1268 sysmocom sysmoISIM-SJA2
1269 """
1270
1271 name = 'sysmoISIM-SJA2'
1272
1273 def __init__(self, ssc):
1274 super(SysmoISIMSJA2, self).__init__(ssc)
1275 self._scc.cla_byte = "00"
1276 self._scc.sel_ctrl = "0004" #request an FCP
1277
1278 @classmethod
1279 def autodetect(kls, scc):
1280 try:
1281 # Try card model #1
1282 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1283 if scc.get_atr() == toBytes(atr):
1284 return kls(scc)
1285
1286 # Try card model #2
1287 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1288 if scc.get_atr() == toBytes(atr):
1289 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001290
1291 # Try card model #3
1292 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1293 if scc.get_atr() == toBytes(atr):
1294 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001295 except:
1296 return None
1297 return None
1298
Harald Weltea6704252021-01-08 20:19:11 +01001299 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001300 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001301 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001302 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001303 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001304 return sw
1305
1306 def program(self, p):
1307 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001308
1309 # This type of card does not allow to reprogram the ICCID.
1310 # Reprogramming the ICCID would mess up the card os software
1311 # license management, so the ICCID must be kept at its factory
1312 # setting!
1313 if p.get('iccid'):
1314 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1315
1316 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001317 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001318
Robert Falkenberg54595362021-04-06 12:04:34 +02001319 # set Service Provider Name
1320 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +02001321 self.update_spn(p['name'], True, True)
Robert Falkenberg54595362021-04-06 12:04:34 +02001322
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001323 # write EF.IMSI
1324 if p.get('imsi'):
1325 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1326
1327 # EF.PLMNsel
1328 if p.get('mcc') and p.get('mnc'):
1329 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1330 if sw != '9000':
1331 print("Programming PLMNsel failed with code %s"%sw)
1332
1333 # EF.PLMNwAcT
1334 if p.get('mcc') and p.get('mnc'):
1335 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1336 if sw != '9000':
1337 print("Programming PLMNwAcT failed with code %s"%sw)
1338
1339 # EF.OPLMNwAcT
1340 if p.get('mcc') and p.get('mnc'):
1341 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1342 if sw != '9000':
1343 print("Programming OPLMNwAcT failed with code %s"%sw)
1344
Harald Welte32f0d412020-05-05 17:35:57 +02001345 # EF.HPLMNwAcT
1346 if p.get('mcc') and p.get('mnc'):
1347 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1348 if sw != '9000':
1349 print("Programming HPLMNwAcT failed with code %s"%sw)
1350
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001351 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001352 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1353 if p.get('mcc') and p.get('mnc'):
1354 mnc = p['mnc']
1355 else:
1356 mnc = None
1357 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001358 if sw != '9000':
1359 print("Programming AD failed with code %s"%sw)
1360
1361 # EF.SMSP
1362 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001363 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001364 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1365
Supreeth Herlec6019232020-03-26 10:00:45 +01001366 # EF.MSISDN
1367 # TODO: Alpha Identifier (currently 'ff'O * 20)
1368 # TODO: Capability/Configuration1 Record Identifier
1369 # TODO: Extension1 Record Identifier
1370 if p.get('msisdn') is not None:
1371 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001372 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001373
Harald Weltec0499c82021-01-21 16:06:50 +01001374 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001375 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1376
Supreeth Herlea97944b2020-03-26 10:03:25 +01001377 # EF.ACC
1378 if p.get('acc'):
1379 sw = self.update_acc(p['acc'])
1380 if sw != '9000':
1381 print("Programming ACC failed with code %s"%sw)
1382
Supreeth Herle80164052020-03-23 12:06:29 +01001383 # Populate AIDs
1384 self.read_aids()
1385
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001386 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1387 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001388 self._scc.select_path(['3f00'])
1389 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001390 if p.get('ki'):
1391 self._scc.update_binary('6f20', p['ki'], 1)
1392 if p.get('opc'):
1393 self._scc.update_binary('6f20', p['opc'], 17)
1394
1395 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001396 data, sw = self.select_adf_by_aid(adf="isim")
1397 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001398 if p.get('ki'):
1399 self._scc.update_binary('af20', p['ki'], 1)
1400 if p.get('opc'):
1401 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001402
Supreeth Herlecf727f22020-03-24 17:32:21 +01001403 # update EF.P-CSCF in ADF.ISIM
1404 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1405 if p.get('pcscf'):
1406 sw = self.update_pcscf(p['pcscf'])
1407 else:
1408 sw = self.update_pcscf("")
1409 if sw != '9000':
1410 print("Programming P-CSCF failed with code %s"%sw)
1411
1412
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001413 # update EF.DOMAIN in ADF.ISIM
1414 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1415 if p.get('ims_hdomain'):
1416 sw = self.update_domain(domain=p['ims_hdomain'])
1417 else:
1418 sw = self.update_domain()
1419
1420 if sw != '9000':
1421 print("Programming Home Network Domain Name failed with code %s"%sw)
1422
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001423 # update EF.IMPI in ADF.ISIM
1424 # TODO: Validate IMPI input
1425 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1426 if p.get('impi'):
1427 sw = self.update_impi(p['impi'])
1428 else:
1429 sw = self.update_impi()
1430 if sw != '9000':
1431 print("Programming IMPI failed with code %s"%sw)
1432
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001433 # update EF.IMPU in ADF.ISIM
1434 # TODO: Validate IMPU input
1435 # Support multiple IMPU if there is enough space
1436 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1437 if p.get('impu'):
1438 sw = self.update_impu(p['impu'])
1439 else:
1440 sw = self.update_impu()
1441 if sw != '9000':
1442 print("Programming IMPU failed with code %s"%sw)
1443
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001444 data, sw = self.select_adf_by_aid(adf="usim")
1445 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001446 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001447 if p.get('ki'):
1448 self._scc.update_binary('af20', p['ki'], 1)
1449 if p.get('opc'):
1450 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001451
Harald Welteca673942020-06-03 15:19:40 +02001452 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001453 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001454 if p.get('mcc') and p.get('mnc'):
1455 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1456 if sw != '9000':
1457 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001458
1459 # update EF.ePDGId in ADF.USIM
1460 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1461 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001462 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001463 else:
1464 sw = self.update_epdgid("")
1465 if sw != '9000':
1466 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001467
Supreeth Herlef964df42020-03-24 13:15:37 +01001468 # update EF.ePDGSelection in ADF.USIM
1469 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1470 if p.get('epdgSelection'):
1471 epdg_plmn = p['epdgSelection']
1472 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1473 else:
1474 sw = self.update_ePDGSelection("", "")
1475 if sw != '9000':
1476 print("Programming ePDGSelection failed with code %s"%sw)
1477
1478
Supreeth Herleacc222f2020-03-24 13:26:53 +01001479 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1480 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001481 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001482 if self.file_exists(EF_USIM_ADF_map['UST']):
1483 if p.get('epdgSelection') and p.get('epdgid'):
1484 sw = self.update_ust(106, 1)
1485 if sw != '9000':
1486 print("Programming UST failed with code %s"%sw)
1487 sw = self.update_ust(107, 1)
1488 if sw != '9000':
1489 print("Programming UST failed with code %s"%sw)
1490
Supreeth Herle44e04622020-03-25 10:34:28 +01001491 sw = self.update_ust(95, 0)
1492 if sw != '9000':
1493 print("Programming UST failed with code %s"%sw)
1494 sw = self.update_ust(99, 0)
1495 if sw != '9000':
1496 print("Programming UST failed with code %s"%sw)
1497 sw = self.update_ust(115, 0)
1498 if sw != '9000':
1499 print("Programming UST failed with code %s"%sw)
1500
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001501 return
1502
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001503
Todd Neal9eeadfc2018-04-25 15:36:29 -05001504# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001505_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001506 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001507 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001508
1509def card_autodetect(scc):
1510 for kls in _cards_classes:
1511 card = kls.autodetect(scc)
1512 if card is not None:
1513 card.reset()
1514 return card
1515 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001516
1517def card_detect(ctype, scc):
1518 # Detect type if needed
1519 card = None
1520 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1521
1522 if ctype in ("auto", "auto_once"):
1523 for kls in _cards_classes:
1524 card = kls.autodetect(scc)
1525 if card:
1526 print("Autodetected card type: %s" % card.name)
1527 card.reset()
1528 break
1529
1530 if card is None:
1531 print("Autodetection failed")
1532 return None
1533
1534 if ctype == "auto_once":
1535 ctype = card.name
1536
1537 elif ctype in ctypes:
1538 card = ctypes[ctype](scc)
1539
1540 else:
1541 raise ValueError("Unknown card type: %s" % ctype)
1542
1543 return card