blob: 3b5365406fe25595b87b57942ea8c3df7aea30a0 [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
26
Robert Falkenbergd0505bd2021-02-24 14:06:18 +010027from pySim.ts_51_011 import EF, DF, EF_AD
Harald Welteca673942020-06-03 15:19:40 +020028from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010029from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030030from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090031from smartcard.util import toBytes
Supreeth Herle79f43dd2020-03-25 11:43:19 +010032from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010033
34class Card(object):
35
36 def __init__(self, scc):
37 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030038 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010039 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010040
Sylvain Munaut76504e02010-12-07 00:24:32 +010041 def reset(self):
42 self._scc.reset_card()
43
Philipp Maierd58c6322020-05-12 16:47:45 +020044 def erase(self):
45 print("warning: erasing is not supported for specified card type!")
46 return
47
Harald Welteca673942020-06-03 15:19:40 +020048 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010049 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020050 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020051 if res[1] != '9000':
52 return False
Harald Welteca673942020-06-03 15:19:40 +020053 return True
54
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030055 def verify_adm(self, key):
56 '''
57 Authenticate with ADM key
58 '''
59 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
60 return sw
61
62 def read_iccid(self):
63 (res, sw) = self._scc.read_binary(EF['ICCID'])
64 if sw == '9000':
65 return (dec_iccid(res), sw)
66 else:
67 return (None, sw)
68
69 def read_imsi(self):
70 (res, sw) = self._scc.read_binary(EF['IMSI'])
71 if sw == '9000':
72 return (dec_imsi(res), sw)
73 else:
74 return (None, sw)
75
76 def update_imsi(self, imsi):
77 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
78 return sw
79
80 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +020081 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030082 return sw
83
Supreeth Herlea850a472020-03-19 12:44:11 +010084 def read_hplmn_act(self):
85 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
86 if sw == '9000':
87 return (format_xplmn_w_act(res), sw)
88 else:
89 return (None, sw)
90
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030091 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
92 """
93 Update Home PLMN with access technology bit-field
94
95 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
96 in ETSI TS 151 011 for the details of the access_tech field coding.
97 Some common values:
98 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +020099 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300100 """
101 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100102 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700103 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300104 hplmn = enc_plmn(mcc, mnc)
105 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700106 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300107 return sw
108
Supreeth Herle1757b262020-03-19 12:43:11 +0100109 def read_oplmn_act(self):
110 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
111 if sw == '9000':
112 return (format_xplmn_w_act(res), sw)
113 else:
114 return (None, sw)
115
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200116 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
117 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200118 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200119 """
120 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200121 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700122 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200123 hplmn = enc_plmn(mcc, mnc)
124 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700125 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200126 return sw
127
Supreeth Herle14084402020-03-19 12:42:10 +0100128 def read_plmn_act(self):
129 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
130 if sw == '9000':
131 return (format_xplmn_w_act(res), sw)
132 else:
133 return (None, sw)
134
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200135 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
136 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200137 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200138 """
139 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200140 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700141 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200142 hplmn = enc_plmn(mcc, mnc)
143 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700144 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200145 return sw
146
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200147 def update_plmnsel(self, mcc, mnc):
148 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700149 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200150 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200151 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
152 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200153
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300154 def update_smsp(self, smsp):
155 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
156 return sw
157
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100158 def update_ad(self, mnc=None, opmode=None, ofm=None):
159 """
160 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100161
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100162 See Sec. "4.2.18 EF_AD (Administrative Data)"
163 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200164
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100165 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200166
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100167 Parameters:
168 mnc (str): MNC of IMSI
169 opmode (Hex-str, 1 Byte): MS Operation Mode
170 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
171
172 Returns:
173 str: Return code of write operation
174 """
175
176 ad = EF_AD()
177
178 # read from card
179 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200180 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100181
182 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200183 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100184 mnclen = len(str(mnc))
185 if mnclen == 1:
186 mnclen = 2
187 if mnclen > 3:
188 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200189 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100190 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200191 opmode_num = int(opmode, 16)
192 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
193 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100194 else:
195 raise RuntimeError('invalid opmode "{}"'.format(opmode))
196 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200197 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100198
199 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200200 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100201 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100202 return sw
203
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300204 def read_spn(self):
205 (spn, sw) = self._scc.read_binary(EF['SPN'])
206 if sw == '9000':
207 return (dec_spn(spn), sw)
208 else:
209 return (None, sw)
210
211 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
212 content = enc_spn(name, hplmn_disp, oplmn_disp)
213 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
214 return sw
215
Supreeth Herled21349a2020-04-01 08:37:47 +0200216 def read_binary(self, ef, length=None, offset=0):
217 ef_path = ef in EF and EF[ef] or ef
218 return self._scc.read_binary(ef_path, length, offset)
219
Supreeth Herlead10d662020-04-01 08:43:08 +0200220 def read_record(self, ef, rec_no):
221 ef_path = ef in EF and EF[ef] or ef
222 return self._scc.read_record(ef_path, rec_no)
223
Supreeth Herle98a69272020-03-18 12:14:48 +0100224 def read_gid1(self):
225 (res, sw) = self._scc.read_binary(EF['GID1'])
226 if sw == '9000':
227 return (res, sw)
228 else:
229 return (None, sw)
230
Supreeth Herle6d66af62020-03-19 12:49:16 +0100231 def read_msisdn(self):
232 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
233 if sw == '9000':
234 return (dec_msisdn(res), sw)
235 else:
236 return (None, sw)
237
Supreeth Herlee4e98312020-03-18 11:33:14 +0100238 # Fetch all the AIDs present on UICC
239 def read_aids(self):
Philipp Maier1e896f32021-03-10 17:02:53 +0100240 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100241 try:
242 # Find out how many records the EF.DIR has
243 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100244 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100245 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100246 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100247 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
248 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
249 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
250 except Exception as e:
251 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100252 self._aids = []
253 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100254
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100255 # Select ADF.U/ISIM in the Card using its full AID
256 def select_adf_by_aid(self, adf="usim"):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100257 # Find full AID by partial AID:
258 if is_hex(adf):
259 for aid in self._aids:
260 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
261 return self._scc.select_adf(aid)
262 # Find full AID by application name:
263 elif adf in ["usim", "isim"]:
264 # First (known) halves of the U/ISIM AID
265 aid_map = {}
266 aid_map["usim"] = "a0000000871002"
267 aid_map["isim"] = "a0000000871004"
268 for aid in self._aids:
269 if aid_map[adf] in aid:
270 return self._scc.select_adf(aid)
271 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100272
Philipp Maier5c2cc662020-05-12 16:27:12 +0200273 # Erase the contents of a file
274 def erase_binary(self, ef):
275 len = self._scc.binary_size(ef)
276 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
277
278 # Erase the contents of a single record
279 def erase_record(self, ef, rec_no):
280 len = self._scc.record_size(ef)
281 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
282
Harald Welteca673942020-06-03 15:19:40 +0200283class UsimCard(Card):
284 def __init__(self, ssc):
285 super(UsimCard, self).__init__(ssc)
286
287 def read_ehplmn(self):
288 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
289 if sw == '9000':
290 return (format_xplmn(res), sw)
291 else:
292 return (None, sw)
293
294 def update_ehplmn(self, mcc, mnc):
295 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
296 size = len(data[0]) // 2
297 ehplmn = enc_plmn(mcc, mnc)
298 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
299 return sw
300
herlesupreethf8232db2020-09-29 10:03:06 +0200301 def read_epdgid(self):
302 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
303 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100304 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200305 else:
306 return (None, sw)
307
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200308 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100309 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
310 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100311 addr_type = get_addr_type(epdgid)
312 if addr_type == None:
313 raise ValueError("Unknown ePDG Id address type or invalid address provided")
314 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100315 else:
316 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200317 data, sw = self._scc.update_binary(
318 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
319 return sw
Harald Welteca673942020-06-03 15:19:40 +0200320
Supreeth Herle99d55552020-03-24 13:03:43 +0100321 def read_ePDGSelection(self):
322 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
323 if sw == '9000':
324 return (format_ePDGSelection(res), sw)
325 else:
326 return (None, sw)
327
Supreeth Herlef964df42020-03-24 13:15:37 +0100328 def update_ePDGSelection(self, mcc, mnc):
329 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
330 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
331 # Reset contents
332 # 80 - Tag value
333 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
334 elif sw == '9000':
335 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
336 return sw
337
herlesupreeth4a3580b2020-09-29 10:11:36 +0200338 def read_ust(self):
339 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
340 if sw == '9000':
341 # Print those which are available
342 return ([res, dec_st(res, table="usim")], sw)
343 else:
344 return ([None, None], sw)
345
Supreeth Herleacc222f2020-03-24 13:26:53 +0100346 def update_ust(self, service, bit=1):
347 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
348 if sw == '9000':
349 content = enc_st(res, service, bit)
350 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
351 return sw
352
herlesupreethecbada92020-12-23 09:24:29 +0100353class IsimCard(Card):
354 def __init__(self, ssc):
355 super(IsimCard, self).__init__(ssc)
356
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100357 def read_pcscf(self):
358 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
359 pcscf_recs = ""
360 for i in range(0, rec_cnt):
361 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
362 if sw == '9000':
363 content = dec_addr_tlv(res)
364 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
365 else:
366 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
367 return pcscf_recs
368
Supreeth Herlecf727f22020-03-24 17:32:21 +0100369 def update_pcscf(self, pcscf):
370 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100371 addr_type = get_addr_type(pcscf)
372 if addr_type == None:
373 raise ValueError("Unknown PCSCF address type or invalid address provided")
374 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100375 else:
376 # Just the tag value
377 content = '80'
378 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100379 pcscf_tlv = rpad(content, rec_size_bytes*2)
380 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100381 return sw
382
Supreeth Herle05b28072020-03-25 10:23:48 +0100383 def read_domain(self):
384 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
385 if sw == '9000':
386 # Skip the inital tag value ('80') byte and get length of contents
387 length = int(res[2:4], 16)
388 content = h2s(res[4:4+(length*2)])
389 return (content, sw)
390 else:
391 return (None, sw)
392
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100393 def update_domain(self, domain=None, mcc=None, mnc=None):
394 hex_str = ""
395 if domain:
396 hex_str = s2h(domain)
397 elif mcc and mnc:
398 # MCC and MNC always has 3 digits in domain form
399 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
400 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
401
402 # Build TLV
403 tlv = TLV(['80'])
404 content = tlv.build({'80': hex_str})
405
406 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
407 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
408 return sw
409
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100410 def read_impi(self):
411 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
412 if sw == '9000':
413 # Skip the inital tag value ('80') byte and get length of contents
414 length = int(res[2:4], 16)
415 content = h2s(res[4:4+(length*2)])
416 return (content, sw)
417 else:
418 return (None, sw)
419
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100420 def update_impi(self, impi=None):
421 hex_str = ""
422 if impi:
423 hex_str = s2h(impi)
424 # Build TLV
425 tlv = TLV(['80'])
426 content = tlv.build({'80': hex_str})
427
428 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
429 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
430 return sw
431
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100432 def read_impu(self):
433 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
434 impu_recs = ""
435 for i in range(0, rec_cnt):
436 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
437 if sw == '9000':
438 # Skip the inital tag value ('80') byte and get length of contents
439 length = int(res[2:4], 16)
440 content = h2s(res[4:4+(length*2)])
441 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
442 else:
443 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
444 return impu_recs
445
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100446 def update_impu(self, impu=None):
447 hex_str = ""
448 if impu:
449 hex_str = s2h(impu)
450 # Build TLV
451 tlv = TLV(['80'])
452 content = tlv.build({'80': hex_str})
453
454 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
455 impu_tlv = rpad(content, rec_size_bytes*2)
456 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
457 return sw
458
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200459 def read_iari(self):
460 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
461 uiari_recs = ""
462 for i in range(0, rec_cnt):
463 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
464 if sw == '9000':
465 # Skip the inital tag value ('80') byte and get length of contents
466 length = int(res[2:4], 16)
467 content = h2s(res[4:4+(length*2)])
468 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
469 else:
470 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
471 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100472
473class _MagicSimBase(Card):
474 """
475 Theses cards uses several record based EFs to store the provider infos,
476 each possible provider uses a specific record number in each EF. The
477 indexes used are ( where N is the number of providers supported ) :
478 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200479 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100480
481 * 3f00/7f4d/8f0c : Operator Name
482
483 bytes 0-15 : provider name, padded with 0xff
484 byte 16 : length of the provider name
485 byte 17 : 01 for valid records, 00 otherwise
486
487 * 3f00/7f4d/8f0d : Programmable Binary EFs
488
489 * 3f00/7f4d/8f0e : Programmable Record EFs
490
491 """
492
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200493 _files = { } # type: Dict[str, Tuple[str, int, bool]]
494 _ki_file = None # type: Optional[str]
495
Sylvain Munaut76504e02010-12-07 00:24:32 +0100496 @classmethod
497 def autodetect(kls, scc):
498 try:
499 for p, l, t in kls._files.values():
500 if not t:
501 continue
502 if scc.record_size(['3f00', '7f4d', p]) != l:
503 return None
504 except:
505 return None
506
507 return kls(scc)
508
509 def _get_count(self):
510 """
511 Selects the file and returns the total number of entries
512 and entry size
513 """
514 f = self._files['name']
515
Harald Weltec0499c82021-01-21 16:06:50 +0100516 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100517 rec_len = int(r[-1][28:30], 16)
518 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200519 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100520
521 if (rec_cnt < 1) or (rec_len != f[1]):
522 raise RuntimeError('Bad card type')
523
524 return rec_cnt
525
526 def program(self, p):
527 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100528 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100529
530 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400531 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100532
533 # Operator name ( 3f00/7f4d/8f0c )
534 self._scc.update_record(self._files['name'][0], 2,
535 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
536 )
537
538 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
539 v = ''
540
541 # inline Ki
542 if self._ki_file is None:
543 v += p['ki']
544
545 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400546 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100547
548 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400549 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100550
551 # Ki
552 if self._ki_file:
553 v += self._ki_file + '10' + p['ki']
554
555 # PLMN_Sel
556 v+= '6f30' + '18' + rpad(hplmn, 36)
557
Alexander Chemeris21885242013-07-02 16:56:55 +0400558 # ACC
559 # This doesn't work with "fake" SuperSIM cards,
560 # but will hopefully work with real SuperSIMs.
561 if p.get('acc') is not None:
562 v+= '6f78' + '02' + lpad(p['acc'], 4)
563
Sylvain Munaut76504e02010-12-07 00:24:32 +0100564 self._scc.update_record(self._files['b_ef'][0], 1,
565 rpad(v, self._files['b_ef'][1]*2)
566 )
567
568 # SMSP ( 3f00/7f4d/8f0e )
569 # FIXME
570
571 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100572 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100573 tl = int(r[-1][4:8], 16)
574
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400575 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100576 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
577
578 def erase(self):
579 # Dummy
580 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200581 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100582 ofs = 1
583 fv = v[1] * 'ff'
584 if k == 'name':
585 ofs = 2
586 fv = fv[0:-4] + '0000'
587 df[v[0]] = (fv, ofs)
588
589 # Write
590 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200591 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100592 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
593
594
595class SuperSim(_MagicSimBase):
596
597 name = 'supersim'
598
599 _files = {
600 'name' : ('8f0c', 18, True),
601 'b_ef' : ('8f0d', 74, True),
602 'r_ef' : ('8f0e', 50, True),
603 }
604
605 _ki_file = None
606
607
608class MagicSim(_MagicSimBase):
609
610 name = 'magicsim'
611
612 _files = {
613 'name' : ('8f0c', 18, True),
614 'b_ef' : ('8f0d', 130, True),
615 'r_ef' : ('8f0e', 102, False),
616 }
617
618 _ki_file = '6f1b'
619
620
621class FakeMagicSim(Card):
622 """
623 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200624 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100625 1 to N.
626 """
627
628 name = 'fakemagicsim'
629
630 @classmethod
631 def autodetect(kls, scc):
632 try:
633 if scc.record_size(['3f00', '000c']) != 0x5a:
634 return None
635 except:
636 return None
637
638 return kls(scc)
639
640 def _get_infos(self):
641 """
642 Selects the file and returns the total number of entries
643 and entry size
644 """
645
Harald Weltec0499c82021-01-21 16:06:50 +0100646 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100647 rec_len = int(r[-1][28:30], 16)
648 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200649 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100650
651 if (rec_cnt < 1) or (rec_len != 0x5a):
652 raise RuntimeError('Bad card type')
653
654 return rec_cnt, rec_len
655
656 def program(self, p):
657 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100658 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100659 tl = int(r[-1][4:8], 16)
660
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400661 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100662 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
663
664 # Get total number of entries and entry size
665 rec_cnt, rec_len = self._get_infos()
666
667 # Set first entry
668 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200669 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100670 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200671 enc_iccid(p['iccid']) + # 10b ICCID
672 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
673 p['ki'] + # 16b Ki
674 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100675 )
676 self._scc.update_record('000c', 1, entry)
677
678 def erase(self):
679 # Get total number of entries and entry size
680 rec_cnt, rec_len = self._get_infos()
681
682 # Erase all entries
683 entry = 'ff' * rec_len
684 for i in range(0, rec_cnt):
685 self._scc.update_record('000c', 1+i, entry)
686
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200687
Harald Welte3156d902011-03-22 21:48:19 +0100688class GrcardSim(Card):
689 """
690 Greencard (grcard.cn) HZCOS GSM SIM
691 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
692 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
693 """
694
695 name = 'grcardsim'
696
697 @classmethod
698 def autodetect(kls, scc):
699 return None
700
701 def program(self, p):
702 # We don't really know yet what ADM PIN 4 is about
703 #self._scc.verify_chv(4, h2b("4444444444444444"))
704
705 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100706 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200707 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100708 else:
709 pin = h2b("4444444444444444")
710 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100711
712 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100713 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400714 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100715
716 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100717 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400718 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100719
720 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400721 if p.get('acc') is not None:
722 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100723
724 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200725 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100726 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200727 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100728
729 # Set the Ki using proprietary command
730 pdu = '80d4020010' + p['ki']
731 data, sw = self._scc._tp.send_apdu(pdu)
732
733 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100734 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100735 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400736 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100737 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
738
739 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100740 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100741 size = int(r[-1][4:8], 16)
742 # FIXME
743
744 # FIXME: EF.MSISDN
745
Sylvain Munaut76504e02010-12-07 00:24:32 +0100746
Harald Weltee10394b2011-12-07 12:34:14 +0100747class SysmoSIMgr1(GrcardSim):
748 """
749 sysmocom sysmoSIM-GR1
750 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
751 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
752 """
753 name = 'sysmosim-gr1'
754
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200755 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200756 def autodetect(kls, scc):
757 try:
758 # Look for ATR
759 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
760 return kls(scc)
761 except:
762 return None
763 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200764
Harald Welteca673942020-06-03 15:19:40 +0200765class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100766 """
767 sysmocom sysmoUSIM-GR1
768 """
769 name = 'sysmoUSIM-GR1'
770
771 @classmethod
772 def autodetect(kls, scc):
773 # TODO: Access the ATR
774 return None
775
776 def program(self, p):
777 # TODO: check if verify_chv could be used or what it needs
778 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
779 # Unlock the card..
780 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
781
782 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100783 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400784 p['opc'] + # 32b OPC
785 enc_iccid(p['iccid']) + # 10b ICCID
786 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100787 )
788 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
789
Sylvain Munaut053c8952013-07-02 15:12:32 +0200790
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100791class SysmoSIMgr2(Card):
792 """
793 sysmocom sysmoSIM-GR2
794 """
795
796 name = 'sysmoSIM-GR2'
797
798 @classmethod
799 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900800 try:
801 # Look for ATR
802 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
803 return kls(scc)
804 except:
805 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100806 return None
807
808 def program(self, p):
809
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200810 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100811 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200812
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100813 # authenticate as SUPER ADM using default key
814 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
815
816 # set ADM pin using proprietary command
817 # INS: D4
818 # P1: 3A for PIN, 3B for PUK
819 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
820 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100821 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200822 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100823 else:
824 pin = h2b("4444444444444444")
825
826 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100827 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200828
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100829 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100830
831 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100832
833 # write EF.ICCID
834 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
835
836 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100837 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200838
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100839 # write EF.IMSI
840 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
841
842 # write EF.ACC
843 if p.get('acc') is not None:
844 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
845
846 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100847 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100848 size = int(r[-1][4:8], 16)
849 hplmn = enc_plmn(p['mcc'], p['mnc'])
850 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
851
852 # set COMP128 version 0 in proprietary file
853 data, sw = self._scc.update_binary('0001', '001000')
854
855 # set Ki in proprietary file
856 data, sw = self._scc.update_binary('0001', p['ki'], 3)
857
858 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100859 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200860
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100861 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200862 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200863 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100864
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100865
Harald Welteca673942020-06-03 15:19:40 +0200866class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100867 """
868 sysmocom sysmoUSIM-SJS1
869 """
870
871 name = 'sysmoUSIM-SJS1'
872
873 def __init__(self, ssc):
874 super(SysmoUSIMSJS1, self).__init__(ssc)
875 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100876 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100877
878 @classmethod
879 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900880 try:
881 # Look for ATR
882 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"):
883 return kls(scc)
884 except:
885 return None
Jan Balke3e840672015-01-26 15:36:27 +0100886 return None
887
Harald Weltea6704252021-01-08 20:19:11 +0100888 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100889 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100890 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100891 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100892 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100893 return sw
894
895 def program(self, p):
896 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100897
898 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100899 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100900
Philipp Maiere9604882017-03-21 17:24:31 +0100901 # write EF.ICCID
902 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
903
Jan Balke3e840672015-01-26 15:36:27 +0100904 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100905 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100906
Jan Balke3e840672015-01-26 15:36:27 +0100907 # set Ki in proprietary file
908 data, sw = self._scc.update_binary('00FF', p['ki'])
909
Philipp Maier1be35bf2018-07-13 11:29:03 +0200910 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200911 if 'opc' in p:
912 content = "01" + p['opc']
913 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100914
Supreeth Herle7947d922019-06-08 07:50:53 +0200915 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100916 if p.get('name') is not None:
917 content = enc_spn(p['name'], True, True)
918 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200919
Supreeth Herlec8796a32019-12-23 12:23:42 +0100920 if p.get('acc') is not None:
921 self.update_acc(p['acc'])
922
Jan Balke3e840672015-01-26 15:36:27 +0100923 # write EF.IMSI
924 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
925
Philipp Maier2d15ea02019-03-20 12:40:36 +0100926 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200927 if p.get('mcc') and p.get('mnc'):
928 sw = self.update_plmnsel(p['mcc'], p['mnc'])
929 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100930 print("Programming PLMNsel failed with code %s"%sw)
931
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200932 # EF.PLMNwAcT
933 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100934 sw = self.update_plmn_act(p['mcc'], p['mnc'])
935 if sw != '9000':
936 print("Programming PLMNwAcT failed with code %s"%sw)
937
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200938 # EF.OPLMNwAcT
939 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100940 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
941 if sw != '9000':
942 print("Programming OPLMNwAcT failed with code %s"%sw)
943
Supreeth Herlef442fb42020-01-21 12:47:32 +0100944 # EF.HPLMNwAcT
945 if p.get('mcc') and p.get('mnc'):
946 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
947 if sw != '9000':
948 print("Programming HPLMNwAcT failed with code %s"%sw)
949
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200950 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100951 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
952 if p.get('mcc') and p.get('mnc'):
953 mnc = p['mnc']
954 else:
955 mnc = None
956 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +0100957 if sw != '9000':
958 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100959
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200960 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200961 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100962 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200963 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100964
Supreeth Herle5a541012019-12-22 08:59:16 +0100965 # EF.MSISDN
966 # TODO: Alpha Identifier (currently 'ff'O * 20)
967 # TODO: Capability/Configuration1 Record Identifier
968 # TODO: Extension1 Record Identifier
969 if p.get('msisdn') is not None:
970 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +0200971 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +0100972
Harald Weltec0499c82021-01-21 16:06:50 +0100973 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100974 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
975
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900976
herlesupreeth4a3580b2020-09-29 10:11:36 +0200977class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900978 """
979 FairwavesSIM
980
981 The SIM card is operating according to the standard.
982 For Ki/OP/OPC programming the following files are additionally open for writing:
983 3F00/7F20/FF01 – OP/OPC:
984 byte 1 = 0x01, bytes 2-17: OPC;
985 byte 1 = 0x00, bytes 2-17: OP;
986 3F00/7F20/FF02: Ki
987 """
988
Philipp Maier5a876312019-11-11 11:01:46 +0100989 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900990 # Propriatary files
991 _EF_num = {
992 'Ki': 'FF02',
993 'OP/OPC': 'FF01',
994 }
995 _EF = {
996 'Ki': DF['GSM']+[_EF_num['Ki']],
997 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
998 }
999
1000 def __init__(self, ssc):
1001 super(FairwavesSIM, self).__init__(ssc)
1002 self._adm_chv_num = 0x11
1003 self._adm2_chv_num = 0x12
1004
1005
1006 @classmethod
1007 def autodetect(kls, scc):
1008 try:
1009 # Look for ATR
1010 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"):
1011 return kls(scc)
1012 except:
1013 return None
1014 return None
1015
1016
1017 def verify_adm2(self, key):
1018 '''
1019 Authenticate with ADM2 key.
1020
1021 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1022 is a key which has access to proprietary files (Ki and OP/OPC).
1023 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1024 need ADM2 key per se.
1025 '''
1026 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1027 return sw
1028
1029
1030 def read_ki(self):
1031 """
1032 Read Ki in proprietary file.
1033
1034 Requires ADM1 access level
1035 """
1036 return self._scc.read_binary(self._EF['Ki'])
1037
1038
1039 def update_ki(self, ki):
1040 """
1041 Set Ki in proprietary file.
1042
1043 Requires ADM1 access level
1044 """
1045 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1046 return sw
1047
1048
1049 def read_op_opc(self):
1050 """
1051 Read Ki in proprietary file.
1052
1053 Requires ADM1 access level
1054 """
1055 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1056 type = 'OP' if ef[0:2] == '00' else 'OPC'
1057 return ((type, ef[2:]), sw)
1058
1059
1060 def update_op(self, op):
1061 """
1062 Set OP in proprietary file.
1063
1064 Requires ADM1 access level
1065 """
1066 content = '00' + op
1067 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1068 return sw
1069
1070
1071 def update_opc(self, opc):
1072 """
1073 Set OPC in proprietary file.
1074
1075 Requires ADM1 access level
1076 """
1077 content = '01' + opc
1078 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1079 return sw
1080
1081
1082 def program(self, p):
1083 # authenticate as ADM1
1084 if not p['pin_adm']:
1085 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001086 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001087
1088 # TODO: Set operator name
1089 if p.get('smsp') is not None:
1090 sw = self.update_smsp(p['smsp'])
1091 if sw != '9000':
1092 print("Programming SMSP failed with code %s"%sw)
1093 # This SIM doesn't support changing ICCID
1094 if p.get('mcc') is not None and p.get('mnc') is not None:
1095 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1096 if sw != '9000':
1097 print("Programming MCC/MNC failed with code %s"%sw)
1098 if p.get('imsi') is not None:
1099 sw = self.update_imsi(p['imsi'])
1100 if sw != '9000':
1101 print("Programming IMSI failed with code %s"%sw)
1102 if p.get('ki') is not None:
1103 sw = self.update_ki(p['ki'])
1104 if sw != '9000':
1105 print("Programming Ki failed with code %s"%sw)
1106 if p.get('opc') is not None:
1107 sw = self.update_opc(p['opc'])
1108 if sw != '9000':
1109 print("Programming OPC failed with code %s"%sw)
1110 if p.get('acc') is not None:
1111 sw = self.update_acc(p['acc'])
1112 if sw != '9000':
1113 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001114
Todd Neal9eeadfc2018-04-25 15:36:29 -05001115class OpenCellsSim(Card):
1116 """
1117 OpenCellsSim
1118
1119 """
1120
Philipp Maier5a876312019-11-11 11:01:46 +01001121 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001122
1123 def __init__(self, ssc):
1124 super(OpenCellsSim, self).__init__(ssc)
1125 self._adm_chv_num = 0x0A
1126
1127
1128 @classmethod
1129 def autodetect(kls, scc):
1130 try:
1131 # Look for ATR
1132 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"):
1133 return kls(scc)
1134 except:
1135 return None
1136 return None
1137
1138
1139 def program(self, p):
1140 if not p['pin_adm']:
1141 raise ValueError("Please provide a PIN-ADM as there is no default one")
1142 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1143
1144 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001145 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001146
1147 # write EF.ICCID
1148 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1149
Harald Weltec0499c82021-01-21 16:06:50 +01001150 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001151
1152 # set Ki in proprietary file
1153 data, sw = self._scc.update_binary('FF02', p['ki'])
1154
1155 # set OPC in proprietary file
1156 data, sw = self._scc.update_binary('FF01', p['opc'])
1157
1158 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001159 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001160
1161 # write EF.IMSI
1162 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1163
herlesupreeth4a3580b2020-09-29 10:11:36 +02001164class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001165 """
1166 WavemobileSim
1167
1168 """
1169
1170 name = 'Wavemobile-SIM'
1171
1172 def __init__(self, ssc):
1173 super(WavemobileSim, self).__init__(ssc)
1174 self._adm_chv_num = 0x0A
1175 self._scc.cla_byte = "00"
1176 self._scc.sel_ctrl = "0004" #request an FCP
1177
1178 @classmethod
1179 def autodetect(kls, scc):
1180 try:
1181 # Look for ATR
1182 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"):
1183 return kls(scc)
1184 except:
1185 return None
1186 return None
1187
1188 def program(self, p):
1189 if not p['pin_adm']:
1190 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001191 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001192
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001193 # EF.ICCID
1194 # TODO: Add programming of the ICCID
1195 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001196 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1197
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001198 # KI (Presumably a propritary file)
1199 # TODO: Add programming of KI
1200 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001201 print("Warning: Programming of the KI is not implemented for this type of card.")
1202
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001203 # OPc (Presumably a propritary file)
1204 # TODO: Add programming of OPc
1205 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001206 print("Warning: Programming of the OPc is not implemented for this type of card.")
1207
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001208 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001209 if p.get('smsp'):
1210 sw = self.update_smsp(p['smsp'])
1211 if sw != '9000':
1212 print("Programming SMSP failed with code %s"%sw)
1213
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001214 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001215 if p.get('imsi'):
1216 sw = self.update_imsi(p['imsi'])
1217 if sw != '9000':
1218 print("Programming IMSI failed with code %s"%sw)
1219
1220 # EF.ACC
1221 if p.get('acc'):
1222 sw = self.update_acc(p['acc'])
1223 if sw != '9000':
1224 print("Programming ACC failed with code %s"%sw)
1225
1226 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001227 if p.get('mcc') and p.get('mnc'):
1228 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1229 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001230 print("Programming PLMNsel failed with code %s"%sw)
1231
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001232 # EF.PLMNwAcT
1233 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001234 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1235 if sw != '9000':
1236 print("Programming PLMNwAcT failed with code %s"%sw)
1237
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001238 # EF.OPLMNwAcT
1239 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001240 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1241 if sw != '9000':
1242 print("Programming OPLMNwAcT failed with code %s"%sw)
1243
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001244 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001245 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1246 if p.get('mcc') and p.get('mnc'):
1247 mnc = p['mnc']
1248 else:
1249 mnc = None
1250 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001251 if sw != '9000':
1252 print("Programming AD failed with code %s"%sw)
1253
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001254 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001255
Todd Neal9eeadfc2018-04-25 15:36:29 -05001256
herlesupreethb0c7d122020-12-23 09:25:46 +01001257class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001258 """
1259 sysmocom sysmoISIM-SJA2
1260 """
1261
1262 name = 'sysmoISIM-SJA2'
1263
1264 def __init__(self, ssc):
1265 super(SysmoISIMSJA2, self).__init__(ssc)
1266 self._scc.cla_byte = "00"
1267 self._scc.sel_ctrl = "0004" #request an FCP
1268
1269 @classmethod
1270 def autodetect(kls, scc):
1271 try:
1272 # Try card model #1
1273 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1274 if scc.get_atr() == toBytes(atr):
1275 return kls(scc)
1276
1277 # Try card model #2
1278 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1279 if scc.get_atr() == toBytes(atr):
1280 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001281
1282 # Try card model #3
1283 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1284 if scc.get_atr() == toBytes(atr):
1285 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001286 except:
1287 return None
1288 return None
1289
Harald Weltea6704252021-01-08 20:19:11 +01001290 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001291 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001292 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001293 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001294 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001295 return sw
1296
1297 def program(self, p):
1298 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001299
1300 # This type of card does not allow to reprogram the ICCID.
1301 # Reprogramming the ICCID would mess up the card os software
1302 # license management, so the ICCID must be kept at its factory
1303 # setting!
1304 if p.get('iccid'):
1305 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1306
1307 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001308 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001309
Robert Falkenberg54595362021-04-06 12:04:34 +02001310 # set Service Provider Name
1311 if p.get('name') is not None:
1312 content = enc_spn(p['name'], True, True)
1313 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
1314
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001315 # write EF.IMSI
1316 if p.get('imsi'):
1317 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1318
1319 # EF.PLMNsel
1320 if p.get('mcc') and p.get('mnc'):
1321 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1322 if sw != '9000':
1323 print("Programming PLMNsel failed with code %s"%sw)
1324
1325 # EF.PLMNwAcT
1326 if p.get('mcc') and p.get('mnc'):
1327 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1328 if sw != '9000':
1329 print("Programming PLMNwAcT failed with code %s"%sw)
1330
1331 # EF.OPLMNwAcT
1332 if p.get('mcc') and p.get('mnc'):
1333 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1334 if sw != '9000':
1335 print("Programming OPLMNwAcT failed with code %s"%sw)
1336
Harald Welte32f0d412020-05-05 17:35:57 +02001337 # EF.HPLMNwAcT
1338 if p.get('mcc') and p.get('mnc'):
1339 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1340 if sw != '9000':
1341 print("Programming HPLMNwAcT failed with code %s"%sw)
1342
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001343 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001344 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1345 if p.get('mcc') and p.get('mnc'):
1346 mnc = p['mnc']
1347 else:
1348 mnc = None
1349 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001350 if sw != '9000':
1351 print("Programming AD failed with code %s"%sw)
1352
1353 # EF.SMSP
1354 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001355 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001356 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1357
Supreeth Herlec6019232020-03-26 10:00:45 +01001358 # EF.MSISDN
1359 # TODO: Alpha Identifier (currently 'ff'O * 20)
1360 # TODO: Capability/Configuration1 Record Identifier
1361 # TODO: Extension1 Record Identifier
1362 if p.get('msisdn') is not None:
1363 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001364 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001365
Harald Weltec0499c82021-01-21 16:06:50 +01001366 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001367 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1368
Supreeth Herlea97944b2020-03-26 10:03:25 +01001369 # EF.ACC
1370 if p.get('acc'):
1371 sw = self.update_acc(p['acc'])
1372 if sw != '9000':
1373 print("Programming ACC failed with code %s"%sw)
1374
Supreeth Herle80164052020-03-23 12:06:29 +01001375 # Populate AIDs
1376 self.read_aids()
1377
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001378 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1379 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001380 self._scc.select_path(['3f00'])
1381 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001382 if p.get('ki'):
1383 self._scc.update_binary('6f20', p['ki'], 1)
1384 if p.get('opc'):
1385 self._scc.update_binary('6f20', p['opc'], 17)
1386
1387 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001388 data, sw = self.select_adf_by_aid(adf="isim")
1389 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001390 if p.get('ki'):
1391 self._scc.update_binary('af20', p['ki'], 1)
1392 if p.get('opc'):
1393 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001394
Supreeth Herlecf727f22020-03-24 17:32:21 +01001395 # update EF.P-CSCF in ADF.ISIM
1396 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1397 if p.get('pcscf'):
1398 sw = self.update_pcscf(p['pcscf'])
1399 else:
1400 sw = self.update_pcscf("")
1401 if sw != '9000':
1402 print("Programming P-CSCF failed with code %s"%sw)
1403
1404
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001405 # update EF.DOMAIN in ADF.ISIM
1406 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1407 if p.get('ims_hdomain'):
1408 sw = self.update_domain(domain=p['ims_hdomain'])
1409 else:
1410 sw = self.update_domain()
1411
1412 if sw != '9000':
1413 print("Programming Home Network Domain Name failed with code %s"%sw)
1414
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001415 # update EF.IMPI in ADF.ISIM
1416 # TODO: Validate IMPI input
1417 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1418 if p.get('impi'):
1419 sw = self.update_impi(p['impi'])
1420 else:
1421 sw = self.update_impi()
1422 if sw != '9000':
1423 print("Programming IMPI failed with code %s"%sw)
1424
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001425 # update EF.IMPU in ADF.ISIM
1426 # TODO: Validate IMPU input
1427 # Support multiple IMPU if there is enough space
1428 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1429 if p.get('impu'):
1430 sw = self.update_impu(p['impu'])
1431 else:
1432 sw = self.update_impu()
1433 if sw != '9000':
1434 print("Programming IMPU failed with code %s"%sw)
1435
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001436 data, sw = self.select_adf_by_aid(adf="usim")
1437 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001438 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001439 if p.get('ki'):
1440 self._scc.update_binary('af20', p['ki'], 1)
1441 if p.get('opc'):
1442 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001443
Harald Welteca673942020-06-03 15:19:40 +02001444 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001445 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001446 if p.get('mcc') and p.get('mnc'):
1447 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1448 if sw != '9000':
1449 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001450
1451 # update EF.ePDGId in ADF.USIM
1452 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1453 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001454 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001455 else:
1456 sw = self.update_epdgid("")
1457 if sw != '9000':
1458 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001459
Supreeth Herlef964df42020-03-24 13:15:37 +01001460 # update EF.ePDGSelection in ADF.USIM
1461 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1462 if p.get('epdgSelection'):
1463 epdg_plmn = p['epdgSelection']
1464 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1465 else:
1466 sw = self.update_ePDGSelection("", "")
1467 if sw != '9000':
1468 print("Programming ePDGSelection failed with code %s"%sw)
1469
1470
Supreeth Herleacc222f2020-03-24 13:26:53 +01001471 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1472 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001473 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001474 if self.file_exists(EF_USIM_ADF_map['UST']):
1475 if p.get('epdgSelection') and p.get('epdgid'):
1476 sw = self.update_ust(106, 1)
1477 if sw != '9000':
1478 print("Programming UST failed with code %s"%sw)
1479 sw = self.update_ust(107, 1)
1480 if sw != '9000':
1481 print("Programming UST failed with code %s"%sw)
1482
Supreeth Herle44e04622020-03-25 10:34:28 +01001483 sw = self.update_ust(95, 0)
1484 if sw != '9000':
1485 print("Programming UST failed with code %s"%sw)
1486 sw = self.update_ust(99, 0)
1487 if sw != '9000':
1488 print("Programming UST failed with code %s"%sw)
1489 sw = self.update_ust(115, 0)
1490 if sw != '9000':
1491 print("Programming UST failed with code %s"%sw)
1492
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001493 return
1494
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001495
Todd Neal9eeadfc2018-04-25 15:36:29 -05001496# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001497_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001498 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001499 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001500
1501def card_autodetect(scc):
1502 for kls in _cards_classes:
1503 card = kls.autodetect(scc)
1504 if card is not None:
1505 card.reset()
1506 return card
1507 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001508
1509def card_detect(ctype, scc):
1510 # Detect type if needed
1511 card = None
1512 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1513
1514 if ctype in ("auto", "auto_once"):
1515 for kls in _cards_classes:
1516 card = kls.autodetect(scc)
1517 if card:
1518 print("Autodetected card type: %s" % card.name)
1519 card.reset()
1520 break
1521
1522 if card is None:
1523 print("Autodetection failed")
1524 return None
1525
1526 if ctype == "auto_once":
1527 ctype = card.name
1528
1529 elif ctype in ctypes:
1530 card = ctypes[ctype](scc)
1531
1532 else:
1533 raise ValueError("Unknown card type: %s" % ctype)
1534
1535 return card