blob: 9a19eeda97ac6595a5cfe49262d4a095b7348f6d [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
Robert Falkenbergd0505bd2021-02-24 14:06:18 +010025from pySim.ts_51_011 import EF, DF, EF_AD
Harald Welteca673942020-06-03 15:19:40 +020026from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010027from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030028from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090029from smartcard.util import toBytes
Supreeth Herle79f43dd2020-03-25 11:43:19 +010030from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010031
32class Card(object):
33
34 def __init__(self, scc):
35 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030036 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010037 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010038
Sylvain Munaut76504e02010-12-07 00:24:32 +010039 def reset(self):
40 self._scc.reset_card()
41
Philipp Maierd58c6322020-05-12 16:47:45 +020042 def erase(self):
43 print("warning: erasing is not supported for specified card type!")
44 return
45
Harald Welteca673942020-06-03 15:19:40 +020046 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010047 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020048 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020049 if res[1] != '9000':
50 return False
Harald Welteca673942020-06-03 15:19:40 +020051 return True
52
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030053 def verify_adm(self, key):
54 '''
55 Authenticate with ADM key
56 '''
57 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
58 return sw
59
60 def read_iccid(self):
61 (res, sw) = self._scc.read_binary(EF['ICCID'])
62 if sw == '9000':
63 return (dec_iccid(res), sw)
64 else:
65 return (None, sw)
66
67 def read_imsi(self):
68 (res, sw) = self._scc.read_binary(EF['IMSI'])
69 if sw == '9000':
70 return (dec_imsi(res), sw)
71 else:
72 return (None, sw)
73
74 def update_imsi(self, imsi):
75 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
76 return sw
77
78 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +020079 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030080 return sw
81
Supreeth Herlea850a472020-03-19 12:44:11 +010082 def read_hplmn_act(self):
83 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
84 if sw == '9000':
85 return (format_xplmn_w_act(res), sw)
86 else:
87 return (None, sw)
88
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030089 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
90 """
91 Update Home PLMN with access technology bit-field
92
93 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
94 in ETSI TS 151 011 for the details of the access_tech field coding.
95 Some common values:
96 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +020097 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030098 """
99 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100100 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700101 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300102 hplmn = enc_plmn(mcc, mnc)
103 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700104 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300105 return sw
106
Supreeth Herle1757b262020-03-19 12:43:11 +0100107 def read_oplmn_act(self):
108 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
109 if sw == '9000':
110 return (format_xplmn_w_act(res), sw)
111 else:
112 return (None, sw)
113
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200114 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
115 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200116 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200117 """
118 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200119 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700120 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200121 hplmn = enc_plmn(mcc, mnc)
122 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700123 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200124 return sw
125
Supreeth Herle14084402020-03-19 12:42:10 +0100126 def read_plmn_act(self):
127 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
128 if sw == '9000':
129 return (format_xplmn_w_act(res), sw)
130 else:
131 return (None, sw)
132
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200133 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
134 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200135 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200136 """
137 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200138 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700139 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200140 hplmn = enc_plmn(mcc, mnc)
141 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700142 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200143 return sw
144
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200145 def update_plmnsel(self, mcc, mnc):
146 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700147 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200148 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200149 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
150 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200151
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300152 def update_smsp(self, smsp):
153 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
154 return sw
155
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100156 def update_ad(self, mnc=None, opmode=None, ofm=None):
157 """
158 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100159
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100160 See Sec. "4.2.18 EF_AD (Administrative Data)"
161 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200162
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100163 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200164
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100165 Parameters:
166 mnc (str): MNC of IMSI
167 opmode (Hex-str, 1 Byte): MS Operation Mode
168 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
169
170 Returns:
171 str: Return code of write operation
172 """
173
174 ad = EF_AD()
175
176 # read from card
177 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200178 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100179
180 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200181 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100182 mnclen = len(str(mnc))
183 if mnclen == 1:
184 mnclen = 2
185 if mnclen > 3:
186 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200187 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100188 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200189 opmode_num = int(opmode, 16)
190 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
191 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100192 else:
193 raise RuntimeError('invalid opmode "{}"'.format(opmode))
194 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200195 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100196
197 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200198 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100199 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100200 return sw
201
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300202 def read_spn(self):
203 (spn, sw) = self._scc.read_binary(EF['SPN'])
204 if sw == '9000':
205 return (dec_spn(spn), sw)
206 else:
207 return (None, sw)
208
209 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
210 content = enc_spn(name, hplmn_disp, oplmn_disp)
211 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
212 return sw
213
Supreeth Herled21349a2020-04-01 08:37:47 +0200214 def read_binary(self, ef, length=None, offset=0):
215 ef_path = ef in EF and EF[ef] or ef
216 return self._scc.read_binary(ef_path, length, offset)
217
Supreeth Herlead10d662020-04-01 08:43:08 +0200218 def read_record(self, ef, rec_no):
219 ef_path = ef in EF and EF[ef] or ef
220 return self._scc.read_record(ef_path, rec_no)
221
Supreeth Herle98a69272020-03-18 12:14:48 +0100222 def read_gid1(self):
223 (res, sw) = self._scc.read_binary(EF['GID1'])
224 if sw == '9000':
225 return (res, sw)
226 else:
227 return (None, sw)
228
Supreeth Herle6d66af62020-03-19 12:49:16 +0100229 def read_msisdn(self):
230 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
231 if sw == '9000':
232 return (dec_msisdn(res), sw)
233 else:
234 return (None, sw)
235
Supreeth Herlee4e98312020-03-18 11:33:14 +0100236 # Fetch all the AIDs present on UICC
237 def read_aids(self):
Philipp Maier1e896f32021-03-10 17:02:53 +0100238 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100239 try:
240 # Find out how many records the EF.DIR has
241 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100242 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100243 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100244 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100245 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
246 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
247 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
248 except Exception as e:
249 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100250 self._aids = []
251 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100252
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100253 # Select ADF.U/ISIM in the Card using its full AID
254 def select_adf_by_aid(self, adf="usim"):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100255 # Find full AID by partial AID:
256 if is_hex(adf):
257 for aid in self._aids:
258 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
259 return self._scc.select_adf(aid)
260 # Find full AID by application name:
261 elif adf in ["usim", "isim"]:
262 # First (known) halves of the U/ISIM AID
263 aid_map = {}
264 aid_map["usim"] = "a0000000871002"
265 aid_map["isim"] = "a0000000871004"
266 for aid in self._aids:
267 if aid_map[adf] in aid:
268 return self._scc.select_adf(aid)
269 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100270
Philipp Maier5c2cc662020-05-12 16:27:12 +0200271 # Erase the contents of a file
272 def erase_binary(self, ef):
273 len = self._scc.binary_size(ef)
274 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
275
276 # Erase the contents of a single record
277 def erase_record(self, ef, rec_no):
278 len = self._scc.record_size(ef)
279 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
280
Harald Welteca673942020-06-03 15:19:40 +0200281class UsimCard(Card):
282 def __init__(self, ssc):
283 super(UsimCard, self).__init__(ssc)
284
285 def read_ehplmn(self):
286 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
287 if sw == '9000':
288 return (format_xplmn(res), sw)
289 else:
290 return (None, sw)
291
292 def update_ehplmn(self, mcc, mnc):
293 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
294 size = len(data[0]) // 2
295 ehplmn = enc_plmn(mcc, mnc)
296 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
297 return sw
298
herlesupreethf8232db2020-09-29 10:03:06 +0200299 def read_epdgid(self):
300 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
301 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100302 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200303 else:
304 return (None, sw)
305
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200306 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100307 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
308 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100309 addr_type = get_addr_type(epdgid)
310 if addr_type == None:
311 raise ValueError("Unknown ePDG Id address type or invalid address provided")
312 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100313 else:
314 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200315 data, sw = self._scc.update_binary(
316 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
317 return sw
Harald Welteca673942020-06-03 15:19:40 +0200318
Supreeth Herle99d55552020-03-24 13:03:43 +0100319 def read_ePDGSelection(self):
320 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
321 if sw == '9000':
322 return (format_ePDGSelection(res), sw)
323 else:
324 return (None, sw)
325
Supreeth Herlef964df42020-03-24 13:15:37 +0100326 def update_ePDGSelection(self, mcc, mnc):
327 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
328 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
329 # Reset contents
330 # 80 - Tag value
331 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
332 elif sw == '9000':
333 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
334 return sw
335
herlesupreeth4a3580b2020-09-29 10:11:36 +0200336 def read_ust(self):
337 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
338 if sw == '9000':
339 # Print those which are available
340 return ([res, dec_st(res, table="usim")], sw)
341 else:
342 return ([None, None], sw)
343
Supreeth Herleacc222f2020-03-24 13:26:53 +0100344 def update_ust(self, service, bit=1):
345 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
346 if sw == '9000':
347 content = enc_st(res, service, bit)
348 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
349 return sw
350
herlesupreethecbada92020-12-23 09:24:29 +0100351class IsimCard(Card):
352 def __init__(self, ssc):
353 super(IsimCard, self).__init__(ssc)
354
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100355 def read_pcscf(self):
356 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
357 pcscf_recs = ""
358 for i in range(0, rec_cnt):
359 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
360 if sw == '9000':
361 content = dec_addr_tlv(res)
362 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
363 else:
364 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
365 return pcscf_recs
366
Supreeth Herlecf727f22020-03-24 17:32:21 +0100367 def update_pcscf(self, pcscf):
368 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100369 addr_type = get_addr_type(pcscf)
370 if addr_type == None:
371 raise ValueError("Unknown PCSCF address type or invalid address provided")
372 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100373 else:
374 # Just the tag value
375 content = '80'
376 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100377 pcscf_tlv = rpad(content, rec_size_bytes*2)
378 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100379 return sw
380
Supreeth Herle05b28072020-03-25 10:23:48 +0100381 def read_domain(self):
382 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
383 if sw == '9000':
384 # Skip the inital tag value ('80') byte and get length of contents
385 length = int(res[2:4], 16)
386 content = h2s(res[4:4+(length*2)])
387 return (content, sw)
388 else:
389 return (None, sw)
390
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100391 def update_domain(self, domain=None, mcc=None, mnc=None):
392 hex_str = ""
393 if domain:
394 hex_str = s2h(domain)
395 elif mcc and mnc:
396 # MCC and MNC always has 3 digits in domain form
397 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
398 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
399
400 # Build TLV
401 tlv = TLV(['80'])
402 content = tlv.build({'80': hex_str})
403
404 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
405 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
406 return sw
407
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100408 def read_impi(self):
409 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
410 if sw == '9000':
411 # Skip the inital tag value ('80') byte and get length of contents
412 length = int(res[2:4], 16)
413 content = h2s(res[4:4+(length*2)])
414 return (content, sw)
415 else:
416 return (None, sw)
417
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100418 def update_impi(self, impi=None):
419 hex_str = ""
420 if impi:
421 hex_str = s2h(impi)
422 # Build TLV
423 tlv = TLV(['80'])
424 content = tlv.build({'80': hex_str})
425
426 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
427 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
428 return sw
429
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100430 def read_impu(self):
431 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
432 impu_recs = ""
433 for i in range(0, rec_cnt):
434 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
435 if sw == '9000':
436 # Skip the inital tag value ('80') byte and get length of contents
437 length = int(res[2:4], 16)
438 content = h2s(res[4:4+(length*2)])
439 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
440 else:
441 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
442 return impu_recs
443
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100444 def update_impu(self, impu=None):
445 hex_str = ""
446 if impu:
447 hex_str = s2h(impu)
448 # Build TLV
449 tlv = TLV(['80'])
450 content = tlv.build({'80': hex_str})
451
452 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
453 impu_tlv = rpad(content, rec_size_bytes*2)
454 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
455 return sw
456
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200457 def read_iari(self):
458 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
459 uiari_recs = ""
460 for i in range(0, rec_cnt):
461 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
462 if sw == '9000':
463 # Skip the inital tag value ('80') byte and get length of contents
464 length = int(res[2:4], 16)
465 content = h2s(res[4:4+(length*2)])
466 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
467 else:
468 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
469 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100470
471class _MagicSimBase(Card):
472 """
473 Theses cards uses several record based EFs to store the provider infos,
474 each possible provider uses a specific record number in each EF. The
475 indexes used are ( where N is the number of providers supported ) :
476 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200477 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100478
479 * 3f00/7f4d/8f0c : Operator Name
480
481 bytes 0-15 : provider name, padded with 0xff
482 byte 16 : length of the provider name
483 byte 17 : 01 for valid records, 00 otherwise
484
485 * 3f00/7f4d/8f0d : Programmable Binary EFs
486
487 * 3f00/7f4d/8f0e : Programmable Record EFs
488
489 """
490
491 @classmethod
492 def autodetect(kls, scc):
493 try:
494 for p, l, t in kls._files.values():
495 if not t:
496 continue
497 if scc.record_size(['3f00', '7f4d', p]) != l:
498 return None
499 except:
500 return None
501
502 return kls(scc)
503
504 def _get_count(self):
505 """
506 Selects the file and returns the total number of entries
507 and entry size
508 """
509 f = self._files['name']
510
Harald Weltec0499c82021-01-21 16:06:50 +0100511 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100512 rec_len = int(r[-1][28:30], 16)
513 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200514 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100515
516 if (rec_cnt < 1) or (rec_len != f[1]):
517 raise RuntimeError('Bad card type')
518
519 return rec_cnt
520
521 def program(self, p):
522 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100523 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100524
525 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400526 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100527
528 # Operator name ( 3f00/7f4d/8f0c )
529 self._scc.update_record(self._files['name'][0], 2,
530 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
531 )
532
533 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
534 v = ''
535
536 # inline Ki
537 if self._ki_file is None:
538 v += p['ki']
539
540 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400541 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100542
543 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400544 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100545
546 # Ki
547 if self._ki_file:
548 v += self._ki_file + '10' + p['ki']
549
550 # PLMN_Sel
551 v+= '6f30' + '18' + rpad(hplmn, 36)
552
Alexander Chemeris21885242013-07-02 16:56:55 +0400553 # ACC
554 # This doesn't work with "fake" SuperSIM cards,
555 # but will hopefully work with real SuperSIMs.
556 if p.get('acc') is not None:
557 v+= '6f78' + '02' + lpad(p['acc'], 4)
558
Sylvain Munaut76504e02010-12-07 00:24:32 +0100559 self._scc.update_record(self._files['b_ef'][0], 1,
560 rpad(v, self._files['b_ef'][1]*2)
561 )
562
563 # SMSP ( 3f00/7f4d/8f0e )
564 # FIXME
565
566 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100567 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100568 tl = int(r[-1][4:8], 16)
569
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400570 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100571 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
572
573 def erase(self):
574 # Dummy
575 df = {}
576 for k, v in self._files.iteritems():
577 ofs = 1
578 fv = v[1] * 'ff'
579 if k == 'name':
580 ofs = 2
581 fv = fv[0:-4] + '0000'
582 df[v[0]] = (fv, ofs)
583
584 # Write
585 for n in range(0,self._get_count()):
586 for k, (msg, ofs) in df.iteritems():
587 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
588
589
590class SuperSim(_MagicSimBase):
591
592 name = 'supersim'
593
594 _files = {
595 'name' : ('8f0c', 18, True),
596 'b_ef' : ('8f0d', 74, True),
597 'r_ef' : ('8f0e', 50, True),
598 }
599
600 _ki_file = None
601
602
603class MagicSim(_MagicSimBase):
604
605 name = 'magicsim'
606
607 _files = {
608 'name' : ('8f0c', 18, True),
609 'b_ef' : ('8f0d', 130, True),
610 'r_ef' : ('8f0e', 102, False),
611 }
612
613 _ki_file = '6f1b'
614
615
616class FakeMagicSim(Card):
617 """
618 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200619 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100620 1 to N.
621 """
622
623 name = 'fakemagicsim'
624
625 @classmethod
626 def autodetect(kls, scc):
627 try:
628 if scc.record_size(['3f00', '000c']) != 0x5a:
629 return None
630 except:
631 return None
632
633 return kls(scc)
634
635 def _get_infos(self):
636 """
637 Selects the file and returns the total number of entries
638 and entry size
639 """
640
Harald Weltec0499c82021-01-21 16:06:50 +0100641 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100642 rec_len = int(r[-1][28:30], 16)
643 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200644 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100645
646 if (rec_cnt < 1) or (rec_len != 0x5a):
647 raise RuntimeError('Bad card type')
648
649 return rec_cnt, rec_len
650
651 def program(self, p):
652 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100653 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100654 tl = int(r[-1][4:8], 16)
655
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400656 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100657 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
658
659 # Get total number of entries and entry size
660 rec_cnt, rec_len = self._get_infos()
661
662 # Set first entry
663 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200664 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100665 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200666 enc_iccid(p['iccid']) + # 10b ICCID
667 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
668 p['ki'] + # 16b Ki
669 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100670 )
671 self._scc.update_record('000c', 1, entry)
672
673 def erase(self):
674 # Get total number of entries and entry size
675 rec_cnt, rec_len = self._get_infos()
676
677 # Erase all entries
678 entry = 'ff' * rec_len
679 for i in range(0, rec_cnt):
680 self._scc.update_record('000c', 1+i, entry)
681
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200682
Harald Welte3156d902011-03-22 21:48:19 +0100683class GrcardSim(Card):
684 """
685 Greencard (grcard.cn) HZCOS GSM SIM
686 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
687 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
688 """
689
690 name = 'grcardsim'
691
692 @classmethod
693 def autodetect(kls, scc):
694 return None
695
696 def program(self, p):
697 # We don't really know yet what ADM PIN 4 is about
698 #self._scc.verify_chv(4, h2b("4444444444444444"))
699
700 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100701 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200702 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100703 else:
704 pin = h2b("4444444444444444")
705 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100706
707 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100708 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400709 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100710
711 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100712 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400713 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100714
715 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400716 if p.get('acc') is not None:
717 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100718
719 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200720 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100721 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200722 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100723
724 # Set the Ki using proprietary command
725 pdu = '80d4020010' + p['ki']
726 data, sw = self._scc._tp.send_apdu(pdu)
727
728 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100729 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100730 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400731 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100732 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
733
734 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100735 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100736 size = int(r[-1][4:8], 16)
737 # FIXME
738
739 # FIXME: EF.MSISDN
740
Sylvain Munaut76504e02010-12-07 00:24:32 +0100741
Harald Weltee10394b2011-12-07 12:34:14 +0100742class SysmoSIMgr1(GrcardSim):
743 """
744 sysmocom sysmoSIM-GR1
745 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
746 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
747 """
748 name = 'sysmosim-gr1'
749
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200750 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200751 def autodetect(kls, scc):
752 try:
753 # Look for ATR
754 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
755 return kls(scc)
756 except:
757 return None
758 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200759
Harald Welteca673942020-06-03 15:19:40 +0200760class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100761 """
762 sysmocom sysmoUSIM-GR1
763 """
764 name = 'sysmoUSIM-GR1'
765
766 @classmethod
767 def autodetect(kls, scc):
768 # TODO: Access the ATR
769 return None
770
771 def program(self, p):
772 # TODO: check if verify_chv could be used or what it needs
773 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
774 # Unlock the card..
775 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
776
777 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100778 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400779 p['opc'] + # 32b OPC
780 enc_iccid(p['iccid']) + # 10b ICCID
781 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100782 )
783 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
784
Sylvain Munaut053c8952013-07-02 15:12:32 +0200785
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100786class SysmoSIMgr2(Card):
787 """
788 sysmocom sysmoSIM-GR2
789 """
790
791 name = 'sysmoSIM-GR2'
792
793 @classmethod
794 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900795 try:
796 # Look for ATR
797 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
798 return kls(scc)
799 except:
800 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100801 return None
802
803 def program(self, p):
804
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200805 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100806 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200807
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100808 # authenticate as SUPER ADM using default key
809 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
810
811 # set ADM pin using proprietary command
812 # INS: D4
813 # P1: 3A for PIN, 3B for PUK
814 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
815 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100816 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200817 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100818 else:
819 pin = h2b("4444444444444444")
820
821 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100822 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200823
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100824 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100825
826 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100827
828 # write EF.ICCID
829 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
830
831 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100832 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200833
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100834 # write EF.IMSI
835 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
836
837 # write EF.ACC
838 if p.get('acc') is not None:
839 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
840
841 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100842 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100843 size = int(r[-1][4:8], 16)
844 hplmn = enc_plmn(p['mcc'], p['mnc'])
845 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
846
847 # set COMP128 version 0 in proprietary file
848 data, sw = self._scc.update_binary('0001', '001000')
849
850 # set Ki in proprietary file
851 data, sw = self._scc.update_binary('0001', p['ki'], 3)
852
853 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100854 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200855
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100856 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200857 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200858 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100859
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100860
Harald Welteca673942020-06-03 15:19:40 +0200861class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100862 """
863 sysmocom sysmoUSIM-SJS1
864 """
865
866 name = 'sysmoUSIM-SJS1'
867
868 def __init__(self, ssc):
869 super(SysmoUSIMSJS1, self).__init__(ssc)
870 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100871 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100872
873 @classmethod
874 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900875 try:
876 # Look for ATR
877 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"):
878 return kls(scc)
879 except:
880 return None
Jan Balke3e840672015-01-26 15:36:27 +0100881 return None
882
Harald Weltea6704252021-01-08 20:19:11 +0100883 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100884 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100885 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100886 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100887 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100888 return sw
889
890 def program(self, p):
891 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100892
893 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100894 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100895
Philipp Maiere9604882017-03-21 17:24:31 +0100896 # write EF.ICCID
897 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
898
Jan Balke3e840672015-01-26 15:36:27 +0100899 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100900 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100901
Jan Balke3e840672015-01-26 15:36:27 +0100902 # set Ki in proprietary file
903 data, sw = self._scc.update_binary('00FF', p['ki'])
904
Philipp Maier1be35bf2018-07-13 11:29:03 +0200905 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200906 if 'opc' in p:
907 content = "01" + p['opc']
908 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100909
Supreeth Herle7947d922019-06-08 07:50:53 +0200910 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100911 if p.get('name') is not None:
912 content = enc_spn(p['name'], True, True)
913 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200914
Supreeth Herlec8796a32019-12-23 12:23:42 +0100915 if p.get('acc') is not None:
916 self.update_acc(p['acc'])
917
Jan Balke3e840672015-01-26 15:36:27 +0100918 # write EF.IMSI
919 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
920
Philipp Maier2d15ea02019-03-20 12:40:36 +0100921 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200922 if p.get('mcc') and p.get('mnc'):
923 sw = self.update_plmnsel(p['mcc'], p['mnc'])
924 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100925 print("Programming PLMNsel failed with code %s"%sw)
926
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200927 # EF.PLMNwAcT
928 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100929 sw = self.update_plmn_act(p['mcc'], p['mnc'])
930 if sw != '9000':
931 print("Programming PLMNwAcT failed with code %s"%sw)
932
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200933 # EF.OPLMNwAcT
934 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100935 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
936 if sw != '9000':
937 print("Programming OPLMNwAcT failed with code %s"%sw)
938
Supreeth Herlef442fb42020-01-21 12:47:32 +0100939 # EF.HPLMNwAcT
940 if p.get('mcc') and p.get('mnc'):
941 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
942 if sw != '9000':
943 print("Programming HPLMNwAcT failed with code %s"%sw)
944
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200945 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100946 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
947 if p.get('mcc') and p.get('mnc'):
948 mnc = p['mnc']
949 else:
950 mnc = None
951 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +0100952 if sw != '9000':
953 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100954
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200955 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200956 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100957 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200958 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100959
Supreeth Herle5a541012019-12-22 08:59:16 +0100960 # EF.MSISDN
961 # TODO: Alpha Identifier (currently 'ff'O * 20)
962 # TODO: Capability/Configuration1 Record Identifier
963 # TODO: Extension1 Record Identifier
964 if p.get('msisdn') is not None:
965 msisdn = enc_msisdn(p['msisdn'])
966 data = 'ff' * 20 + msisdn + 'ff' * 2
967
Harald Weltec0499c82021-01-21 16:06:50 +0100968 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100969 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
970
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900971
herlesupreeth4a3580b2020-09-29 10:11:36 +0200972class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900973 """
974 FairwavesSIM
975
976 The SIM card is operating according to the standard.
977 For Ki/OP/OPC programming the following files are additionally open for writing:
978 3F00/7F20/FF01 – OP/OPC:
979 byte 1 = 0x01, bytes 2-17: OPC;
980 byte 1 = 0x00, bytes 2-17: OP;
981 3F00/7F20/FF02: Ki
982 """
983
Philipp Maier5a876312019-11-11 11:01:46 +0100984 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900985 # Propriatary files
986 _EF_num = {
987 'Ki': 'FF02',
988 'OP/OPC': 'FF01',
989 }
990 _EF = {
991 'Ki': DF['GSM']+[_EF_num['Ki']],
992 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
993 }
994
995 def __init__(self, ssc):
996 super(FairwavesSIM, self).__init__(ssc)
997 self._adm_chv_num = 0x11
998 self._adm2_chv_num = 0x12
999
1000
1001 @classmethod
1002 def autodetect(kls, scc):
1003 try:
1004 # Look for ATR
1005 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"):
1006 return kls(scc)
1007 except:
1008 return None
1009 return None
1010
1011
1012 def verify_adm2(self, key):
1013 '''
1014 Authenticate with ADM2 key.
1015
1016 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1017 is a key which has access to proprietary files (Ki and OP/OPC).
1018 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1019 need ADM2 key per se.
1020 '''
1021 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1022 return sw
1023
1024
1025 def read_ki(self):
1026 """
1027 Read Ki in proprietary file.
1028
1029 Requires ADM1 access level
1030 """
1031 return self._scc.read_binary(self._EF['Ki'])
1032
1033
1034 def update_ki(self, ki):
1035 """
1036 Set Ki in proprietary file.
1037
1038 Requires ADM1 access level
1039 """
1040 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1041 return sw
1042
1043
1044 def read_op_opc(self):
1045 """
1046 Read Ki in proprietary file.
1047
1048 Requires ADM1 access level
1049 """
1050 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1051 type = 'OP' if ef[0:2] == '00' else 'OPC'
1052 return ((type, ef[2:]), sw)
1053
1054
1055 def update_op(self, op):
1056 """
1057 Set OP in proprietary file.
1058
1059 Requires ADM1 access level
1060 """
1061 content = '00' + op
1062 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1063 return sw
1064
1065
1066 def update_opc(self, opc):
1067 """
1068 Set OPC in proprietary file.
1069
1070 Requires ADM1 access level
1071 """
1072 content = '01' + opc
1073 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1074 return sw
1075
1076
1077 def program(self, p):
1078 # authenticate as ADM1
1079 if not p['pin_adm']:
1080 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001081 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001082
1083 # TODO: Set operator name
1084 if p.get('smsp') is not None:
1085 sw = self.update_smsp(p['smsp'])
1086 if sw != '9000':
1087 print("Programming SMSP failed with code %s"%sw)
1088 # This SIM doesn't support changing ICCID
1089 if p.get('mcc') is not None and p.get('mnc') is not None:
1090 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1091 if sw != '9000':
1092 print("Programming MCC/MNC failed with code %s"%sw)
1093 if p.get('imsi') is not None:
1094 sw = self.update_imsi(p['imsi'])
1095 if sw != '9000':
1096 print("Programming IMSI failed with code %s"%sw)
1097 if p.get('ki') is not None:
1098 sw = self.update_ki(p['ki'])
1099 if sw != '9000':
1100 print("Programming Ki failed with code %s"%sw)
1101 if p.get('opc') is not None:
1102 sw = self.update_opc(p['opc'])
1103 if sw != '9000':
1104 print("Programming OPC failed with code %s"%sw)
1105 if p.get('acc') is not None:
1106 sw = self.update_acc(p['acc'])
1107 if sw != '9000':
1108 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001109
Todd Neal9eeadfc2018-04-25 15:36:29 -05001110class OpenCellsSim(Card):
1111 """
1112 OpenCellsSim
1113
1114 """
1115
Philipp Maier5a876312019-11-11 11:01:46 +01001116 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001117
1118 def __init__(self, ssc):
1119 super(OpenCellsSim, self).__init__(ssc)
1120 self._adm_chv_num = 0x0A
1121
1122
1123 @classmethod
1124 def autodetect(kls, scc):
1125 try:
1126 # Look for ATR
1127 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"):
1128 return kls(scc)
1129 except:
1130 return None
1131 return None
1132
1133
1134 def program(self, p):
1135 if not p['pin_adm']:
1136 raise ValueError("Please provide a PIN-ADM as there is no default one")
1137 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1138
1139 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001140 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001141
1142 # write EF.ICCID
1143 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1144
Harald Weltec0499c82021-01-21 16:06:50 +01001145 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001146
1147 # set Ki in proprietary file
1148 data, sw = self._scc.update_binary('FF02', p['ki'])
1149
1150 # set OPC in proprietary file
1151 data, sw = self._scc.update_binary('FF01', p['opc'])
1152
1153 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001154 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001155
1156 # write EF.IMSI
1157 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1158
herlesupreeth4a3580b2020-09-29 10:11:36 +02001159class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001160 """
1161 WavemobileSim
1162
1163 """
1164
1165 name = 'Wavemobile-SIM'
1166
1167 def __init__(self, ssc):
1168 super(WavemobileSim, self).__init__(ssc)
1169 self._adm_chv_num = 0x0A
1170 self._scc.cla_byte = "00"
1171 self._scc.sel_ctrl = "0004" #request an FCP
1172
1173 @classmethod
1174 def autodetect(kls, scc):
1175 try:
1176 # Look for ATR
1177 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"):
1178 return kls(scc)
1179 except:
1180 return None
1181 return None
1182
1183 def program(self, p):
1184 if not p['pin_adm']:
1185 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001186 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001187
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001188 # EF.ICCID
1189 # TODO: Add programming of the ICCID
1190 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001191 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1192
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001193 # KI (Presumably a propritary file)
1194 # TODO: Add programming of KI
1195 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001196 print("Warning: Programming of the KI is not implemented for this type of card.")
1197
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001198 # OPc (Presumably a propritary file)
1199 # TODO: Add programming of OPc
1200 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001201 print("Warning: Programming of the OPc is not implemented for this type of card.")
1202
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001203 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001204 if p.get('smsp'):
1205 sw = self.update_smsp(p['smsp'])
1206 if sw != '9000':
1207 print("Programming SMSP failed with code %s"%sw)
1208
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001209 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001210 if p.get('imsi'):
1211 sw = self.update_imsi(p['imsi'])
1212 if sw != '9000':
1213 print("Programming IMSI failed with code %s"%sw)
1214
1215 # EF.ACC
1216 if p.get('acc'):
1217 sw = self.update_acc(p['acc'])
1218 if sw != '9000':
1219 print("Programming ACC failed with code %s"%sw)
1220
1221 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001222 if p.get('mcc') and p.get('mnc'):
1223 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1224 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001225 print("Programming PLMNsel failed with code %s"%sw)
1226
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001227 # EF.PLMNwAcT
1228 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001229 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1230 if sw != '9000':
1231 print("Programming PLMNwAcT failed with code %s"%sw)
1232
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001233 # EF.OPLMNwAcT
1234 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001235 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1236 if sw != '9000':
1237 print("Programming OPLMNwAcT failed with code %s"%sw)
1238
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001239 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001240 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1241 if p.get('mcc') and p.get('mnc'):
1242 mnc = p['mnc']
1243 else:
1244 mnc = None
1245 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001246 if sw != '9000':
1247 print("Programming AD failed with code %s"%sw)
1248
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001249 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001250
Todd Neal9eeadfc2018-04-25 15:36:29 -05001251
herlesupreethb0c7d122020-12-23 09:25:46 +01001252class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001253 """
1254 sysmocom sysmoISIM-SJA2
1255 """
1256
1257 name = 'sysmoISIM-SJA2'
1258
1259 def __init__(self, ssc):
1260 super(SysmoISIMSJA2, self).__init__(ssc)
1261 self._scc.cla_byte = "00"
1262 self._scc.sel_ctrl = "0004" #request an FCP
1263
1264 @classmethod
1265 def autodetect(kls, scc):
1266 try:
1267 # Try card model #1
1268 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1269 if scc.get_atr() == toBytes(atr):
1270 return kls(scc)
1271
1272 # Try card model #2
1273 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1274 if scc.get_atr() == toBytes(atr):
1275 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001276
1277 # Try card model #3
1278 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1279 if scc.get_atr() == toBytes(atr):
1280 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001281 except:
1282 return None
1283 return None
1284
Harald Weltea6704252021-01-08 20:19:11 +01001285 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001286 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001287 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001288 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001289 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001290 return sw
1291
1292 def program(self, p):
1293 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001294
1295 # This type of card does not allow to reprogram the ICCID.
1296 # Reprogramming the ICCID would mess up the card os software
1297 # license management, so the ICCID must be kept at its factory
1298 # setting!
1299 if p.get('iccid'):
1300 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1301
1302 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001303 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001304
Robert Falkenberg54595362021-04-06 12:04:34 +02001305 # set Service Provider Name
1306 if p.get('name') is not None:
1307 content = enc_spn(p['name'], True, True)
1308 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
1309
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001310 # write EF.IMSI
1311 if p.get('imsi'):
1312 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1313
1314 # EF.PLMNsel
1315 if p.get('mcc') and p.get('mnc'):
1316 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1317 if sw != '9000':
1318 print("Programming PLMNsel failed with code %s"%sw)
1319
1320 # EF.PLMNwAcT
1321 if p.get('mcc') and p.get('mnc'):
1322 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1323 if sw != '9000':
1324 print("Programming PLMNwAcT failed with code %s"%sw)
1325
1326 # EF.OPLMNwAcT
1327 if p.get('mcc') and p.get('mnc'):
1328 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1329 if sw != '9000':
1330 print("Programming OPLMNwAcT failed with code %s"%sw)
1331
Harald Welte32f0d412020-05-05 17:35:57 +02001332 # EF.HPLMNwAcT
1333 if p.get('mcc') and p.get('mnc'):
1334 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1335 if sw != '9000':
1336 print("Programming HPLMNwAcT failed with code %s"%sw)
1337
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001338 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001339 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1340 if p.get('mcc') and p.get('mnc'):
1341 mnc = p['mnc']
1342 else:
1343 mnc = None
1344 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001345 if sw != '9000':
1346 print("Programming AD failed with code %s"%sw)
1347
1348 # EF.SMSP
1349 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001350 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001351 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1352
Supreeth Herlec6019232020-03-26 10:00:45 +01001353 # EF.MSISDN
1354 # TODO: Alpha Identifier (currently 'ff'O * 20)
1355 # TODO: Capability/Configuration1 Record Identifier
1356 # TODO: Extension1 Record Identifier
1357 if p.get('msisdn') is not None:
1358 msisdn = enc_msisdn(p['msisdn'])
1359 content = 'ff' * 20 + msisdn + 'ff' * 2
1360
Harald Weltec0499c82021-01-21 16:06:50 +01001361 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001362 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1363
Supreeth Herlea97944b2020-03-26 10:03:25 +01001364 # EF.ACC
1365 if p.get('acc'):
1366 sw = self.update_acc(p['acc'])
1367 if sw != '9000':
1368 print("Programming ACC failed with code %s"%sw)
1369
Supreeth Herle80164052020-03-23 12:06:29 +01001370 # Populate AIDs
1371 self.read_aids()
1372
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001373 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1374 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001375 self._scc.select_path(['3f00'])
1376 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001377 if p.get('ki'):
1378 self._scc.update_binary('6f20', p['ki'], 1)
1379 if p.get('opc'):
1380 self._scc.update_binary('6f20', p['opc'], 17)
1381
1382 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001383 data, sw = self.select_adf_by_aid(adf="isim")
1384 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001385 if p.get('ki'):
1386 self._scc.update_binary('af20', p['ki'], 1)
1387 if p.get('opc'):
1388 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001389
Supreeth Herlecf727f22020-03-24 17:32:21 +01001390 # update EF.P-CSCF in ADF.ISIM
1391 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1392 if p.get('pcscf'):
1393 sw = self.update_pcscf(p['pcscf'])
1394 else:
1395 sw = self.update_pcscf("")
1396 if sw != '9000':
1397 print("Programming P-CSCF failed with code %s"%sw)
1398
1399
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001400 # update EF.DOMAIN in ADF.ISIM
1401 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1402 if p.get('ims_hdomain'):
1403 sw = self.update_domain(domain=p['ims_hdomain'])
1404 else:
1405 sw = self.update_domain()
1406
1407 if sw != '9000':
1408 print("Programming Home Network Domain Name failed with code %s"%sw)
1409
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001410 # update EF.IMPI in ADF.ISIM
1411 # TODO: Validate IMPI input
1412 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1413 if p.get('impi'):
1414 sw = self.update_impi(p['impi'])
1415 else:
1416 sw = self.update_impi()
1417 if sw != '9000':
1418 print("Programming IMPI failed with code %s"%sw)
1419
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001420 # update EF.IMPU in ADF.ISIM
1421 # TODO: Validate IMPU input
1422 # Support multiple IMPU if there is enough space
1423 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1424 if p.get('impu'):
1425 sw = self.update_impu(p['impu'])
1426 else:
1427 sw = self.update_impu()
1428 if sw != '9000':
1429 print("Programming IMPU failed with code %s"%sw)
1430
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001431 data, sw = self.select_adf_by_aid(adf="usim")
1432 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001433 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001434 if p.get('ki'):
1435 self._scc.update_binary('af20', p['ki'], 1)
1436 if p.get('opc'):
1437 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001438
Harald Welteca673942020-06-03 15:19:40 +02001439 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001440 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001441 if p.get('mcc') and p.get('mnc'):
1442 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1443 if sw != '9000':
1444 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001445
1446 # update EF.ePDGId in ADF.USIM
1447 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1448 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001449 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001450 else:
1451 sw = self.update_epdgid("")
1452 if sw != '9000':
1453 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001454
Supreeth Herlef964df42020-03-24 13:15:37 +01001455 # update EF.ePDGSelection in ADF.USIM
1456 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1457 if p.get('epdgSelection'):
1458 epdg_plmn = p['epdgSelection']
1459 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1460 else:
1461 sw = self.update_ePDGSelection("", "")
1462 if sw != '9000':
1463 print("Programming ePDGSelection failed with code %s"%sw)
1464
1465
Supreeth Herleacc222f2020-03-24 13:26:53 +01001466 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1467 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001468 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001469 if self.file_exists(EF_USIM_ADF_map['UST']):
1470 if p.get('epdgSelection') and p.get('epdgid'):
1471 sw = self.update_ust(106, 1)
1472 if sw != '9000':
1473 print("Programming UST failed with code %s"%sw)
1474 sw = self.update_ust(107, 1)
1475 if sw != '9000':
1476 print("Programming UST failed with code %s"%sw)
1477
Supreeth Herle44e04622020-03-25 10:34:28 +01001478 sw = self.update_ust(95, 0)
1479 if sw != '9000':
1480 print("Programming UST failed with code %s"%sw)
1481 sw = self.update_ust(99, 0)
1482 if sw != '9000':
1483 print("Programming UST failed with code %s"%sw)
1484 sw = self.update_ust(115, 0)
1485 if sw != '9000':
1486 print("Programming UST failed with code %s"%sw)
1487
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001488 return
1489
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001490
Todd Neal9eeadfc2018-04-25 15:36:29 -05001491# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001492_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001493 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001494 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001495
1496def card_autodetect(scc):
1497 for kls in _cards_classes:
1498 card = kls.autodetect(scc)
1499 if card is not None:
1500 card.reset()
1501 return card
1502 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001503
1504def card_detect(ctype, scc):
1505 # Detect type if needed
1506 card = None
1507 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1508
1509 if ctype in ("auto", "auto_once"):
1510 for kls in _cards_classes:
1511 card = kls.autodetect(scc)
1512 if card:
1513 print("Autodetected card type: %s" % card.name)
1514 card.reset()
1515 break
1516
1517 if card is None:
1518 print("Autodetection failed")
1519 return None
1520
1521 if ctype == "auto_once":
1522 ctype = card.name
1523
1524 elif ctype in ctypes:
1525 card = ctypes[ctype](scc)
1526
1527 else:
1528 raise ValueError("Unknown card type: %s" % ctype)
1529
1530 return card