blob: 24e789ee6296bb83faeb2e8e6caf7853bc2e467b [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: Card programmation logic
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Welte3156d902011-03-22 21:48:19 +01008# Copyright (C) 2011 Harald Welte <laforge@gnumonks.org>
Alexander Chemeriseb6807d2017-07-18 17:04:38 +03009# Copyright (C) 2017 Alexander.Chemeris <Alexander.Chemeris@gmail.com>
Sylvain Munaut76504e02010-12-07 00:24:32 +010010#
11# This program is free software: you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation, either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program. If not, see <http://www.gnu.org/licenses/>.
23#
24
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020025from typing import Optional, Dict, Tuple
Vadim Yanitskiy85302d62021-05-02 02:18:42 +020026import abc
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020027
Robert Falkenbergd0505bd2021-02-24 14:06:18 +010028from pySim.ts_51_011 import EF, DF, EF_AD
Harald Welteca673942020-06-03 15:19:40 +020029from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010030from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030031from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090032from smartcard.util import toBytes
Supreeth Herle79f43dd2020-03-25 11:43:19 +010033from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010034
35class Card(object):
36
37 def __init__(self, scc):
38 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030039 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010040 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010041
Sylvain Munaut76504e02010-12-07 00:24:32 +010042 def reset(self):
43 self._scc.reset_card()
44
Philipp Maierd58c6322020-05-12 16:47:45 +020045 def erase(self):
46 print("warning: erasing is not supported for specified card type!")
47 return
48
Harald Welteca673942020-06-03 15:19:40 +020049 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010050 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020051 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020052 if res[1] != '9000':
53 return False
Harald Welteca673942020-06-03 15:19:40 +020054 return True
55
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030056 def verify_adm(self, key):
57 '''
58 Authenticate with ADM key
59 '''
60 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
61 return sw
62
63 def read_iccid(self):
64 (res, sw) = self._scc.read_binary(EF['ICCID'])
65 if sw == '9000':
66 return (dec_iccid(res), sw)
67 else:
68 return (None, sw)
69
70 def read_imsi(self):
71 (res, sw) = self._scc.read_binary(EF['IMSI'])
72 if sw == '9000':
73 return (dec_imsi(res), sw)
74 else:
75 return (None, sw)
76
77 def update_imsi(self, imsi):
78 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
79 return sw
80
81 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +020082 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030083 return sw
84
Supreeth Herlea850a472020-03-19 12:44:11 +010085 def read_hplmn_act(self):
86 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
87 if sw == '9000':
88 return (format_xplmn_w_act(res), sw)
89 else:
90 return (None, sw)
91
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030092 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
93 """
94 Update Home PLMN with access technology bit-field
95
96 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
97 in ETSI TS 151 011 for the details of the access_tech field coding.
98 Some common values:
99 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +0200100 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300101 """
102 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100103 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700104 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300105 hplmn = enc_plmn(mcc, mnc)
106 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700107 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300108 return sw
109
Supreeth Herle1757b262020-03-19 12:43:11 +0100110 def read_oplmn_act(self):
111 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
112 if sw == '9000':
113 return (format_xplmn_w_act(res), sw)
114 else:
115 return (None, sw)
116
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200117 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
118 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200119 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200120 """
121 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200122 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700123 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200124 hplmn = enc_plmn(mcc, mnc)
125 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700126 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200127 return sw
128
Supreeth Herle14084402020-03-19 12:42:10 +0100129 def read_plmn_act(self):
130 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
131 if sw == '9000':
132 return (format_xplmn_w_act(res), sw)
133 else:
134 return (None, sw)
135
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200136 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
137 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200138 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200139 """
140 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200141 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700142 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200143 hplmn = enc_plmn(mcc, mnc)
144 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700145 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200146 return sw
147
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200148 def update_plmnsel(self, mcc, mnc):
149 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700150 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200151 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200152 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
153 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200154
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300155 def update_smsp(self, smsp):
156 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
157 return sw
158
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100159 def update_ad(self, mnc=None, opmode=None, ofm=None):
160 """
161 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100162
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100163 See Sec. "4.2.18 EF_AD (Administrative Data)"
164 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200165
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100166 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200167
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100168 Parameters:
169 mnc (str): MNC of IMSI
170 opmode (Hex-str, 1 Byte): MS Operation Mode
171 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
172
173 Returns:
174 str: Return code of write operation
175 """
176
177 ad = EF_AD()
178
179 # read from card
180 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200181 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100182
183 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200184 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100185 mnclen = len(str(mnc))
186 if mnclen == 1:
187 mnclen = 2
188 if mnclen > 3:
189 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200190 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100191 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200192 opmode_num = int(opmode, 16)
193 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
194 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100195 else:
196 raise RuntimeError('invalid opmode "{}"'.format(opmode))
197 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200198 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100199
200 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200201 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100202 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100203 return sw
204
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300205 def read_spn(self):
206 (spn, sw) = self._scc.read_binary(EF['SPN'])
207 if sw == '9000':
208 return (dec_spn(spn), sw)
209 else:
210 return (None, sw)
211
212 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
213 content = enc_spn(name, hplmn_disp, oplmn_disp)
214 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
215 return sw
216
Supreeth Herled21349a2020-04-01 08:37:47 +0200217 def read_binary(self, ef, length=None, offset=0):
218 ef_path = ef in EF and EF[ef] or ef
219 return self._scc.read_binary(ef_path, length, offset)
220
Supreeth Herlead10d662020-04-01 08:43:08 +0200221 def read_record(self, ef, rec_no):
222 ef_path = ef in EF and EF[ef] or ef
223 return self._scc.read_record(ef_path, rec_no)
224
Supreeth Herle98a69272020-03-18 12:14:48 +0100225 def read_gid1(self):
226 (res, sw) = self._scc.read_binary(EF['GID1'])
227 if sw == '9000':
228 return (res, sw)
229 else:
230 return (None, sw)
231
Supreeth Herle6d66af62020-03-19 12:49:16 +0100232 def read_msisdn(self):
233 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
234 if sw == '9000':
235 return (dec_msisdn(res), sw)
236 else:
237 return (None, sw)
238
Supreeth Herlee4e98312020-03-18 11:33:14 +0100239 # Fetch all the AIDs present on UICC
240 def read_aids(self):
Philipp Maier1e896f32021-03-10 17:02:53 +0100241 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100242 try:
243 # Find out how many records the EF.DIR has
244 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100245 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100246 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100247 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100248 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
249 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
250 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
251 except Exception as e:
252 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100253 self._aids = []
254 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100255
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100256 # Select ADF.U/ISIM in the Card using its full AID
257 def select_adf_by_aid(self, adf="usim"):
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100258 # Find full AID by partial AID:
259 if is_hex(adf):
260 for aid in self._aids:
261 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
262 return self._scc.select_adf(aid)
263 # Find full AID by application name:
264 elif adf in ["usim", "isim"]:
265 # First (known) halves of the U/ISIM AID
266 aid_map = {}
267 aid_map["usim"] = "a0000000871002"
268 aid_map["isim"] = "a0000000871004"
269 for aid in self._aids:
270 if aid_map[adf] in aid:
271 return self._scc.select_adf(aid)
272 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100273
Philipp Maier5c2cc662020-05-12 16:27:12 +0200274 # Erase the contents of a file
275 def erase_binary(self, ef):
276 len = self._scc.binary_size(ef)
277 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
278
279 # Erase the contents of a single record
280 def erase_record(self, ef, rec_no):
281 len = self._scc.record_size(ef)
282 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
283
Harald Welteca673942020-06-03 15:19:40 +0200284class UsimCard(Card):
285 def __init__(self, ssc):
286 super(UsimCard, self).__init__(ssc)
287
288 def read_ehplmn(self):
289 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
290 if sw == '9000':
291 return (format_xplmn(res), sw)
292 else:
293 return (None, sw)
294
295 def update_ehplmn(self, mcc, mnc):
296 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
297 size = len(data[0]) // 2
298 ehplmn = enc_plmn(mcc, mnc)
299 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
300 return sw
301
herlesupreethf8232db2020-09-29 10:03:06 +0200302 def read_epdgid(self):
303 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
304 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100305 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200306 else:
307 return (None, sw)
308
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200309 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100310 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
311 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100312 addr_type = get_addr_type(epdgid)
313 if addr_type == None:
314 raise ValueError("Unknown ePDG Id address type or invalid address provided")
315 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100316 else:
317 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200318 data, sw = self._scc.update_binary(
319 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
320 return sw
Harald Welteca673942020-06-03 15:19:40 +0200321
Supreeth Herle99d55552020-03-24 13:03:43 +0100322 def read_ePDGSelection(self):
323 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
324 if sw == '9000':
325 return (format_ePDGSelection(res), sw)
326 else:
327 return (None, sw)
328
Supreeth Herlef964df42020-03-24 13:15:37 +0100329 def update_ePDGSelection(self, mcc, mnc):
330 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
331 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
332 # Reset contents
333 # 80 - Tag value
334 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
335 elif sw == '9000':
336 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
337 return sw
338
herlesupreeth4a3580b2020-09-29 10:11:36 +0200339 def read_ust(self):
340 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
341 if sw == '9000':
342 # Print those which are available
343 return ([res, dec_st(res, table="usim")], sw)
344 else:
345 return ([None, None], sw)
346
Supreeth Herleacc222f2020-03-24 13:26:53 +0100347 def update_ust(self, service, bit=1):
348 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
349 if sw == '9000':
350 content = enc_st(res, service, bit)
351 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
352 return sw
353
herlesupreethecbada92020-12-23 09:24:29 +0100354class IsimCard(Card):
355 def __init__(self, ssc):
356 super(IsimCard, self).__init__(ssc)
357
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100358 def read_pcscf(self):
359 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
360 pcscf_recs = ""
361 for i in range(0, rec_cnt):
362 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
363 if sw == '9000':
364 content = dec_addr_tlv(res)
365 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
366 else:
367 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
368 return pcscf_recs
369
Supreeth Herlecf727f22020-03-24 17:32:21 +0100370 def update_pcscf(self, pcscf):
371 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100372 addr_type = get_addr_type(pcscf)
373 if addr_type == None:
374 raise ValueError("Unknown PCSCF address type or invalid address provided")
375 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100376 else:
377 # Just the tag value
378 content = '80'
379 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100380 pcscf_tlv = rpad(content, rec_size_bytes*2)
381 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100382 return sw
383
Supreeth Herle05b28072020-03-25 10:23:48 +0100384 def read_domain(self):
385 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
386 if sw == '9000':
387 # Skip the inital tag value ('80') byte and get length of contents
388 length = int(res[2:4], 16)
389 content = h2s(res[4:4+(length*2)])
390 return (content, sw)
391 else:
392 return (None, sw)
393
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100394 def update_domain(self, domain=None, mcc=None, mnc=None):
395 hex_str = ""
396 if domain:
397 hex_str = s2h(domain)
398 elif mcc and mnc:
399 # MCC and MNC always has 3 digits in domain form
400 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
401 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
402
403 # Build TLV
404 tlv = TLV(['80'])
405 content = tlv.build({'80': hex_str})
406
407 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
408 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
409 return sw
410
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100411 def read_impi(self):
412 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
413 if sw == '9000':
414 # Skip the inital tag value ('80') byte and get length of contents
415 length = int(res[2:4], 16)
416 content = h2s(res[4:4+(length*2)])
417 return (content, sw)
418 else:
419 return (None, sw)
420
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100421 def update_impi(self, impi=None):
422 hex_str = ""
423 if impi:
424 hex_str = s2h(impi)
425 # Build TLV
426 tlv = TLV(['80'])
427 content = tlv.build({'80': hex_str})
428
429 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
430 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
431 return sw
432
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100433 def read_impu(self):
434 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
435 impu_recs = ""
436 for i in range(0, rec_cnt):
437 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
438 if sw == '9000':
439 # Skip the inital tag value ('80') byte and get length of contents
440 length = int(res[2:4], 16)
441 content = h2s(res[4:4+(length*2)])
442 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
443 else:
444 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
445 return impu_recs
446
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100447 def update_impu(self, impu=None):
448 hex_str = ""
449 if impu:
450 hex_str = s2h(impu)
451 # Build TLV
452 tlv = TLV(['80'])
453 content = tlv.build({'80': hex_str})
454
455 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
456 impu_tlv = rpad(content, rec_size_bytes*2)
457 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
458 return sw
459
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200460 def read_iari(self):
461 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
462 uiari_recs = ""
463 for i in range(0, rec_cnt):
464 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
465 if sw == '9000':
466 # Skip the inital tag value ('80') byte and get length of contents
467 length = int(res[2:4], 16)
468 content = h2s(res[4:4+(length*2)])
469 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
470 else:
471 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
472 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100473
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200474class MagicSimBase(abc.ABC, Card):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100475 """
476 Theses cards uses several record based EFs to store the provider infos,
477 each possible provider uses a specific record number in each EF. The
478 indexes used are ( where N is the number of providers supported ) :
479 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200480 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100481
482 * 3f00/7f4d/8f0c : Operator Name
483
484 bytes 0-15 : provider name, padded with 0xff
485 byte 16 : length of the provider name
486 byte 17 : 01 for valid records, 00 otherwise
487
488 * 3f00/7f4d/8f0d : Programmable Binary EFs
489
490 * 3f00/7f4d/8f0e : Programmable Record EFs
491
492 """
493
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200494 _files = { } # type: Dict[str, Tuple[str, int, bool]]
495 _ki_file = None # type: Optional[str]
496
Sylvain Munaut76504e02010-12-07 00:24:32 +0100497 @classmethod
498 def autodetect(kls, scc):
499 try:
500 for p, l, t in kls._files.values():
501 if not t:
502 continue
503 if scc.record_size(['3f00', '7f4d', p]) != l:
504 return None
505 except:
506 return None
507
508 return kls(scc)
509
510 def _get_count(self):
511 """
512 Selects the file and returns the total number of entries
513 and entry size
514 """
515 f = self._files['name']
516
Harald Weltec0499c82021-01-21 16:06:50 +0100517 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100518 rec_len = int(r[-1][28:30], 16)
519 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200520 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100521
522 if (rec_cnt < 1) or (rec_len != f[1]):
523 raise RuntimeError('Bad card type')
524
525 return rec_cnt
526
527 def program(self, p):
528 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100529 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100530
531 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400532 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100533
534 # Operator name ( 3f00/7f4d/8f0c )
535 self._scc.update_record(self._files['name'][0], 2,
536 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
537 )
538
539 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
540 v = ''
541
542 # inline Ki
543 if self._ki_file is None:
544 v += p['ki']
545
546 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400547 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100548
549 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400550 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100551
552 # Ki
553 if self._ki_file:
554 v += self._ki_file + '10' + p['ki']
555
556 # PLMN_Sel
557 v+= '6f30' + '18' + rpad(hplmn, 36)
558
Alexander Chemeris21885242013-07-02 16:56:55 +0400559 # ACC
560 # This doesn't work with "fake" SuperSIM cards,
561 # but will hopefully work with real SuperSIMs.
562 if p.get('acc') is not None:
563 v+= '6f78' + '02' + lpad(p['acc'], 4)
564
Sylvain Munaut76504e02010-12-07 00:24:32 +0100565 self._scc.update_record(self._files['b_ef'][0], 1,
566 rpad(v, self._files['b_ef'][1]*2)
567 )
568
569 # SMSP ( 3f00/7f4d/8f0e )
570 # FIXME
571
572 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100573 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100574 tl = int(r[-1][4:8], 16)
575
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400576 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100577 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
578
579 def erase(self):
580 # Dummy
581 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200582 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100583 ofs = 1
584 fv = v[1] * 'ff'
585 if k == 'name':
586 ofs = 2
587 fv = fv[0:-4] + '0000'
588 df[v[0]] = (fv, ofs)
589
590 # Write
591 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200592 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100593 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
594
595
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200596class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100597
598 name = 'supersim'
599
600 _files = {
601 'name' : ('8f0c', 18, True),
602 'b_ef' : ('8f0d', 74, True),
603 'r_ef' : ('8f0e', 50, True),
604 }
605
606 _ki_file = None
607
608
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200609class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100610
611 name = 'magicsim'
612
613 _files = {
614 'name' : ('8f0c', 18, True),
615 'b_ef' : ('8f0d', 130, True),
616 'r_ef' : ('8f0e', 102, False),
617 }
618
619 _ki_file = '6f1b'
620
621
622class FakeMagicSim(Card):
623 """
624 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200625 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100626 1 to N.
627 """
628
629 name = 'fakemagicsim'
630
631 @classmethod
632 def autodetect(kls, scc):
633 try:
634 if scc.record_size(['3f00', '000c']) != 0x5a:
635 return None
636 except:
637 return None
638
639 return kls(scc)
640
641 def _get_infos(self):
642 """
643 Selects the file and returns the total number of entries
644 and entry size
645 """
646
Harald Weltec0499c82021-01-21 16:06:50 +0100647 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100648 rec_len = int(r[-1][28:30], 16)
649 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200650 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100651
652 if (rec_cnt < 1) or (rec_len != 0x5a):
653 raise RuntimeError('Bad card type')
654
655 return rec_cnt, rec_len
656
657 def program(self, p):
658 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100659 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100660 tl = int(r[-1][4:8], 16)
661
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400662 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100663 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
664
665 # Get total number of entries and entry size
666 rec_cnt, rec_len = self._get_infos()
667
668 # Set first entry
669 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200670 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100671 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200672 enc_iccid(p['iccid']) + # 10b ICCID
673 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
674 p['ki'] + # 16b Ki
675 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100676 )
677 self._scc.update_record('000c', 1, entry)
678
679 def erase(self):
680 # Get total number of entries and entry size
681 rec_cnt, rec_len = self._get_infos()
682
683 # Erase all entries
684 entry = 'ff' * rec_len
685 for i in range(0, rec_cnt):
686 self._scc.update_record('000c', 1+i, entry)
687
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200688
Harald Welte3156d902011-03-22 21:48:19 +0100689class GrcardSim(Card):
690 """
691 Greencard (grcard.cn) HZCOS GSM SIM
692 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
693 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
694 """
695
696 name = 'grcardsim'
697
698 @classmethod
699 def autodetect(kls, scc):
700 return None
701
702 def program(self, p):
703 # We don't really know yet what ADM PIN 4 is about
704 #self._scc.verify_chv(4, h2b("4444444444444444"))
705
706 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100707 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200708 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100709 else:
710 pin = h2b("4444444444444444")
711 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100712
713 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100714 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400715 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100716
717 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100718 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400719 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100720
721 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400722 if p.get('acc') is not None:
723 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100724
725 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200726 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100727 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200728 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100729
730 # Set the Ki using proprietary command
731 pdu = '80d4020010' + p['ki']
732 data, sw = self._scc._tp.send_apdu(pdu)
733
734 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100735 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100736 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400737 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100738 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
739
740 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100741 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100742 size = int(r[-1][4:8], 16)
743 # FIXME
744
745 # FIXME: EF.MSISDN
746
Sylvain Munaut76504e02010-12-07 00:24:32 +0100747
Harald Weltee10394b2011-12-07 12:34:14 +0100748class SysmoSIMgr1(GrcardSim):
749 """
750 sysmocom sysmoSIM-GR1
751 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
752 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
753 """
754 name = 'sysmosim-gr1'
755
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200756 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200757 def autodetect(kls, scc):
758 try:
759 # Look for ATR
760 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
761 return kls(scc)
762 except:
763 return None
764 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200765
Harald Welteca673942020-06-03 15:19:40 +0200766class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100767 """
768 sysmocom sysmoUSIM-GR1
769 """
770 name = 'sysmoUSIM-GR1'
771
772 @classmethod
773 def autodetect(kls, scc):
774 # TODO: Access the ATR
775 return None
776
777 def program(self, p):
778 # TODO: check if verify_chv could be used or what it needs
779 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
780 # Unlock the card..
781 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
782
783 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100784 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400785 p['opc'] + # 32b OPC
786 enc_iccid(p['iccid']) + # 10b ICCID
787 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100788 )
789 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
790
Sylvain Munaut053c8952013-07-02 15:12:32 +0200791
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100792class SysmoSIMgr2(Card):
793 """
794 sysmocom sysmoSIM-GR2
795 """
796
797 name = 'sysmoSIM-GR2'
798
799 @classmethod
800 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900801 try:
802 # Look for ATR
803 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
804 return kls(scc)
805 except:
806 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100807 return None
808
809 def program(self, p):
810
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200811 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100812 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200813
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100814 # authenticate as SUPER ADM using default key
815 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
816
817 # set ADM pin using proprietary command
818 # INS: D4
819 # P1: 3A for PIN, 3B for PUK
820 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
821 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100822 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200823 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100824 else:
825 pin = h2b("4444444444444444")
826
827 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100828 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200829
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100830 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100831
832 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100833
834 # write EF.ICCID
835 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
836
837 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100838 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200839
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100840 # write EF.IMSI
841 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
842
843 # write EF.ACC
844 if p.get('acc') is not None:
845 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
846
847 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100848 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100849 size = int(r[-1][4:8], 16)
850 hplmn = enc_plmn(p['mcc'], p['mnc'])
851 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
852
853 # set COMP128 version 0 in proprietary file
854 data, sw = self._scc.update_binary('0001', '001000')
855
856 # set Ki in proprietary file
857 data, sw = self._scc.update_binary('0001', p['ki'], 3)
858
859 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100860 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200861
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100862 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200863 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200864 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100865
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100866
Harald Welteca673942020-06-03 15:19:40 +0200867class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100868 """
869 sysmocom sysmoUSIM-SJS1
870 """
871
872 name = 'sysmoUSIM-SJS1'
873
874 def __init__(self, ssc):
875 super(SysmoUSIMSJS1, self).__init__(ssc)
876 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100877 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100878
879 @classmethod
880 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900881 try:
882 # Look for ATR
883 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"):
884 return kls(scc)
885 except:
886 return None
Jan Balke3e840672015-01-26 15:36:27 +0100887 return None
888
Harald Weltea6704252021-01-08 20:19:11 +0100889 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100890 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100891 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100892 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100893 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100894 return sw
895
896 def program(self, p):
897 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100898
899 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100900 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100901
Philipp Maiere9604882017-03-21 17:24:31 +0100902 # write EF.ICCID
903 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
904
Jan Balke3e840672015-01-26 15:36:27 +0100905 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100906 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100907
Jan Balke3e840672015-01-26 15:36:27 +0100908 # set Ki in proprietary file
909 data, sw = self._scc.update_binary('00FF', p['ki'])
910
Philipp Maier1be35bf2018-07-13 11:29:03 +0200911 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200912 if 'opc' in p:
913 content = "01" + p['opc']
914 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100915
Supreeth Herle7947d922019-06-08 07:50:53 +0200916 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100917 if p.get('name') is not None:
918 content = enc_spn(p['name'], True, True)
919 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200920
Supreeth Herlec8796a32019-12-23 12:23:42 +0100921 if p.get('acc') is not None:
922 self.update_acc(p['acc'])
923
Jan Balke3e840672015-01-26 15:36:27 +0100924 # write EF.IMSI
925 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
926
Philipp Maier2d15ea02019-03-20 12:40:36 +0100927 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200928 if p.get('mcc') and p.get('mnc'):
929 sw = self.update_plmnsel(p['mcc'], p['mnc'])
930 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100931 print("Programming PLMNsel failed with code %s"%sw)
932
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200933 # EF.PLMNwAcT
934 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100935 sw = self.update_plmn_act(p['mcc'], p['mnc'])
936 if sw != '9000':
937 print("Programming PLMNwAcT failed with code %s"%sw)
938
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200939 # EF.OPLMNwAcT
940 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100941 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
942 if sw != '9000':
943 print("Programming OPLMNwAcT failed with code %s"%sw)
944
Supreeth Herlef442fb42020-01-21 12:47:32 +0100945 # EF.HPLMNwAcT
946 if p.get('mcc') and p.get('mnc'):
947 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
948 if sw != '9000':
949 print("Programming HPLMNwAcT failed with code %s"%sw)
950
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200951 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100952 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
953 if p.get('mcc') and p.get('mnc'):
954 mnc = p['mnc']
955 else:
956 mnc = None
957 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +0100958 if sw != '9000':
959 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100960
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200961 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200962 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100963 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +0200964 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100965
Supreeth Herle5a541012019-12-22 08:59:16 +0100966 # EF.MSISDN
967 # TODO: Alpha Identifier (currently 'ff'O * 20)
968 # TODO: Capability/Configuration1 Record Identifier
969 # TODO: Extension1 Record Identifier
970 if p.get('msisdn') is not None:
971 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +0200972 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +0100973
Harald Weltec0499c82021-01-21 16:06:50 +0100974 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +0100975 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
976
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900977
herlesupreeth4a3580b2020-09-29 10:11:36 +0200978class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900979 """
980 FairwavesSIM
981
982 The SIM card is operating according to the standard.
983 For Ki/OP/OPC programming the following files are additionally open for writing:
984 3F00/7F20/FF01 – OP/OPC:
985 byte 1 = 0x01, bytes 2-17: OPC;
986 byte 1 = 0x00, bytes 2-17: OP;
987 3F00/7F20/FF02: Ki
988 """
989
Philipp Maier5a876312019-11-11 11:01:46 +0100990 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900991 # Propriatary files
992 _EF_num = {
993 'Ki': 'FF02',
994 'OP/OPC': 'FF01',
995 }
996 _EF = {
997 'Ki': DF['GSM']+[_EF_num['Ki']],
998 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
999 }
1000
1001 def __init__(self, ssc):
1002 super(FairwavesSIM, self).__init__(ssc)
1003 self._adm_chv_num = 0x11
1004 self._adm2_chv_num = 0x12
1005
1006
1007 @classmethod
1008 def autodetect(kls, scc):
1009 try:
1010 # Look for ATR
1011 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"):
1012 return kls(scc)
1013 except:
1014 return None
1015 return None
1016
1017
1018 def verify_adm2(self, key):
1019 '''
1020 Authenticate with ADM2 key.
1021
1022 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1023 is a key which has access to proprietary files (Ki and OP/OPC).
1024 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1025 need ADM2 key per se.
1026 '''
1027 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1028 return sw
1029
1030
1031 def read_ki(self):
1032 """
1033 Read Ki in proprietary file.
1034
1035 Requires ADM1 access level
1036 """
1037 return self._scc.read_binary(self._EF['Ki'])
1038
1039
1040 def update_ki(self, ki):
1041 """
1042 Set Ki in proprietary file.
1043
1044 Requires ADM1 access level
1045 """
1046 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1047 return sw
1048
1049
1050 def read_op_opc(self):
1051 """
1052 Read Ki in proprietary file.
1053
1054 Requires ADM1 access level
1055 """
1056 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1057 type = 'OP' if ef[0:2] == '00' else 'OPC'
1058 return ((type, ef[2:]), sw)
1059
1060
1061 def update_op(self, op):
1062 """
1063 Set OP in proprietary file.
1064
1065 Requires ADM1 access level
1066 """
1067 content = '00' + op
1068 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1069 return sw
1070
1071
1072 def update_opc(self, opc):
1073 """
1074 Set OPC in proprietary file.
1075
1076 Requires ADM1 access level
1077 """
1078 content = '01' + opc
1079 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1080 return sw
1081
1082
1083 def program(self, p):
1084 # authenticate as ADM1
1085 if not p['pin_adm']:
1086 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001087 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001088
1089 # TODO: Set operator name
1090 if p.get('smsp') is not None:
1091 sw = self.update_smsp(p['smsp'])
1092 if sw != '9000':
1093 print("Programming SMSP failed with code %s"%sw)
1094 # This SIM doesn't support changing ICCID
1095 if p.get('mcc') is not None and p.get('mnc') is not None:
1096 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1097 if sw != '9000':
1098 print("Programming MCC/MNC failed with code %s"%sw)
1099 if p.get('imsi') is not None:
1100 sw = self.update_imsi(p['imsi'])
1101 if sw != '9000':
1102 print("Programming IMSI failed with code %s"%sw)
1103 if p.get('ki') is not None:
1104 sw = self.update_ki(p['ki'])
1105 if sw != '9000':
1106 print("Programming Ki failed with code %s"%sw)
1107 if p.get('opc') is not None:
1108 sw = self.update_opc(p['opc'])
1109 if sw != '9000':
1110 print("Programming OPC failed with code %s"%sw)
1111 if p.get('acc') is not None:
1112 sw = self.update_acc(p['acc'])
1113 if sw != '9000':
1114 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001115
Todd Neal9eeadfc2018-04-25 15:36:29 -05001116class OpenCellsSim(Card):
1117 """
1118 OpenCellsSim
1119
1120 """
1121
Philipp Maier5a876312019-11-11 11:01:46 +01001122 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001123
1124 def __init__(self, ssc):
1125 super(OpenCellsSim, self).__init__(ssc)
1126 self._adm_chv_num = 0x0A
1127
1128
1129 @classmethod
1130 def autodetect(kls, scc):
1131 try:
1132 # Look for ATR
1133 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"):
1134 return kls(scc)
1135 except:
1136 return None
1137 return None
1138
1139
1140 def program(self, p):
1141 if not p['pin_adm']:
1142 raise ValueError("Please provide a PIN-ADM as there is no default one")
1143 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1144
1145 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001146 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001147
1148 # write EF.ICCID
1149 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1150
Harald Weltec0499c82021-01-21 16:06:50 +01001151 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001152
1153 # set Ki in proprietary file
1154 data, sw = self._scc.update_binary('FF02', p['ki'])
1155
1156 # set OPC in proprietary file
1157 data, sw = self._scc.update_binary('FF01', p['opc'])
1158
1159 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001160 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001161
1162 # write EF.IMSI
1163 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1164
herlesupreeth4a3580b2020-09-29 10:11:36 +02001165class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001166 """
1167 WavemobileSim
1168
1169 """
1170
1171 name = 'Wavemobile-SIM'
1172
1173 def __init__(self, ssc):
1174 super(WavemobileSim, self).__init__(ssc)
1175 self._adm_chv_num = 0x0A
1176 self._scc.cla_byte = "00"
1177 self._scc.sel_ctrl = "0004" #request an FCP
1178
1179 @classmethod
1180 def autodetect(kls, scc):
1181 try:
1182 # Look for ATR
1183 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"):
1184 return kls(scc)
1185 except:
1186 return None
1187 return None
1188
1189 def program(self, p):
1190 if not p['pin_adm']:
1191 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001192 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001193
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001194 # EF.ICCID
1195 # TODO: Add programming of the ICCID
1196 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001197 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1198
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001199 # KI (Presumably a propritary file)
1200 # TODO: Add programming of KI
1201 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001202 print("Warning: Programming of the KI is not implemented for this type of card.")
1203
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001204 # OPc (Presumably a propritary file)
1205 # TODO: Add programming of OPc
1206 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001207 print("Warning: Programming of the OPc is not implemented for this type of card.")
1208
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001209 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001210 if p.get('smsp'):
1211 sw = self.update_smsp(p['smsp'])
1212 if sw != '9000':
1213 print("Programming SMSP failed with code %s"%sw)
1214
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001215 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001216 if p.get('imsi'):
1217 sw = self.update_imsi(p['imsi'])
1218 if sw != '9000':
1219 print("Programming IMSI failed with code %s"%sw)
1220
1221 # EF.ACC
1222 if p.get('acc'):
1223 sw = self.update_acc(p['acc'])
1224 if sw != '9000':
1225 print("Programming ACC failed with code %s"%sw)
1226
1227 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001228 if p.get('mcc') and p.get('mnc'):
1229 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1230 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001231 print("Programming PLMNsel failed with code %s"%sw)
1232
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001233 # EF.PLMNwAcT
1234 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001235 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1236 if sw != '9000':
1237 print("Programming PLMNwAcT failed with code %s"%sw)
1238
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001239 # EF.OPLMNwAcT
1240 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001241 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1242 if sw != '9000':
1243 print("Programming OPLMNwAcT failed with code %s"%sw)
1244
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001245 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001246 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1247 if p.get('mcc') and p.get('mnc'):
1248 mnc = p['mnc']
1249 else:
1250 mnc = None
1251 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001252 if sw != '9000':
1253 print("Programming AD failed with code %s"%sw)
1254
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001255 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001256
Todd Neal9eeadfc2018-04-25 15:36:29 -05001257
herlesupreethb0c7d122020-12-23 09:25:46 +01001258class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001259 """
1260 sysmocom sysmoISIM-SJA2
1261 """
1262
1263 name = 'sysmoISIM-SJA2'
1264
1265 def __init__(self, ssc):
1266 super(SysmoISIMSJA2, self).__init__(ssc)
1267 self._scc.cla_byte = "00"
1268 self._scc.sel_ctrl = "0004" #request an FCP
1269
1270 @classmethod
1271 def autodetect(kls, scc):
1272 try:
1273 # Try card model #1
1274 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1275 if scc.get_atr() == toBytes(atr):
1276 return kls(scc)
1277
1278 # Try card model #2
1279 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1280 if scc.get_atr() == toBytes(atr):
1281 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001282
1283 # Try card model #3
1284 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1285 if scc.get_atr() == toBytes(atr):
1286 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001287 except:
1288 return None
1289 return None
1290
Harald Weltea6704252021-01-08 20:19:11 +01001291 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001292 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001293 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001294 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001295 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001296 return sw
1297
1298 def program(self, p):
1299 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001300
1301 # This type of card does not allow to reprogram the ICCID.
1302 # Reprogramming the ICCID would mess up the card os software
1303 # license management, so the ICCID must be kept at its factory
1304 # setting!
1305 if p.get('iccid'):
1306 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1307
1308 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001309 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001310
Robert Falkenberg54595362021-04-06 12:04:34 +02001311 # set Service Provider Name
1312 if p.get('name') is not None:
1313 content = enc_spn(p['name'], True, True)
1314 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
1315
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001316 # write EF.IMSI
1317 if p.get('imsi'):
1318 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1319
1320 # EF.PLMNsel
1321 if p.get('mcc') and p.get('mnc'):
1322 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1323 if sw != '9000':
1324 print("Programming PLMNsel failed with code %s"%sw)
1325
1326 # EF.PLMNwAcT
1327 if p.get('mcc') and p.get('mnc'):
1328 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1329 if sw != '9000':
1330 print("Programming PLMNwAcT failed with code %s"%sw)
1331
1332 # EF.OPLMNwAcT
1333 if p.get('mcc') and p.get('mnc'):
1334 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1335 if sw != '9000':
1336 print("Programming OPLMNwAcT failed with code %s"%sw)
1337
Harald Welte32f0d412020-05-05 17:35:57 +02001338 # EF.HPLMNwAcT
1339 if p.get('mcc') and p.get('mnc'):
1340 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1341 if sw != '9000':
1342 print("Programming HPLMNwAcT failed with code %s"%sw)
1343
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001344 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001345 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1346 if p.get('mcc') and p.get('mnc'):
1347 mnc = p['mnc']
1348 else:
1349 mnc = None
1350 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001351 if sw != '9000':
1352 print("Programming AD failed with code %s"%sw)
1353
1354 # EF.SMSP
1355 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001356 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001357 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1358
Supreeth Herlec6019232020-03-26 10:00:45 +01001359 # EF.MSISDN
1360 # TODO: Alpha Identifier (currently 'ff'O * 20)
1361 # TODO: Capability/Configuration1 Record Identifier
1362 # TODO: Extension1 Record Identifier
1363 if p.get('msisdn') is not None:
1364 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001365 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001366
Harald Weltec0499c82021-01-21 16:06:50 +01001367 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001368 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1369
Supreeth Herlea97944b2020-03-26 10:03:25 +01001370 # EF.ACC
1371 if p.get('acc'):
1372 sw = self.update_acc(p['acc'])
1373 if sw != '9000':
1374 print("Programming ACC failed with code %s"%sw)
1375
Supreeth Herle80164052020-03-23 12:06:29 +01001376 # Populate AIDs
1377 self.read_aids()
1378
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001379 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1380 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001381 self._scc.select_path(['3f00'])
1382 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001383 if p.get('ki'):
1384 self._scc.update_binary('6f20', p['ki'], 1)
1385 if p.get('opc'):
1386 self._scc.update_binary('6f20', p['opc'], 17)
1387
1388 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001389 data, sw = self.select_adf_by_aid(adf="isim")
1390 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001391 if p.get('ki'):
1392 self._scc.update_binary('af20', p['ki'], 1)
1393 if p.get('opc'):
1394 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001395
Supreeth Herlecf727f22020-03-24 17:32:21 +01001396 # update EF.P-CSCF in ADF.ISIM
1397 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1398 if p.get('pcscf'):
1399 sw = self.update_pcscf(p['pcscf'])
1400 else:
1401 sw = self.update_pcscf("")
1402 if sw != '9000':
1403 print("Programming P-CSCF failed with code %s"%sw)
1404
1405
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001406 # update EF.DOMAIN in ADF.ISIM
1407 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1408 if p.get('ims_hdomain'):
1409 sw = self.update_domain(domain=p['ims_hdomain'])
1410 else:
1411 sw = self.update_domain()
1412
1413 if sw != '9000':
1414 print("Programming Home Network Domain Name failed with code %s"%sw)
1415
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001416 # update EF.IMPI in ADF.ISIM
1417 # TODO: Validate IMPI input
1418 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1419 if p.get('impi'):
1420 sw = self.update_impi(p['impi'])
1421 else:
1422 sw = self.update_impi()
1423 if sw != '9000':
1424 print("Programming IMPI failed with code %s"%sw)
1425
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001426 # update EF.IMPU in ADF.ISIM
1427 # TODO: Validate IMPU input
1428 # Support multiple IMPU if there is enough space
1429 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1430 if p.get('impu'):
1431 sw = self.update_impu(p['impu'])
1432 else:
1433 sw = self.update_impu()
1434 if sw != '9000':
1435 print("Programming IMPU failed with code %s"%sw)
1436
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001437 data, sw = self.select_adf_by_aid(adf="usim")
1438 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001439 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001440 if p.get('ki'):
1441 self._scc.update_binary('af20', p['ki'], 1)
1442 if p.get('opc'):
1443 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001444
Harald Welteca673942020-06-03 15:19:40 +02001445 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001446 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001447 if p.get('mcc') and p.get('mnc'):
1448 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1449 if sw != '9000':
1450 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001451
1452 # update EF.ePDGId in ADF.USIM
1453 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1454 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001455 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001456 else:
1457 sw = self.update_epdgid("")
1458 if sw != '9000':
1459 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001460
Supreeth Herlef964df42020-03-24 13:15:37 +01001461 # update EF.ePDGSelection in ADF.USIM
1462 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1463 if p.get('epdgSelection'):
1464 epdg_plmn = p['epdgSelection']
1465 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1466 else:
1467 sw = self.update_ePDGSelection("", "")
1468 if sw != '9000':
1469 print("Programming ePDGSelection failed with code %s"%sw)
1470
1471
Supreeth Herleacc222f2020-03-24 13:26:53 +01001472 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1473 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001474 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001475 if self.file_exists(EF_USIM_ADF_map['UST']):
1476 if p.get('epdgSelection') and p.get('epdgid'):
1477 sw = self.update_ust(106, 1)
1478 if sw != '9000':
1479 print("Programming UST failed with code %s"%sw)
1480 sw = self.update_ust(107, 1)
1481 if sw != '9000':
1482 print("Programming UST failed with code %s"%sw)
1483
Supreeth Herle44e04622020-03-25 10:34:28 +01001484 sw = self.update_ust(95, 0)
1485 if sw != '9000':
1486 print("Programming UST failed with code %s"%sw)
1487 sw = self.update_ust(99, 0)
1488 if sw != '9000':
1489 print("Programming UST failed with code %s"%sw)
1490 sw = self.update_ust(115, 0)
1491 if sw != '9000':
1492 print("Programming UST failed with code %s"%sw)
1493
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001494 return
1495
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001496
Todd Neal9eeadfc2018-04-25 15:36:29 -05001497# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001498_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001499 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001500 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001501
1502def card_autodetect(scc):
1503 for kls in _cards_classes:
1504 card = kls.autodetect(scc)
1505 if card is not None:
1506 card.reset()
1507 return card
1508 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001509
1510def card_detect(ctype, scc):
1511 # Detect type if needed
1512 card = None
1513 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1514
1515 if ctype in ("auto", "auto_once"):
1516 for kls in _cards_classes:
1517 card = kls.autodetect(scc)
1518 if card:
1519 print("Autodetected card type: %s" % card.name)
1520 card.reset()
1521 break
1522
1523 if card is None:
1524 print("Autodetection failed")
1525 return None
1526
1527 if ctype == "auto_once":
1528 ctype = card.name
1529
1530 elif ctype in ctypes:
1531 card = ctypes[ctype](scc)
1532
1533 else:
1534 raise ValueError("Unknown card type: %s" % ctype)
1535
1536 return card