blob: 8b51787a9e378a68cc1c5c8f65990448ab4cd894 [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
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030025from pySim.ts_51_011 import EF, DF
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):
79 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
80 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
97 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
98 """
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
Philipp Maieree908ae2019-03-21 16:21:12 +0100156 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200157 #See also: 3GPP TS 31.102, chapter 4.2.18
158 mnclen = len(str(mnc))
159 if mnclen == 1:
160 mnclen = 2
161 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100162 raise RuntimeError('unable to calculate proper mnclen')
163
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200164 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
165
166 # Reset contents to EF.AD in case the file is uninintalized
167 if data.lower() == "ffffffff":
168 data = "00000000"
169
170 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100171 data, sw = self._scc.update_binary(EF['AD'], content)
172 return sw
173
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300174 def read_spn(self):
175 (spn, sw) = self._scc.read_binary(EF['SPN'])
176 if sw == '9000':
177 return (dec_spn(spn), sw)
178 else:
179 return (None, sw)
180
181 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
182 content = enc_spn(name, hplmn_disp, oplmn_disp)
183 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
184 return sw
185
Supreeth Herled21349a2020-04-01 08:37:47 +0200186 def read_binary(self, ef, length=None, offset=0):
187 ef_path = ef in EF and EF[ef] or ef
188 return self._scc.read_binary(ef_path, length, offset)
189
Supreeth Herlead10d662020-04-01 08:43:08 +0200190 def read_record(self, ef, rec_no):
191 ef_path = ef in EF and EF[ef] or ef
192 return self._scc.read_record(ef_path, rec_no)
193
Supreeth Herle98a69272020-03-18 12:14:48 +0100194 def read_gid1(self):
195 (res, sw) = self._scc.read_binary(EF['GID1'])
196 if sw == '9000':
197 return (res, sw)
198 else:
199 return (None, sw)
200
Supreeth Herle6d66af62020-03-19 12:49:16 +0100201 def read_msisdn(self):
202 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
203 if sw == '9000':
204 return (dec_msisdn(res), sw)
205 else:
206 return (None, sw)
207
Supreeth Herlee4e98312020-03-18 11:33:14 +0100208 # Fetch all the AIDs present on UICC
209 def read_aids(self):
210 try:
211 # Find out how many records the EF.DIR has
212 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100213 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100214 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100215 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100216 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
217 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
218 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
219 except Exception as e:
220 print("Can't read AIDs from SIM -- %s" % (str(e),))
221
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100222 # Select ADF.U/ISIM in the Card using its full AID
223 def select_adf_by_aid(self, adf="usim"):
224 # Check for valid ADF name
225 if adf not in ["usim", "isim"]:
226 return None
227
228 # First (known) halves of the U/ISIM AID
229 aid_map = {}
230 aid_map["usim"] = "a0000000871002"
231 aid_map["isim"] = "a0000000871004"
232
233 for aid in self._aids:
234 if aid_map[adf] in aid:
235 (res, sw) = self._scc.select_adf(aid)
236 return sw
237
238 return None
239
Philipp Maier5c2cc662020-05-12 16:27:12 +0200240 # Erase the contents of a file
241 def erase_binary(self, ef):
242 len = self._scc.binary_size(ef)
243 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
244
245 # Erase the contents of a single record
246 def erase_record(self, ef, rec_no):
247 len = self._scc.record_size(ef)
248 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
249
Harald Welteca673942020-06-03 15:19:40 +0200250class UsimCard(Card):
251 def __init__(self, ssc):
252 super(UsimCard, self).__init__(ssc)
253
254 def read_ehplmn(self):
255 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
256 if sw == '9000':
257 return (format_xplmn(res), sw)
258 else:
259 return (None, sw)
260
261 def update_ehplmn(self, mcc, mnc):
262 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
263 size = len(data[0]) // 2
264 ehplmn = enc_plmn(mcc, mnc)
265 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
266 return sw
267
herlesupreethf8232db2020-09-29 10:03:06 +0200268 def read_epdgid(self):
269 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
270 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100271 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200272 else:
273 return (None, sw)
274
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200275 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100276 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
277 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100278 addr_type = get_addr_type(epdgid)
279 if addr_type == None:
280 raise ValueError("Unknown ePDG Id address type or invalid address provided")
281 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100282 else:
283 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200284 data, sw = self._scc.update_binary(
285 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
286 return sw
Harald Welteca673942020-06-03 15:19:40 +0200287
Supreeth Herle99d55552020-03-24 13:03:43 +0100288 def read_ePDGSelection(self):
289 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
290 if sw == '9000':
291 return (format_ePDGSelection(res), sw)
292 else:
293 return (None, sw)
294
Supreeth Herlef964df42020-03-24 13:15:37 +0100295 def update_ePDGSelection(self, mcc, mnc):
296 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
297 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
298 # Reset contents
299 # 80 - Tag value
300 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
301 elif sw == '9000':
302 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
303 return sw
304
herlesupreeth4a3580b2020-09-29 10:11:36 +0200305 def read_ust(self):
306 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
307 if sw == '9000':
308 # Print those which are available
309 return ([res, dec_st(res, table="usim")], sw)
310 else:
311 return ([None, None], sw)
312
Supreeth Herleacc222f2020-03-24 13:26:53 +0100313 def update_ust(self, service, bit=1):
314 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
315 if sw == '9000':
316 content = enc_st(res, service, bit)
317 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
318 return sw
319
herlesupreethecbada92020-12-23 09:24:29 +0100320class IsimCard(Card):
321 def __init__(self, ssc):
322 super(IsimCard, self).__init__(ssc)
323
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100324 def read_pcscf(self):
325 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
326 pcscf_recs = ""
327 for i in range(0, rec_cnt):
328 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
329 if sw == '9000':
330 content = dec_addr_tlv(res)
331 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
332 else:
333 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
334 return pcscf_recs
335
Supreeth Herlecf727f22020-03-24 17:32:21 +0100336 def update_pcscf(self, pcscf):
337 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100338 addr_type = get_addr_type(pcscf)
339 if addr_type == None:
340 raise ValueError("Unknown PCSCF address type or invalid address provided")
341 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100342 else:
343 # Just the tag value
344 content = '80'
345 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100346 pcscf_tlv = rpad(content, rec_size_bytes*2)
347 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100348 return sw
349
Supreeth Herle05b28072020-03-25 10:23:48 +0100350 def read_domain(self):
351 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
352 if sw == '9000':
353 # Skip the inital tag value ('80') byte and get length of contents
354 length = int(res[2:4], 16)
355 content = h2s(res[4:4+(length*2)])
356 return (content, sw)
357 else:
358 return (None, sw)
359
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100360 def update_domain(self, domain=None, mcc=None, mnc=None):
361 hex_str = ""
362 if domain:
363 hex_str = s2h(domain)
364 elif mcc and mnc:
365 # MCC and MNC always has 3 digits in domain form
366 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
367 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
368
369 # Build TLV
370 tlv = TLV(['80'])
371 content = tlv.build({'80': hex_str})
372
373 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
374 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
375 return sw
376
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100377 def read_impi(self):
378 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
379 if sw == '9000':
380 # Skip the inital tag value ('80') byte and get length of contents
381 length = int(res[2:4], 16)
382 content = h2s(res[4:4+(length*2)])
383 return (content, sw)
384 else:
385 return (None, sw)
386
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100387 def update_impi(self, impi=None):
388 hex_str = ""
389 if impi:
390 hex_str = s2h(impi)
391 # Build TLV
392 tlv = TLV(['80'])
393 content = tlv.build({'80': hex_str})
394
395 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
396 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
397 return sw
398
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100399 def read_impu(self):
400 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
401 impu_recs = ""
402 for i in range(0, rec_cnt):
403 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
404 if sw == '9000':
405 # Skip the inital tag value ('80') byte and get length of contents
406 length = int(res[2:4], 16)
407 content = h2s(res[4:4+(length*2)])
408 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
409 else:
410 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
411 return impu_recs
412
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100413 def update_impu(self, impu=None):
414 hex_str = ""
415 if impu:
416 hex_str = s2h(impu)
417 # Build TLV
418 tlv = TLV(['80'])
419 content = tlv.build({'80': hex_str})
420
421 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
422 impu_tlv = rpad(content, rec_size_bytes*2)
423 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
424 return sw
425
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200426 def read_iari(self):
427 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
428 uiari_recs = ""
429 for i in range(0, rec_cnt):
430 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
431 if sw == '9000':
432 # Skip the inital tag value ('80') byte and get length of contents
433 length = int(res[2:4], 16)
434 content = h2s(res[4:4+(length*2)])
435 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
436 else:
437 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
438 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100439
440class _MagicSimBase(Card):
441 """
442 Theses cards uses several record based EFs to store the provider infos,
443 each possible provider uses a specific record number in each EF. The
444 indexes used are ( where N is the number of providers supported ) :
445 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100446 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100447
448 * 3f00/7f4d/8f0c : Operator Name
449
450 bytes 0-15 : provider name, padded with 0xff
451 byte 16 : length of the provider name
452 byte 17 : 01 for valid records, 00 otherwise
453
454 * 3f00/7f4d/8f0d : Programmable Binary EFs
455
456 * 3f00/7f4d/8f0e : Programmable Record EFs
457
458 """
459
460 @classmethod
461 def autodetect(kls, scc):
462 try:
463 for p, l, t in kls._files.values():
464 if not t:
465 continue
466 if scc.record_size(['3f00', '7f4d', p]) != l:
467 return None
468 except:
469 return None
470
471 return kls(scc)
472
473 def _get_count(self):
474 """
475 Selects the file and returns the total number of entries
476 and entry size
477 """
478 f = self._files['name']
479
Harald Weltec0499c82021-01-21 16:06:50 +0100480 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100481 rec_len = int(r[-1][28:30], 16)
482 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200483 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100484
485 if (rec_cnt < 1) or (rec_len != f[1]):
486 raise RuntimeError('Bad card type')
487
488 return rec_cnt
489
490 def program(self, p):
491 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100492 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100493
494 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400495 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100496
497 # Operator name ( 3f00/7f4d/8f0c )
498 self._scc.update_record(self._files['name'][0], 2,
499 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
500 )
501
502 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
503 v = ''
504
505 # inline Ki
506 if self._ki_file is None:
507 v += p['ki']
508
509 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400510 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100511
512 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400513 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100514
515 # Ki
516 if self._ki_file:
517 v += self._ki_file + '10' + p['ki']
518
519 # PLMN_Sel
520 v+= '6f30' + '18' + rpad(hplmn, 36)
521
Alexander Chemeris21885242013-07-02 16:56:55 +0400522 # ACC
523 # This doesn't work with "fake" SuperSIM cards,
524 # but will hopefully work with real SuperSIMs.
525 if p.get('acc') is not None:
526 v+= '6f78' + '02' + lpad(p['acc'], 4)
527
Sylvain Munaut76504e02010-12-07 00:24:32 +0100528 self._scc.update_record(self._files['b_ef'][0], 1,
529 rpad(v, self._files['b_ef'][1]*2)
530 )
531
532 # SMSP ( 3f00/7f4d/8f0e )
533 # FIXME
534
535 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100536 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100537 tl = int(r[-1][4:8], 16)
538
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400539 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100540 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
541
542 def erase(self):
543 # Dummy
544 df = {}
545 for k, v in self._files.iteritems():
546 ofs = 1
547 fv = v[1] * 'ff'
548 if k == 'name':
549 ofs = 2
550 fv = fv[0:-4] + '0000'
551 df[v[0]] = (fv, ofs)
552
553 # Write
554 for n in range(0,self._get_count()):
555 for k, (msg, ofs) in df.iteritems():
556 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
557
558
559class SuperSim(_MagicSimBase):
560
561 name = 'supersim'
562
563 _files = {
564 'name' : ('8f0c', 18, True),
565 'b_ef' : ('8f0d', 74, True),
566 'r_ef' : ('8f0e', 50, True),
567 }
568
569 _ki_file = None
570
571
572class MagicSim(_MagicSimBase):
573
574 name = 'magicsim'
575
576 _files = {
577 'name' : ('8f0c', 18, True),
578 'b_ef' : ('8f0d', 130, True),
579 'r_ef' : ('8f0e', 102, False),
580 }
581
582 _ki_file = '6f1b'
583
584
585class FakeMagicSim(Card):
586 """
587 Theses cards have a record based EF 3f00/000c that contains the provider
588 informations. See the program method for its format. The records go from
589 1 to N.
590 """
591
592 name = 'fakemagicsim'
593
594 @classmethod
595 def autodetect(kls, scc):
596 try:
597 if scc.record_size(['3f00', '000c']) != 0x5a:
598 return None
599 except:
600 return None
601
602 return kls(scc)
603
604 def _get_infos(self):
605 """
606 Selects the file and returns the total number of entries
607 and entry size
608 """
609
Harald Weltec0499c82021-01-21 16:06:50 +0100610 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100611 rec_len = int(r[-1][28:30], 16)
612 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200613 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614
615 if (rec_cnt < 1) or (rec_len != 0x5a):
616 raise RuntimeError('Bad card type')
617
618 return rec_cnt, rec_len
619
620 def program(self, p):
621 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100622 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100623 tl = int(r[-1][4:8], 16)
624
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400625 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100626 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
627
628 # Get total number of entries and entry size
629 rec_cnt, rec_len = self._get_infos()
630
631 # Set first entry
632 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200633 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100634 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200635 enc_iccid(p['iccid']) + # 10b ICCID
636 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
637 p['ki'] + # 16b Ki
638 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100639 )
640 self._scc.update_record('000c', 1, entry)
641
642 def erase(self):
643 # Get total number of entries and entry size
644 rec_cnt, rec_len = self._get_infos()
645
646 # Erase all entries
647 entry = 'ff' * rec_len
648 for i in range(0, rec_cnt):
649 self._scc.update_record('000c', 1+i, entry)
650
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200651
Harald Welte3156d902011-03-22 21:48:19 +0100652class GrcardSim(Card):
653 """
654 Greencard (grcard.cn) HZCOS GSM SIM
655 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
656 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
657 """
658
659 name = 'grcardsim'
660
661 @classmethod
662 def autodetect(kls, scc):
663 return None
664
665 def program(self, p):
666 # We don't really know yet what ADM PIN 4 is about
667 #self._scc.verify_chv(4, h2b("4444444444444444"))
668
669 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100670 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200671 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100672 else:
673 pin = h2b("4444444444444444")
674 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100675
676 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100677 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400678 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100679
680 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100681 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400682 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100683
684 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400685 if p.get('acc') is not None:
686 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100687
688 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200689 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100690 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200691 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100692
693 # Set the Ki using proprietary command
694 pdu = '80d4020010' + p['ki']
695 data, sw = self._scc._tp.send_apdu(pdu)
696
697 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100698 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100699 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400700 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100701 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
702
703 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100704 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100705 size = int(r[-1][4:8], 16)
706 # FIXME
707
708 # FIXME: EF.MSISDN
709
Sylvain Munaut76504e02010-12-07 00:24:32 +0100710
Harald Weltee10394b2011-12-07 12:34:14 +0100711class SysmoSIMgr1(GrcardSim):
712 """
713 sysmocom sysmoSIM-GR1
714 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
715 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
716 """
717 name = 'sysmosim-gr1'
718
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200719 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200720 def autodetect(kls, scc):
721 try:
722 # Look for ATR
723 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
724 return kls(scc)
725 except:
726 return None
727 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200728
Harald Welteca673942020-06-03 15:19:40 +0200729class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100730 """
731 sysmocom sysmoUSIM-GR1
732 """
733 name = 'sysmoUSIM-GR1'
734
735 @classmethod
736 def autodetect(kls, scc):
737 # TODO: Access the ATR
738 return None
739
740 def program(self, p):
741 # TODO: check if verify_chv could be used or what it needs
742 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
743 # Unlock the card..
744 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
745
746 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100747 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400748 p['opc'] + # 32b OPC
749 enc_iccid(p['iccid']) + # 10b ICCID
750 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100751 )
752 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
753
Sylvain Munaut053c8952013-07-02 15:12:32 +0200754
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100755class SysmoSIMgr2(Card):
756 """
757 sysmocom sysmoSIM-GR2
758 """
759
760 name = 'sysmoSIM-GR2'
761
762 @classmethod
763 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900764 try:
765 # Look for ATR
766 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
767 return kls(scc)
768 except:
769 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100770 return None
771
772 def program(self, p):
773
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200774 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100775 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200776
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100777 # authenticate as SUPER ADM using default key
778 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
779
780 # set ADM pin using proprietary command
781 # INS: D4
782 # P1: 3A for PIN, 3B for PUK
783 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
784 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100785 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200786 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100787 else:
788 pin = h2b("4444444444444444")
789
790 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100791 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200792
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100793 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100794
795 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100796
797 # write EF.ICCID
798 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
799
800 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100801 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200802
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100803 # write EF.IMSI
804 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
805
806 # write EF.ACC
807 if p.get('acc') is not None:
808 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
809
810 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100811 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100812 size = int(r[-1][4:8], 16)
813 hplmn = enc_plmn(p['mcc'], p['mnc'])
814 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
815
816 # set COMP128 version 0 in proprietary file
817 data, sw = self._scc.update_binary('0001', '001000')
818
819 # set Ki in proprietary file
820 data, sw = self._scc.update_binary('0001', p['ki'], 3)
821
822 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100823 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200824
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100825 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200826 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200827 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100828
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100829
Harald Welteca673942020-06-03 15:19:40 +0200830class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100831 """
832 sysmocom sysmoUSIM-SJS1
833 """
834
835 name = 'sysmoUSIM-SJS1'
836
837 def __init__(self, ssc):
838 super(SysmoUSIMSJS1, self).__init__(ssc)
839 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100840 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100841
842 @classmethod
843 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900844 try:
845 # Look for ATR
846 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"):
847 return kls(scc)
848 except:
849 return None
Jan Balke3e840672015-01-26 15:36:27 +0100850 return None
851
Harald Weltea6704252021-01-08 20:19:11 +0100852 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100853 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100854 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100855 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100856 (res, sw) = self._scc.verify_chv(0x0A, key)
857 if sw != '9000':
858 raise RuntimeError('Failed to authenticate with ADM key %s'%(key))
859 return sw
860
861 def program(self, p):
862 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100863
864 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100865 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100866
Philipp Maiere9604882017-03-21 17:24:31 +0100867 # write EF.ICCID
868 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
869
Jan Balke3e840672015-01-26 15:36:27 +0100870 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100871 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100872
Jan Balke3e840672015-01-26 15:36:27 +0100873 # set Ki in proprietary file
874 data, sw = self._scc.update_binary('00FF', p['ki'])
875
Philipp Maier1be35bf2018-07-13 11:29:03 +0200876 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200877 if 'opc' in p:
878 content = "01" + p['opc']
879 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100880
Supreeth Herle7947d922019-06-08 07:50:53 +0200881 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100882 if p.get('name') is not None:
883 content = enc_spn(p['name'], True, True)
884 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200885
Supreeth Herlec8796a32019-12-23 12:23:42 +0100886 if p.get('acc') is not None:
887 self.update_acc(p['acc'])
888
Jan Balke3e840672015-01-26 15:36:27 +0100889 # write EF.IMSI
890 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
891
Philipp Maier2d15ea02019-03-20 12:40:36 +0100892 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200893 if p.get('mcc') and p.get('mnc'):
894 sw = self.update_plmnsel(p['mcc'], p['mnc'])
895 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100896 print("Programming PLMNsel failed with code %s"%sw)
897
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200898 # EF.PLMNwAcT
899 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100900 sw = self.update_plmn_act(p['mcc'], p['mnc'])
901 if sw != '9000':
902 print("Programming PLMNwAcT failed with code %s"%sw)
903
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200904 # EF.OPLMNwAcT
905 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100906 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
907 if sw != '9000':
908 print("Programming OPLMNwAcT failed with code %s"%sw)
909
Supreeth Herlef442fb42020-01-21 12:47:32 +0100910 # EF.HPLMNwAcT
911 if p.get('mcc') and p.get('mnc'):
912 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
913 if sw != '9000':
914 print("Programming HPLMNwAcT failed with code %s"%sw)
915
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200916 # EF.AD
917 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100918 sw = self.update_ad(p['mnc'])
919 if sw != '9000':
920 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100921
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200922 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200923 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100924 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200925 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100926
Supreeth Herle5a541012019-12-22 08:59:16 +0100927 # EF.MSISDN
928 # TODO: Alpha Identifier (currently 'ff'O * 20)
929 # TODO: Capability/Configuration1 Record Identifier
930 # TODO: Extension1 Record Identifier
931 if p.get('msisdn') is not None:
932 msisdn = enc_msisdn(p['msisdn'])
933 data = 'ff' * 20 + msisdn + 'ff' * 2
934
Harald Weltec0499c82021-01-21 16:06:50 +0100935 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100936 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
937
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900938
herlesupreeth4a3580b2020-09-29 10:11:36 +0200939class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900940 """
941 FairwavesSIM
942
943 The SIM card is operating according to the standard.
944 For Ki/OP/OPC programming the following files are additionally open for writing:
945 3F00/7F20/FF01 – OP/OPC:
946 byte 1 = 0x01, bytes 2-17: OPC;
947 byte 1 = 0x00, bytes 2-17: OP;
948 3F00/7F20/FF02: Ki
949 """
950
Philipp Maier5a876312019-11-11 11:01:46 +0100951 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900952 # Propriatary files
953 _EF_num = {
954 'Ki': 'FF02',
955 'OP/OPC': 'FF01',
956 }
957 _EF = {
958 'Ki': DF['GSM']+[_EF_num['Ki']],
959 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
960 }
961
962 def __init__(self, ssc):
963 super(FairwavesSIM, self).__init__(ssc)
964 self._adm_chv_num = 0x11
965 self._adm2_chv_num = 0x12
966
967
968 @classmethod
969 def autodetect(kls, scc):
970 try:
971 # Look for ATR
972 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"):
973 return kls(scc)
974 except:
975 return None
976 return None
977
978
979 def verify_adm2(self, key):
980 '''
981 Authenticate with ADM2 key.
982
983 Fairwaves SIM cards support hierarchical key structure and ADM2 key
984 is a key which has access to proprietary files (Ki and OP/OPC).
985 That said, ADM key inherits permissions of ADM2 key and thus we rarely
986 need ADM2 key per se.
987 '''
988 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
989 return sw
990
991
992 def read_ki(self):
993 """
994 Read Ki in proprietary file.
995
996 Requires ADM1 access level
997 """
998 return self._scc.read_binary(self._EF['Ki'])
999
1000
1001 def update_ki(self, ki):
1002 """
1003 Set Ki in proprietary file.
1004
1005 Requires ADM1 access level
1006 """
1007 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1008 return sw
1009
1010
1011 def read_op_opc(self):
1012 """
1013 Read Ki in proprietary file.
1014
1015 Requires ADM1 access level
1016 """
1017 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1018 type = 'OP' if ef[0:2] == '00' else 'OPC'
1019 return ((type, ef[2:]), sw)
1020
1021
1022 def update_op(self, op):
1023 """
1024 Set OP in proprietary file.
1025
1026 Requires ADM1 access level
1027 """
1028 content = '00' + op
1029 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1030 return sw
1031
1032
1033 def update_opc(self, opc):
1034 """
1035 Set OPC in proprietary file.
1036
1037 Requires ADM1 access level
1038 """
1039 content = '01' + opc
1040 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1041 return sw
1042
1043
1044 def program(self, p):
1045 # authenticate as ADM1
1046 if not p['pin_adm']:
1047 raise ValueError("Please provide a PIN-ADM as there is no default one")
1048 sw = self.verify_adm(h2b(p['pin_adm']))
1049 if sw != '9000':
1050 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1051
1052 # TODO: Set operator name
1053 if p.get('smsp') is not None:
1054 sw = self.update_smsp(p['smsp'])
1055 if sw != '9000':
1056 print("Programming SMSP failed with code %s"%sw)
1057 # This SIM doesn't support changing ICCID
1058 if p.get('mcc') is not None and p.get('mnc') is not None:
1059 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1060 if sw != '9000':
1061 print("Programming MCC/MNC failed with code %s"%sw)
1062 if p.get('imsi') is not None:
1063 sw = self.update_imsi(p['imsi'])
1064 if sw != '9000':
1065 print("Programming IMSI failed with code %s"%sw)
1066 if p.get('ki') is not None:
1067 sw = self.update_ki(p['ki'])
1068 if sw != '9000':
1069 print("Programming Ki failed with code %s"%sw)
1070 if p.get('opc') is not None:
1071 sw = self.update_opc(p['opc'])
1072 if sw != '9000':
1073 print("Programming OPC failed with code %s"%sw)
1074 if p.get('acc') is not None:
1075 sw = self.update_acc(p['acc'])
1076 if sw != '9000':
1077 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001078
Todd Neal9eeadfc2018-04-25 15:36:29 -05001079class OpenCellsSim(Card):
1080 """
1081 OpenCellsSim
1082
1083 """
1084
Philipp Maier5a876312019-11-11 11:01:46 +01001085 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001086
1087 def __init__(self, ssc):
1088 super(OpenCellsSim, self).__init__(ssc)
1089 self._adm_chv_num = 0x0A
1090
1091
1092 @classmethod
1093 def autodetect(kls, scc):
1094 try:
1095 # Look for ATR
1096 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"):
1097 return kls(scc)
1098 except:
1099 return None
1100 return None
1101
1102
1103 def program(self, p):
1104 if not p['pin_adm']:
1105 raise ValueError("Please provide a PIN-ADM as there is no default one")
1106 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1107
1108 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001109 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001110
1111 # write EF.ICCID
1112 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1113
Harald Weltec0499c82021-01-21 16:06:50 +01001114 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001115
1116 # set Ki in proprietary file
1117 data, sw = self._scc.update_binary('FF02', p['ki'])
1118
1119 # set OPC in proprietary file
1120 data, sw = self._scc.update_binary('FF01', p['opc'])
1121
1122 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001123 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001124
1125 # write EF.IMSI
1126 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1127
herlesupreeth4a3580b2020-09-29 10:11:36 +02001128class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001129 """
1130 WavemobileSim
1131
1132 """
1133
1134 name = 'Wavemobile-SIM'
1135
1136 def __init__(self, ssc):
1137 super(WavemobileSim, self).__init__(ssc)
1138 self._adm_chv_num = 0x0A
1139 self._scc.cla_byte = "00"
1140 self._scc.sel_ctrl = "0004" #request an FCP
1141
1142 @classmethod
1143 def autodetect(kls, scc):
1144 try:
1145 # Look for ATR
1146 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"):
1147 return kls(scc)
1148 except:
1149 return None
1150 return None
1151
1152 def program(self, p):
1153 if not p['pin_adm']:
1154 raise ValueError("Please provide a PIN-ADM as there is no default one")
1155 sw = self.verify_adm(h2b(p['pin_adm']))
1156 if sw != '9000':
1157 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1158
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001159 # EF.ICCID
1160 # TODO: Add programming of the ICCID
1161 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001162 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1163
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001164 # KI (Presumably a propritary file)
1165 # TODO: Add programming of KI
1166 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001167 print("Warning: Programming of the KI is not implemented for this type of card.")
1168
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001169 # OPc (Presumably a propritary file)
1170 # TODO: Add programming of OPc
1171 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001172 print("Warning: Programming of the OPc is not implemented for this type of card.")
1173
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001174 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001175 if p.get('smsp'):
1176 sw = self.update_smsp(p['smsp'])
1177 if sw != '9000':
1178 print("Programming SMSP failed with code %s"%sw)
1179
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001180 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001181 if p.get('imsi'):
1182 sw = self.update_imsi(p['imsi'])
1183 if sw != '9000':
1184 print("Programming IMSI failed with code %s"%sw)
1185
1186 # EF.ACC
1187 if p.get('acc'):
1188 sw = self.update_acc(p['acc'])
1189 if sw != '9000':
1190 print("Programming ACC failed with code %s"%sw)
1191
1192 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001193 if p.get('mcc') and p.get('mnc'):
1194 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1195 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001196 print("Programming PLMNsel failed with code %s"%sw)
1197
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001198 # EF.PLMNwAcT
1199 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001200 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1201 if sw != '9000':
1202 print("Programming PLMNwAcT failed with code %s"%sw)
1203
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001204 # EF.OPLMNwAcT
1205 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001206 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1207 if sw != '9000':
1208 print("Programming OPLMNwAcT failed with code %s"%sw)
1209
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001210 # EF.AD
1211 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001212 sw = self.update_ad(p['mnc'])
1213 if sw != '9000':
1214 print("Programming AD failed with code %s"%sw)
1215
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001216 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001217
Todd Neal9eeadfc2018-04-25 15:36:29 -05001218
herlesupreethb0c7d122020-12-23 09:25:46 +01001219class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001220 """
1221 sysmocom sysmoISIM-SJA2
1222 """
1223
1224 name = 'sysmoISIM-SJA2'
1225
1226 def __init__(self, ssc):
1227 super(SysmoISIMSJA2, self).__init__(ssc)
1228 self._scc.cla_byte = "00"
1229 self._scc.sel_ctrl = "0004" #request an FCP
1230
1231 @classmethod
1232 def autodetect(kls, scc):
1233 try:
1234 # Try card model #1
1235 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1236 if scc.get_atr() == toBytes(atr):
1237 return kls(scc)
1238
1239 # Try card model #2
1240 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1241 if scc.get_atr() == toBytes(atr):
1242 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001243
1244 # Try card model #3
1245 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1246 if scc.get_atr() == toBytes(atr):
1247 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001248 except:
1249 return None
1250 return None
1251
Harald Weltea6704252021-01-08 20:19:11 +01001252 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001253 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001254 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001255 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001256 (res, sw) = self._scc.verify_chv(0x0A, key)
1257 if sw != '9000':
1258 raise RuntimeError('Failed to authenticate with ADM key %s'%(key))
1259 return sw
1260
1261 def program(self, p):
1262 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001263
1264 # This type of card does not allow to reprogram the ICCID.
1265 # Reprogramming the ICCID would mess up the card os software
1266 # license management, so the ICCID must be kept at its factory
1267 # setting!
1268 if p.get('iccid'):
1269 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1270
1271 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001272 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001273
1274 # write EF.IMSI
1275 if p.get('imsi'):
1276 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1277
1278 # EF.PLMNsel
1279 if p.get('mcc') and p.get('mnc'):
1280 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1281 if sw != '9000':
1282 print("Programming PLMNsel failed with code %s"%sw)
1283
1284 # EF.PLMNwAcT
1285 if p.get('mcc') and p.get('mnc'):
1286 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1287 if sw != '9000':
1288 print("Programming PLMNwAcT failed with code %s"%sw)
1289
1290 # EF.OPLMNwAcT
1291 if p.get('mcc') and p.get('mnc'):
1292 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1293 if sw != '9000':
1294 print("Programming OPLMNwAcT failed with code %s"%sw)
1295
Harald Welte32f0d412020-05-05 17:35:57 +02001296 # EF.HPLMNwAcT
1297 if p.get('mcc') and p.get('mnc'):
1298 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1299 if sw != '9000':
1300 print("Programming HPLMNwAcT failed with code %s"%sw)
1301
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001302 # EF.AD
1303 if p.get('mcc') and p.get('mnc'):
1304 sw = self.update_ad(p['mnc'])
1305 if sw != '9000':
1306 print("Programming AD failed with code %s"%sw)
1307
1308 # EF.SMSP
1309 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001310 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001311 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1312
Supreeth Herlec6019232020-03-26 10:00:45 +01001313 # EF.MSISDN
1314 # TODO: Alpha Identifier (currently 'ff'O * 20)
1315 # TODO: Capability/Configuration1 Record Identifier
1316 # TODO: Extension1 Record Identifier
1317 if p.get('msisdn') is not None:
1318 msisdn = enc_msisdn(p['msisdn'])
1319 content = 'ff' * 20 + msisdn + 'ff' * 2
1320
Harald Weltec0499c82021-01-21 16:06:50 +01001321 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001322 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1323
Supreeth Herlea97944b2020-03-26 10:03:25 +01001324 # EF.ACC
1325 if p.get('acc'):
1326 sw = self.update_acc(p['acc'])
1327 if sw != '9000':
1328 print("Programming ACC failed with code %s"%sw)
1329
Supreeth Herle80164052020-03-23 12:06:29 +01001330 # Populate AIDs
1331 self.read_aids()
1332
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001333 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1334 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001335 self._scc.select_path(['3f00'])
1336 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001337 if p.get('ki'):
1338 self._scc.update_binary('6f20', p['ki'], 1)
1339 if p.get('opc'):
1340 self._scc.update_binary('6f20', p['opc'], 17)
1341
1342 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001343 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001344 if p.get('ki'):
1345 self._scc.update_binary('af20', p['ki'], 1)
1346 if p.get('opc'):
1347 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001348
Supreeth Herlecf727f22020-03-24 17:32:21 +01001349 # update EF.P-CSCF in ADF.ISIM
1350 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1351 if p.get('pcscf'):
1352 sw = self.update_pcscf(p['pcscf'])
1353 else:
1354 sw = self.update_pcscf("")
1355 if sw != '9000':
1356 print("Programming P-CSCF failed with code %s"%sw)
1357
1358
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001359 # update EF.DOMAIN in ADF.ISIM
1360 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1361 if p.get('ims_hdomain'):
1362 sw = self.update_domain(domain=p['ims_hdomain'])
1363 else:
1364 sw = self.update_domain()
1365
1366 if sw != '9000':
1367 print("Programming Home Network Domain Name failed with code %s"%sw)
1368
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001369 # update EF.IMPI in ADF.ISIM
1370 # TODO: Validate IMPI input
1371 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1372 if p.get('impi'):
1373 sw = self.update_impi(p['impi'])
1374 else:
1375 sw = self.update_impi()
1376 if sw != '9000':
1377 print("Programming IMPI failed with code %s"%sw)
1378
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001379 # update EF.IMPU in ADF.ISIM
1380 # TODO: Validate IMPU input
1381 # Support multiple IMPU if there is enough space
1382 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1383 if p.get('impu'):
1384 sw = self.update_impu(p['impu'])
1385 else:
1386 sw = self.update_impu()
1387 if sw != '9000':
1388 print("Programming IMPU failed with code %s"%sw)
1389
herlesupreeth1a13c442020-09-11 21:16:51 +02001390 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001391 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001392 if p.get('ki'):
1393 self._scc.update_binary('af20', p['ki'], 1)
1394 if p.get('opc'):
1395 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001396
Harald Welteca673942020-06-03 15:19:40 +02001397 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001398 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001399 if p.get('mcc') and p.get('mnc'):
1400 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1401 if sw != '9000':
1402 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001403
1404 # update EF.ePDGId in ADF.USIM
1405 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1406 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001407 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001408 else:
1409 sw = self.update_epdgid("")
1410 if sw != '9000':
1411 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001412
Supreeth Herlef964df42020-03-24 13:15:37 +01001413 # update EF.ePDGSelection in ADF.USIM
1414 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1415 if p.get('epdgSelection'):
1416 epdg_plmn = p['epdgSelection']
1417 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1418 else:
1419 sw = self.update_ePDGSelection("", "")
1420 if sw != '9000':
1421 print("Programming ePDGSelection failed with code %s"%sw)
1422
1423
Supreeth Herleacc222f2020-03-24 13:26:53 +01001424 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1425 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001426 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001427 if self.file_exists(EF_USIM_ADF_map['UST']):
1428 if p.get('epdgSelection') and p.get('epdgid'):
1429 sw = self.update_ust(106, 1)
1430 if sw != '9000':
1431 print("Programming UST failed with code %s"%sw)
1432 sw = self.update_ust(107, 1)
1433 if sw != '9000':
1434 print("Programming UST failed with code %s"%sw)
1435
Supreeth Herle44e04622020-03-25 10:34:28 +01001436 sw = self.update_ust(95, 0)
1437 if sw != '9000':
1438 print("Programming UST failed with code %s"%sw)
1439 sw = self.update_ust(99, 0)
1440 if sw != '9000':
1441 print("Programming UST failed with code %s"%sw)
1442 sw = self.update_ust(115, 0)
1443 if sw != '9000':
1444 print("Programming UST failed with code %s"%sw)
1445
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001446 return
1447
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001448
Todd Neal9eeadfc2018-04-25 15:36:29 -05001449# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001450_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001451 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001452 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001453
1454def card_autodetect(scc):
1455 for kls in _cards_classes:
1456 card = kls.autodetect(scc)
1457 if card is not None:
1458 card.reset()
1459 return card
1460 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001461
1462def card_detect(ctype, scc):
1463 # Detect type if needed
1464 card = None
1465 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1466
1467 if ctype in ("auto", "auto_once"):
1468 for kls in _cards_classes:
1469 card = kls.autodetect(scc)
1470 if card:
1471 print("Autodetected card type: %s" % card.name)
1472 card.reset()
1473 break
1474
1475 if card is None:
1476 print("Autodetection failed")
1477 return None
1478
1479 if ctype == "auto_once":
1480 ctype = card.name
1481
1482 elif ctype in ctypes:
1483 card = ctypes[ctype](scc)
1484
1485 else:
1486 raise ValueError("Unknown card type: %s" % ctype)
1487
1488 return card