blob: 8489c9711c6d7f662f05a01f3156e1828a1b61c9 [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
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
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)
178 raw_bin_data = h2b(raw_hex_data)
179 abstract_data = ad.decode_bin(raw_bin_data)
180
181 # perform updates
182 if mnc:
183 mnclen = len(str(mnc))
184 if mnclen == 1:
185 mnclen = 2
186 if mnclen > 3:
187 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
188 abstract_data['len_of_mnc_in_imsi'] = mnclen
189 if opmode:
190 opmode_symb = ad.OP_MODE.get(int(opmode, 16))
191 if opmode_symb:
192 abstract_data['ms_operation_mode'] = opmode_symb
193 else:
194 raise RuntimeError('invalid opmode "{}"'.format(opmode))
195 if ofm:
196 abstract_data['specific_facilities']['ofm'] = bool(int(ofm, 16))
197
198 # write to card
199 raw_bin_data = ad.encode_bin(abstract_data)
200 raw_hex_data = b2h(raw_bin_data)
201 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100202 return sw
203
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300204 def read_spn(self):
205 (spn, sw) = self._scc.read_binary(EF['SPN'])
206 if sw == '9000':
207 return (dec_spn(spn), sw)
208 else:
209 return (None, sw)
210
211 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
212 content = enc_spn(name, hplmn_disp, oplmn_disp)
213 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
214 return sw
215
Supreeth Herled21349a2020-04-01 08:37:47 +0200216 def read_binary(self, ef, length=None, offset=0):
217 ef_path = ef in EF and EF[ef] or ef
218 return self._scc.read_binary(ef_path, length, offset)
219
Supreeth Herlead10d662020-04-01 08:43:08 +0200220 def read_record(self, ef, rec_no):
221 ef_path = ef in EF and EF[ef] or ef
222 return self._scc.read_record(ef_path, rec_no)
223
Supreeth Herle98a69272020-03-18 12:14:48 +0100224 def read_gid1(self):
225 (res, sw) = self._scc.read_binary(EF['GID1'])
226 if sw == '9000':
227 return (res, sw)
228 else:
229 return (None, sw)
230
Supreeth Herle6d66af62020-03-19 12:49:16 +0100231 def read_msisdn(self):
232 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
233 if sw == '9000':
234 return (dec_msisdn(res), sw)
235 else:
236 return (None, sw)
237
Supreeth Herlee4e98312020-03-18 11:33:14 +0100238 # Fetch all the AIDs present on UICC
239 def read_aids(self):
Philipp Maier1e896f32021-03-10 17:02:53 +0100240 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100241 try:
242 # Find out how many records the EF.DIR has
243 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100244 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100245 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100246 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100247 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
248 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
249 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
250 except Exception as e:
251 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100252 self._aids = []
253 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100254
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100255 # Select ADF.U/ISIM in the Card using its full AID
256 def select_adf_by_aid(self, adf="usim"):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100257 # Find full AID by partial AID:
258 if is_hex(adf):
259 for aid in self._aids:
260 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
261 return self._scc.select_adf(aid)
262 # Find full AID by application name:
263 elif adf in ["usim", "isim"]:
264 # First (known) halves of the U/ISIM AID
265 aid_map = {}
266 aid_map["usim"] = "a0000000871002"
267 aid_map["isim"] = "a0000000871004"
268 for aid in self._aids:
269 if aid_map[adf] in aid:
270 return self._scc.select_adf(aid)
271 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100272
Philipp Maier5c2cc662020-05-12 16:27:12 +0200273 # Erase the contents of a file
274 def erase_binary(self, ef):
275 len = self._scc.binary_size(ef)
276 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
277
278 # Erase the contents of a single record
279 def erase_record(self, ef, rec_no):
280 len = self._scc.record_size(ef)
281 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
282
Harald Welteca673942020-06-03 15:19:40 +0200283class UsimCard(Card):
284 def __init__(self, ssc):
285 super(UsimCard, self).__init__(ssc)
286
287 def read_ehplmn(self):
288 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
289 if sw == '9000':
290 return (format_xplmn(res), sw)
291 else:
292 return (None, sw)
293
294 def update_ehplmn(self, mcc, mnc):
295 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
296 size = len(data[0]) // 2
297 ehplmn = enc_plmn(mcc, mnc)
298 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
299 return sw
300
herlesupreethf8232db2020-09-29 10:03:06 +0200301 def read_epdgid(self):
302 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
303 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100304 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200305 else:
306 return (None, sw)
307
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200308 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100309 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
310 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100311 addr_type = get_addr_type(epdgid)
312 if addr_type == None:
313 raise ValueError("Unknown ePDG Id address type or invalid address provided")
314 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100315 else:
316 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200317 data, sw = self._scc.update_binary(
318 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
319 return sw
Harald Welteca673942020-06-03 15:19:40 +0200320
Supreeth Herle99d55552020-03-24 13:03:43 +0100321 def read_ePDGSelection(self):
322 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
323 if sw == '9000':
324 return (format_ePDGSelection(res), sw)
325 else:
326 return (None, sw)
327
Supreeth Herlef964df42020-03-24 13:15:37 +0100328 def update_ePDGSelection(self, mcc, mnc):
329 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
330 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
331 # Reset contents
332 # 80 - Tag value
333 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
334 elif sw == '9000':
335 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
336 return sw
337
herlesupreeth4a3580b2020-09-29 10:11:36 +0200338 def read_ust(self):
339 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
340 if sw == '9000':
341 # Print those which are available
342 return ([res, dec_st(res, table="usim")], sw)
343 else:
344 return ([None, None], sw)
345
Supreeth Herleacc222f2020-03-24 13:26:53 +0100346 def update_ust(self, service, bit=1):
347 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
348 if sw == '9000':
349 content = enc_st(res, service, bit)
350 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
351 return sw
352
herlesupreethecbada92020-12-23 09:24:29 +0100353class IsimCard(Card):
354 def __init__(self, ssc):
355 super(IsimCard, self).__init__(ssc)
356
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100357 def read_pcscf(self):
358 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
359 pcscf_recs = ""
360 for i in range(0, rec_cnt):
361 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
362 if sw == '9000':
363 content = dec_addr_tlv(res)
364 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
365 else:
366 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
367 return pcscf_recs
368
Supreeth Herlecf727f22020-03-24 17:32:21 +0100369 def update_pcscf(self, pcscf):
370 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100371 addr_type = get_addr_type(pcscf)
372 if addr_type == None:
373 raise ValueError("Unknown PCSCF address type or invalid address provided")
374 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100375 else:
376 # Just the tag value
377 content = '80'
378 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100379 pcscf_tlv = rpad(content, rec_size_bytes*2)
380 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100381 return sw
382
Supreeth Herle05b28072020-03-25 10:23:48 +0100383 def read_domain(self):
384 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
385 if sw == '9000':
386 # Skip the inital tag value ('80') byte and get length of contents
387 length = int(res[2:4], 16)
388 content = h2s(res[4:4+(length*2)])
389 return (content, sw)
390 else:
391 return (None, sw)
392
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100393 def update_domain(self, domain=None, mcc=None, mnc=None):
394 hex_str = ""
395 if domain:
396 hex_str = s2h(domain)
397 elif mcc and mnc:
398 # MCC and MNC always has 3 digits in domain form
399 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
400 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
401
402 # Build TLV
403 tlv = TLV(['80'])
404 content = tlv.build({'80': hex_str})
405
406 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
407 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
408 return sw
409
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100410 def read_impi(self):
411 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
412 if sw == '9000':
413 # Skip the inital tag value ('80') byte and get length of contents
414 length = int(res[2:4], 16)
415 content = h2s(res[4:4+(length*2)])
416 return (content, sw)
417 else:
418 return (None, sw)
419
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100420 def update_impi(self, impi=None):
421 hex_str = ""
422 if impi:
423 hex_str = s2h(impi)
424 # Build TLV
425 tlv = TLV(['80'])
426 content = tlv.build({'80': hex_str})
427
428 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
429 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
430 return sw
431
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100432 def read_impu(self):
433 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
434 impu_recs = ""
435 for i in range(0, rec_cnt):
436 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
437 if sw == '9000':
438 # Skip the inital tag value ('80') byte and get length of contents
439 length = int(res[2:4], 16)
440 content = h2s(res[4:4+(length*2)])
441 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
442 else:
443 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
444 return impu_recs
445
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100446 def update_impu(self, impu=None):
447 hex_str = ""
448 if impu:
449 hex_str = s2h(impu)
450 # Build TLV
451 tlv = TLV(['80'])
452 content = tlv.build({'80': hex_str})
453
454 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
455 impu_tlv = rpad(content, rec_size_bytes*2)
456 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
457 return sw
458
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200459 def read_iari(self):
460 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
461 uiari_recs = ""
462 for i in range(0, rec_cnt):
463 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
464 if sw == '9000':
465 # Skip the inital tag value ('80') byte and get length of contents
466 length = int(res[2:4], 16)
467 content = h2s(res[4:4+(length*2)])
468 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
469 else:
470 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
471 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100472
473class _MagicSimBase(Card):
474 """
475 Theses cards uses several record based EFs to store the provider infos,
476 each possible provider uses a specific record number in each EF. The
477 indexes used are ( where N is the number of providers supported ) :
478 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100479 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100480
481 * 3f00/7f4d/8f0c : Operator Name
482
483 bytes 0-15 : provider name, padded with 0xff
484 byte 16 : length of the provider name
485 byte 17 : 01 for valid records, 00 otherwise
486
487 * 3f00/7f4d/8f0d : Programmable Binary EFs
488
489 * 3f00/7f4d/8f0e : Programmable Record EFs
490
491 """
492
493 @classmethod
494 def autodetect(kls, scc):
495 try:
496 for p, l, t in kls._files.values():
497 if not t:
498 continue
499 if scc.record_size(['3f00', '7f4d', p]) != l:
500 return None
501 except:
502 return None
503
504 return kls(scc)
505
506 def _get_count(self):
507 """
508 Selects the file and returns the total number of entries
509 and entry size
510 """
511 f = self._files['name']
512
Harald Weltec0499c82021-01-21 16:06:50 +0100513 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100514 rec_len = int(r[-1][28:30], 16)
515 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200516 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100517
518 if (rec_cnt < 1) or (rec_len != f[1]):
519 raise RuntimeError('Bad card type')
520
521 return rec_cnt
522
523 def program(self, p):
524 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100525 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100526
527 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400528 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100529
530 # Operator name ( 3f00/7f4d/8f0c )
531 self._scc.update_record(self._files['name'][0], 2,
532 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
533 )
534
535 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
536 v = ''
537
538 # inline Ki
539 if self._ki_file is None:
540 v += p['ki']
541
542 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400543 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100544
545 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400546 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100547
548 # Ki
549 if self._ki_file:
550 v += self._ki_file + '10' + p['ki']
551
552 # PLMN_Sel
553 v+= '6f30' + '18' + rpad(hplmn, 36)
554
Alexander Chemeris21885242013-07-02 16:56:55 +0400555 # ACC
556 # This doesn't work with "fake" SuperSIM cards,
557 # but will hopefully work with real SuperSIMs.
558 if p.get('acc') is not None:
559 v+= '6f78' + '02' + lpad(p['acc'], 4)
560
Sylvain Munaut76504e02010-12-07 00:24:32 +0100561 self._scc.update_record(self._files['b_ef'][0], 1,
562 rpad(v, self._files['b_ef'][1]*2)
563 )
564
565 # SMSP ( 3f00/7f4d/8f0e )
566 # FIXME
567
568 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100569 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100570 tl = int(r[-1][4:8], 16)
571
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400572 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100573 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
574
575 def erase(self):
576 # Dummy
577 df = {}
578 for k, v in self._files.iteritems():
579 ofs = 1
580 fv = v[1] * 'ff'
581 if k == 'name':
582 ofs = 2
583 fv = fv[0:-4] + '0000'
584 df[v[0]] = (fv, ofs)
585
586 # Write
587 for n in range(0,self._get_count()):
588 for k, (msg, ofs) in df.iteritems():
589 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
590
591
592class SuperSim(_MagicSimBase):
593
594 name = 'supersim'
595
596 _files = {
597 'name' : ('8f0c', 18, True),
598 'b_ef' : ('8f0d', 74, True),
599 'r_ef' : ('8f0e', 50, True),
600 }
601
602 _ki_file = None
603
604
605class MagicSim(_MagicSimBase):
606
607 name = 'magicsim'
608
609 _files = {
610 'name' : ('8f0c', 18, True),
611 'b_ef' : ('8f0d', 130, True),
612 'r_ef' : ('8f0e', 102, False),
613 }
614
615 _ki_file = '6f1b'
616
617
618class FakeMagicSim(Card):
619 """
620 Theses cards have a record based EF 3f00/000c that contains the provider
621 informations. See the program method for its format. The records go from
622 1 to N.
623 """
624
625 name = 'fakemagicsim'
626
627 @classmethod
628 def autodetect(kls, scc):
629 try:
630 if scc.record_size(['3f00', '000c']) != 0x5a:
631 return None
632 except:
633 return None
634
635 return kls(scc)
636
637 def _get_infos(self):
638 """
639 Selects the file and returns the total number of entries
640 and entry size
641 """
642
Harald Weltec0499c82021-01-21 16:06:50 +0100643 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100644 rec_len = int(r[-1][28:30], 16)
645 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200646 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100647
648 if (rec_cnt < 1) or (rec_len != 0x5a):
649 raise RuntimeError('Bad card type')
650
651 return rec_cnt, rec_len
652
653 def program(self, p):
654 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100655 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100656 tl = int(r[-1][4:8], 16)
657
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400658 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100659 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
660
661 # Get total number of entries and entry size
662 rec_cnt, rec_len = self._get_infos()
663
664 # Set first entry
665 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200666 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100667 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200668 enc_iccid(p['iccid']) + # 10b ICCID
669 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
670 p['ki'] + # 16b Ki
671 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100672 )
673 self._scc.update_record('000c', 1, entry)
674
675 def erase(self):
676 # Get total number of entries and entry size
677 rec_cnt, rec_len = self._get_infos()
678
679 # Erase all entries
680 entry = 'ff' * rec_len
681 for i in range(0, rec_cnt):
682 self._scc.update_record('000c', 1+i, entry)
683
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200684
Harald Welte3156d902011-03-22 21:48:19 +0100685class GrcardSim(Card):
686 """
687 Greencard (grcard.cn) HZCOS GSM SIM
688 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
689 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
690 """
691
692 name = 'grcardsim'
693
694 @classmethod
695 def autodetect(kls, scc):
696 return None
697
698 def program(self, p):
699 # We don't really know yet what ADM PIN 4 is about
700 #self._scc.verify_chv(4, h2b("4444444444444444"))
701
702 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100703 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200704 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100705 else:
706 pin = h2b("4444444444444444")
707 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100708
709 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100710 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400711 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100712
713 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100714 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400715 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100716
717 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400718 if p.get('acc') is not None:
719 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100720
721 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200722 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100723 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200724 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100725
726 # Set the Ki using proprietary command
727 pdu = '80d4020010' + p['ki']
728 data, sw = self._scc._tp.send_apdu(pdu)
729
730 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100731 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100732 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400733 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100734 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
735
736 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100737 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100738 size = int(r[-1][4:8], 16)
739 # FIXME
740
741 # FIXME: EF.MSISDN
742
Sylvain Munaut76504e02010-12-07 00:24:32 +0100743
Harald Weltee10394b2011-12-07 12:34:14 +0100744class SysmoSIMgr1(GrcardSim):
745 """
746 sysmocom sysmoSIM-GR1
747 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
748 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
749 """
750 name = 'sysmosim-gr1'
751
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200752 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200753 def autodetect(kls, scc):
754 try:
755 # Look for ATR
756 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
757 return kls(scc)
758 except:
759 return None
760 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200761
Harald Welteca673942020-06-03 15:19:40 +0200762class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100763 """
764 sysmocom sysmoUSIM-GR1
765 """
766 name = 'sysmoUSIM-GR1'
767
768 @classmethod
769 def autodetect(kls, scc):
770 # TODO: Access the ATR
771 return None
772
773 def program(self, p):
774 # TODO: check if verify_chv could be used or what it needs
775 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
776 # Unlock the card..
777 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
778
779 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100780 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400781 p['opc'] + # 32b OPC
782 enc_iccid(p['iccid']) + # 10b ICCID
783 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100784 )
785 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
786
Sylvain Munaut053c8952013-07-02 15:12:32 +0200787
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100788class SysmoSIMgr2(Card):
789 """
790 sysmocom sysmoSIM-GR2
791 """
792
793 name = 'sysmoSIM-GR2'
794
795 @classmethod
796 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900797 try:
798 # Look for ATR
799 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
800 return kls(scc)
801 except:
802 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100803 return None
804
805 def program(self, p):
806
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200807 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100808 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200809
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100810 # authenticate as SUPER ADM using default key
811 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
812
813 # set ADM pin using proprietary command
814 # INS: D4
815 # P1: 3A for PIN, 3B for PUK
816 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
817 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100818 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200819 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100820 else:
821 pin = h2b("4444444444444444")
822
823 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100824 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200825
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100826 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100827
828 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100829
830 # write EF.ICCID
831 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
832
833 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100834 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200835
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100836 # write EF.IMSI
837 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
838
839 # write EF.ACC
840 if p.get('acc') is not None:
841 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
842
843 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100844 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100845 size = int(r[-1][4:8], 16)
846 hplmn = enc_plmn(p['mcc'], p['mnc'])
847 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
848
849 # set COMP128 version 0 in proprietary file
850 data, sw = self._scc.update_binary('0001', '001000')
851
852 # set Ki in proprietary file
853 data, sw = self._scc.update_binary('0001', p['ki'], 3)
854
855 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100856 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200857
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100858 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200859 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200860 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100861
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100862
Harald Welteca673942020-06-03 15:19:40 +0200863class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100864 """
865 sysmocom sysmoUSIM-SJS1
866 """
867
868 name = 'sysmoUSIM-SJS1'
869
870 def __init__(self, ssc):
871 super(SysmoUSIMSJS1, self).__init__(ssc)
872 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100873 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100874
875 @classmethod
876 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900877 try:
878 # Look for ATR
879 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"):
880 return kls(scc)
881 except:
882 return None
Jan Balke3e840672015-01-26 15:36:27 +0100883 return None
884
Harald Weltea6704252021-01-08 20:19:11 +0100885 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100886 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100887 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100888 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100889 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100890 return sw
891
892 def program(self, p):
893 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100894
895 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100896 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100897
Philipp Maiere9604882017-03-21 17:24:31 +0100898 # write EF.ICCID
899 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
900
Jan Balke3e840672015-01-26 15:36:27 +0100901 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100902 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100903
Jan Balke3e840672015-01-26 15:36:27 +0100904 # set Ki in proprietary file
905 data, sw = self._scc.update_binary('00FF', p['ki'])
906
Philipp Maier1be35bf2018-07-13 11:29:03 +0200907 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200908 if 'opc' in p:
909 content = "01" + p['opc']
910 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100911
Supreeth Herle7947d922019-06-08 07:50:53 +0200912 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100913 if p.get('name') is not None:
914 content = enc_spn(p['name'], True, True)
915 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200916
Supreeth Herlec8796a32019-12-23 12:23:42 +0100917 if p.get('acc') is not None:
918 self.update_acc(p['acc'])
919
Jan Balke3e840672015-01-26 15:36:27 +0100920 # write EF.IMSI
921 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
922
Philipp Maier2d15ea02019-03-20 12:40:36 +0100923 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200924 if p.get('mcc') and p.get('mnc'):
925 sw = self.update_plmnsel(p['mcc'], p['mnc'])
926 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100927 print("Programming PLMNsel failed with code %s"%sw)
928
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200929 # EF.PLMNwAcT
930 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100931 sw = self.update_plmn_act(p['mcc'], p['mnc'])
932 if sw != '9000':
933 print("Programming PLMNwAcT failed with code %s"%sw)
934
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200935 # EF.OPLMNwAcT
936 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100937 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
938 if sw != '9000':
939 print("Programming OPLMNwAcT failed with code %s"%sw)
940
Supreeth Herlef442fb42020-01-21 12:47:32 +0100941 # EF.HPLMNwAcT
942 if p.get('mcc') and p.get('mnc'):
943 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
944 if sw != '9000':
945 print("Programming HPLMNwAcT failed with code %s"%sw)
946
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200947 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100948 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
949 if p.get('mcc') and p.get('mnc'):
950 mnc = p['mnc']
951 else:
952 mnc = None
953 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +0100954 if sw != '9000':
955 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100956
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200957 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200958 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100959 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200960 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100961
Supreeth Herle5a541012019-12-22 08:59:16 +0100962 # EF.MSISDN
963 # TODO: Alpha Identifier (currently 'ff'O * 20)
964 # TODO: Capability/Configuration1 Record Identifier
965 # TODO: Extension1 Record Identifier
966 if p.get('msisdn') is not None:
967 msisdn = enc_msisdn(p['msisdn'])
968 data = 'ff' * 20 + msisdn + 'ff' * 2
969
Harald Weltec0499c82021-01-21 16:06:50 +0100970 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100971 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
972
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900973
herlesupreeth4a3580b2020-09-29 10:11:36 +0200974class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900975 """
976 FairwavesSIM
977
978 The SIM card is operating according to the standard.
979 For Ki/OP/OPC programming the following files are additionally open for writing:
980 3F00/7F20/FF01 – OP/OPC:
981 byte 1 = 0x01, bytes 2-17: OPC;
982 byte 1 = 0x00, bytes 2-17: OP;
983 3F00/7F20/FF02: Ki
984 """
985
Philipp Maier5a876312019-11-11 11:01:46 +0100986 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900987 # Propriatary files
988 _EF_num = {
989 'Ki': 'FF02',
990 'OP/OPC': 'FF01',
991 }
992 _EF = {
993 'Ki': DF['GSM']+[_EF_num['Ki']],
994 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
995 }
996
997 def __init__(self, ssc):
998 super(FairwavesSIM, self).__init__(ssc)
999 self._adm_chv_num = 0x11
1000 self._adm2_chv_num = 0x12
1001
1002
1003 @classmethod
1004 def autodetect(kls, scc):
1005 try:
1006 # Look for ATR
1007 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"):
1008 return kls(scc)
1009 except:
1010 return None
1011 return None
1012
1013
1014 def verify_adm2(self, key):
1015 '''
1016 Authenticate with ADM2 key.
1017
1018 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1019 is a key which has access to proprietary files (Ki and OP/OPC).
1020 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1021 need ADM2 key per se.
1022 '''
1023 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1024 return sw
1025
1026
1027 def read_ki(self):
1028 """
1029 Read Ki in proprietary file.
1030
1031 Requires ADM1 access level
1032 """
1033 return self._scc.read_binary(self._EF['Ki'])
1034
1035
1036 def update_ki(self, ki):
1037 """
1038 Set Ki in proprietary file.
1039
1040 Requires ADM1 access level
1041 """
1042 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1043 return sw
1044
1045
1046 def read_op_opc(self):
1047 """
1048 Read Ki in proprietary file.
1049
1050 Requires ADM1 access level
1051 """
1052 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1053 type = 'OP' if ef[0:2] == '00' else 'OPC'
1054 return ((type, ef[2:]), sw)
1055
1056
1057 def update_op(self, op):
1058 """
1059 Set OP in proprietary file.
1060
1061 Requires ADM1 access level
1062 """
1063 content = '00' + op
1064 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1065 return sw
1066
1067
1068 def update_opc(self, opc):
1069 """
1070 Set OPC in proprietary file.
1071
1072 Requires ADM1 access level
1073 """
1074 content = '01' + opc
1075 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1076 return sw
1077
1078
1079 def program(self, p):
1080 # authenticate as ADM1
1081 if not p['pin_adm']:
1082 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001083 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001084
1085 # TODO: Set operator name
1086 if p.get('smsp') is not None:
1087 sw = self.update_smsp(p['smsp'])
1088 if sw != '9000':
1089 print("Programming SMSP failed with code %s"%sw)
1090 # This SIM doesn't support changing ICCID
1091 if p.get('mcc') is not None and p.get('mnc') is not None:
1092 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1093 if sw != '9000':
1094 print("Programming MCC/MNC failed with code %s"%sw)
1095 if p.get('imsi') is not None:
1096 sw = self.update_imsi(p['imsi'])
1097 if sw != '9000':
1098 print("Programming IMSI failed with code %s"%sw)
1099 if p.get('ki') is not None:
1100 sw = self.update_ki(p['ki'])
1101 if sw != '9000':
1102 print("Programming Ki failed with code %s"%sw)
1103 if p.get('opc') is not None:
1104 sw = self.update_opc(p['opc'])
1105 if sw != '9000':
1106 print("Programming OPC failed with code %s"%sw)
1107 if p.get('acc') is not None:
1108 sw = self.update_acc(p['acc'])
1109 if sw != '9000':
1110 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001111
Todd Neal9eeadfc2018-04-25 15:36:29 -05001112class OpenCellsSim(Card):
1113 """
1114 OpenCellsSim
1115
1116 """
1117
Philipp Maier5a876312019-11-11 11:01:46 +01001118 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001119
1120 def __init__(self, ssc):
1121 super(OpenCellsSim, self).__init__(ssc)
1122 self._adm_chv_num = 0x0A
1123
1124
1125 @classmethod
1126 def autodetect(kls, scc):
1127 try:
1128 # Look for ATR
1129 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"):
1130 return kls(scc)
1131 except:
1132 return None
1133 return None
1134
1135
1136 def program(self, p):
1137 if not p['pin_adm']:
1138 raise ValueError("Please provide a PIN-ADM as there is no default one")
1139 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1140
1141 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001142 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001143
1144 # write EF.ICCID
1145 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1146
Harald Weltec0499c82021-01-21 16:06:50 +01001147 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001148
1149 # set Ki in proprietary file
1150 data, sw = self._scc.update_binary('FF02', p['ki'])
1151
1152 # set OPC in proprietary file
1153 data, sw = self._scc.update_binary('FF01', p['opc'])
1154
1155 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001156 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001157
1158 # write EF.IMSI
1159 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1160
herlesupreeth4a3580b2020-09-29 10:11:36 +02001161class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001162 """
1163 WavemobileSim
1164
1165 """
1166
1167 name = 'Wavemobile-SIM'
1168
1169 def __init__(self, ssc):
1170 super(WavemobileSim, self).__init__(ssc)
1171 self._adm_chv_num = 0x0A
1172 self._scc.cla_byte = "00"
1173 self._scc.sel_ctrl = "0004" #request an FCP
1174
1175 @classmethod
1176 def autodetect(kls, scc):
1177 try:
1178 # Look for ATR
1179 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"):
1180 return kls(scc)
1181 except:
1182 return None
1183 return None
1184
1185 def program(self, p):
1186 if not p['pin_adm']:
1187 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001188 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001189
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001190 # EF.ICCID
1191 # TODO: Add programming of the ICCID
1192 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001193 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1194
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001195 # KI (Presumably a propritary file)
1196 # TODO: Add programming of KI
1197 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001198 print("Warning: Programming of the KI is not implemented for this type of card.")
1199
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001200 # OPc (Presumably a propritary file)
1201 # TODO: Add programming of OPc
1202 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001203 print("Warning: Programming of the OPc is not implemented for this type of card.")
1204
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001205 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001206 if p.get('smsp'):
1207 sw = self.update_smsp(p['smsp'])
1208 if sw != '9000':
1209 print("Programming SMSP failed with code %s"%sw)
1210
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001211 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001212 if p.get('imsi'):
1213 sw = self.update_imsi(p['imsi'])
1214 if sw != '9000':
1215 print("Programming IMSI failed with code %s"%sw)
1216
1217 # EF.ACC
1218 if p.get('acc'):
1219 sw = self.update_acc(p['acc'])
1220 if sw != '9000':
1221 print("Programming ACC failed with code %s"%sw)
1222
1223 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001224 if p.get('mcc') and p.get('mnc'):
1225 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1226 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001227 print("Programming PLMNsel failed with code %s"%sw)
1228
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001229 # EF.PLMNwAcT
1230 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001231 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1232 if sw != '9000':
1233 print("Programming PLMNwAcT failed with code %s"%sw)
1234
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001235 # EF.OPLMNwAcT
1236 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001237 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1238 if sw != '9000':
1239 print("Programming OPLMNwAcT failed with code %s"%sw)
1240
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001241 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001242 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1243 if p.get('mcc') and p.get('mnc'):
1244 mnc = p['mnc']
1245 else:
1246 mnc = None
1247 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001248 if sw != '9000':
1249 print("Programming AD failed with code %s"%sw)
1250
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001251 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001252
Todd Neal9eeadfc2018-04-25 15:36:29 -05001253
herlesupreethb0c7d122020-12-23 09:25:46 +01001254class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001255 """
1256 sysmocom sysmoISIM-SJA2
1257 """
1258
1259 name = 'sysmoISIM-SJA2'
1260
1261 def __init__(self, ssc):
1262 super(SysmoISIMSJA2, self).__init__(ssc)
1263 self._scc.cla_byte = "00"
1264 self._scc.sel_ctrl = "0004" #request an FCP
1265
1266 @classmethod
1267 def autodetect(kls, scc):
1268 try:
1269 # Try card model #1
1270 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1271 if scc.get_atr() == toBytes(atr):
1272 return kls(scc)
1273
1274 # Try card model #2
1275 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1276 if scc.get_atr() == toBytes(atr):
1277 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001278
1279 # Try card model #3
1280 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1281 if scc.get_atr() == toBytes(atr):
1282 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001283 except:
1284 return None
1285 return None
1286
Harald Weltea6704252021-01-08 20:19:11 +01001287 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001288 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001289 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001290 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001291 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001292 return sw
1293
1294 def program(self, p):
1295 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001296
1297 # This type of card does not allow to reprogram the ICCID.
1298 # Reprogramming the ICCID would mess up the card os software
1299 # license management, so the ICCID must be kept at its factory
1300 # setting!
1301 if p.get('iccid'):
1302 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1303
1304 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001305 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001306
Robert Falkenberg54595362021-04-06 12:04:34 +02001307 # set Service Provider Name
1308 if p.get('name') is not None:
1309 content = enc_spn(p['name'], True, True)
1310 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
1311
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001312 # write EF.IMSI
1313 if p.get('imsi'):
1314 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1315
1316 # EF.PLMNsel
1317 if p.get('mcc') and p.get('mnc'):
1318 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1319 if sw != '9000':
1320 print("Programming PLMNsel failed with code %s"%sw)
1321
1322 # EF.PLMNwAcT
1323 if p.get('mcc') and p.get('mnc'):
1324 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1325 if sw != '9000':
1326 print("Programming PLMNwAcT failed with code %s"%sw)
1327
1328 # EF.OPLMNwAcT
1329 if p.get('mcc') and p.get('mnc'):
1330 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1331 if sw != '9000':
1332 print("Programming OPLMNwAcT failed with code %s"%sw)
1333
Harald Welte32f0d412020-05-05 17:35:57 +02001334 # EF.HPLMNwAcT
1335 if p.get('mcc') and p.get('mnc'):
1336 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1337 if sw != '9000':
1338 print("Programming HPLMNwAcT failed with code %s"%sw)
1339
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001340 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001341 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1342 if p.get('mcc') and p.get('mnc'):
1343 mnc = p['mnc']
1344 else:
1345 mnc = None
1346 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001347 if sw != '9000':
1348 print("Programming AD failed with code %s"%sw)
1349
1350 # EF.SMSP
1351 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001352 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001353 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1354
Supreeth Herlec6019232020-03-26 10:00:45 +01001355 # EF.MSISDN
1356 # TODO: Alpha Identifier (currently 'ff'O * 20)
1357 # TODO: Capability/Configuration1 Record Identifier
1358 # TODO: Extension1 Record Identifier
1359 if p.get('msisdn') is not None:
1360 msisdn = enc_msisdn(p['msisdn'])
1361 content = 'ff' * 20 + msisdn + 'ff' * 2
1362
Harald Weltec0499c82021-01-21 16:06:50 +01001363 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001364 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1365
Supreeth Herlea97944b2020-03-26 10:03:25 +01001366 # EF.ACC
1367 if p.get('acc'):
1368 sw = self.update_acc(p['acc'])
1369 if sw != '9000':
1370 print("Programming ACC failed with code %s"%sw)
1371
Supreeth Herle80164052020-03-23 12:06:29 +01001372 # Populate AIDs
1373 self.read_aids()
1374
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001375 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1376 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001377 self._scc.select_path(['3f00'])
1378 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001379 if p.get('ki'):
1380 self._scc.update_binary('6f20', p['ki'], 1)
1381 if p.get('opc'):
1382 self._scc.update_binary('6f20', p['opc'], 17)
1383
1384 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001385 data, sw = self.select_adf_by_aid(adf="isim")
1386 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001387 if p.get('ki'):
1388 self._scc.update_binary('af20', p['ki'], 1)
1389 if p.get('opc'):
1390 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001391
Supreeth Herlecf727f22020-03-24 17:32:21 +01001392 # update EF.P-CSCF in ADF.ISIM
1393 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1394 if p.get('pcscf'):
1395 sw = self.update_pcscf(p['pcscf'])
1396 else:
1397 sw = self.update_pcscf("")
1398 if sw != '9000':
1399 print("Programming P-CSCF failed with code %s"%sw)
1400
1401
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001402 # update EF.DOMAIN in ADF.ISIM
1403 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1404 if p.get('ims_hdomain'):
1405 sw = self.update_domain(domain=p['ims_hdomain'])
1406 else:
1407 sw = self.update_domain()
1408
1409 if sw != '9000':
1410 print("Programming Home Network Domain Name failed with code %s"%sw)
1411
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001412 # update EF.IMPI in ADF.ISIM
1413 # TODO: Validate IMPI input
1414 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1415 if p.get('impi'):
1416 sw = self.update_impi(p['impi'])
1417 else:
1418 sw = self.update_impi()
1419 if sw != '9000':
1420 print("Programming IMPI failed with code %s"%sw)
1421
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001422 # update EF.IMPU in ADF.ISIM
1423 # TODO: Validate IMPU input
1424 # Support multiple IMPU if there is enough space
1425 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1426 if p.get('impu'):
1427 sw = self.update_impu(p['impu'])
1428 else:
1429 sw = self.update_impu()
1430 if sw != '9000':
1431 print("Programming IMPU failed with code %s"%sw)
1432
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001433 data, sw = self.select_adf_by_aid(adf="usim")
1434 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001435 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001436 if p.get('ki'):
1437 self._scc.update_binary('af20', p['ki'], 1)
1438 if p.get('opc'):
1439 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001440
Harald Welteca673942020-06-03 15:19:40 +02001441 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001442 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001443 if p.get('mcc') and p.get('mnc'):
1444 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1445 if sw != '9000':
1446 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001447
1448 # update EF.ePDGId in ADF.USIM
1449 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1450 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001451 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001452 else:
1453 sw = self.update_epdgid("")
1454 if sw != '9000':
1455 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001456
Supreeth Herlef964df42020-03-24 13:15:37 +01001457 # update EF.ePDGSelection in ADF.USIM
1458 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1459 if p.get('epdgSelection'):
1460 epdg_plmn = p['epdgSelection']
1461 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1462 else:
1463 sw = self.update_ePDGSelection("", "")
1464 if sw != '9000':
1465 print("Programming ePDGSelection failed with code %s"%sw)
1466
1467
Supreeth Herleacc222f2020-03-24 13:26:53 +01001468 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1469 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001470 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001471 if self.file_exists(EF_USIM_ADF_map['UST']):
1472 if p.get('epdgSelection') and p.get('epdgid'):
1473 sw = self.update_ust(106, 1)
1474 if sw != '9000':
1475 print("Programming UST failed with code %s"%sw)
1476 sw = self.update_ust(107, 1)
1477 if sw != '9000':
1478 print("Programming UST failed with code %s"%sw)
1479
Supreeth Herle44e04622020-03-25 10:34:28 +01001480 sw = self.update_ust(95, 0)
1481 if sw != '9000':
1482 print("Programming UST failed with code %s"%sw)
1483 sw = self.update_ust(99, 0)
1484 if sw != '9000':
1485 print("Programming UST failed with code %s"%sw)
1486 sw = self.update_ust(115, 0)
1487 if sw != '9000':
1488 print("Programming UST failed with code %s"%sw)
1489
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001490 return
1491
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001492
Todd Neal9eeadfc2018-04-25 15:36:29 -05001493# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001494_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001495 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001496 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001497
1498def card_autodetect(scc):
1499 for kls in _cards_classes:
1500 card = kls.autodetect(scc)
1501 if card is not None:
1502 card.reset()
1503 return card
1504 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001505
1506def card_detect(ctype, scc):
1507 # Detect type if needed
1508 card = None
1509 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1510
1511 if ctype in ("auto", "auto_once"):
1512 for kls in _cards_classes:
1513 card = kls.autodetect(scc)
1514 if card:
1515 print("Autodetected card type: %s" % card.name)
1516 card.reset()
1517 break
1518
1519 if card is None:
1520 print("Autodetection failed")
1521 return None
1522
1523 if ctype == "auto_once":
1524 ctype = card.name
1525
1526 elif ctype in ctypes:
1527 card = ctypes[ctype](scc)
1528
1529 else:
1530 raise ValueError("Unknown card type: %s" % ctype)
1531
1532 return card