blob: 4511271ecbf70f378b3184ca2cf481d4c6528cb8 [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 Falkenbergb07a3e92021-05-07 15:23:20 +020028from pySim.ts_51_011 import EF, DF, EF_AD, EF_SPN
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
Philipp Maierbe18f2a2021-04-30 15:00:27 +020035def format_addr(addr:str, addr_type:str) -> str:
36 """
37 helper function to format an FQDN (addr_type = '00') or IPv4
38 (addr_type = '01') address string into a printable string that
39 contains the hexadecimal representation and the original address
40 string (addr)
41 """
42 res = ""
43 if addr_type == '00': #FQDN
44 res += "\t%s # %s\n" % (s2h(addr), addr)
45 elif addr_type == '01': #IPv4
46 octets = addr.split(".")
47 addr_hex = ""
48 for o in octets:
49 addr_hex += ("%02x" % int(o))
50 res += "\t%s # %s\n" % (addr_hex, addr)
51 return res
52
Philipp Maierbb73e512021-05-05 16:14:00 +020053class SimCard(object):
Sylvain Munaut76504e02010-12-07 00:24:32 +010054
Philipp Maierfc5f28d2021-05-05 12:18:41 +020055 name = 'SIM'
56
Sylvain Munaut76504e02010-12-07 00:24:32 +010057 def __init__(self, scc):
58 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030059 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010060 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010061
Sylvain Munaut76504e02010-12-07 00:24:32 +010062 def reset(self):
63 self._scc.reset_card()
64
Philipp Maierd58c6322020-05-12 16:47:45 +020065 def erase(self):
66 print("warning: erasing is not supported for specified card type!")
67 return
68
Harald Welteca673942020-06-03 15:19:40 +020069 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010070 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020071 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020072 if res[1] != '9000':
73 return False
Harald Welteca673942020-06-03 15:19:40 +020074 return True
75
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030076 def verify_adm(self, key):
Philipp Maier305e1f82021-10-29 16:35:22 +020077 """Authenticate with ADM key"""
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030078 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
79 return sw
80
81 def read_iccid(self):
82 (res, sw) = self._scc.read_binary(EF['ICCID'])
83 if sw == '9000':
84 return (dec_iccid(res), sw)
85 else:
86 return (None, sw)
87
88 def read_imsi(self):
89 (res, sw) = self._scc.read_binary(EF['IMSI'])
90 if sw == '9000':
91 return (dec_imsi(res), sw)
92 else:
93 return (None, sw)
94
95 def update_imsi(self, imsi):
96 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
97 return sw
98
99 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +0200100 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300101 return sw
102
Supreeth Herlea850a472020-03-19 12:44:11 +0100103 def read_hplmn_act(self):
104 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
105 if sw == '9000':
106 return (format_xplmn_w_act(res), sw)
107 else:
108 return (None, sw)
109
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300110 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
111 """
112 Update Home PLMN with access technology bit-field
113
114 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
115 in ETSI TS 151 011 for the details of the access_tech field coding.
116 Some common values:
117 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +0200118 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300119 """
120 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100121 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700122 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300123 hplmn = enc_plmn(mcc, mnc)
124 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700125 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300126 return sw
127
Supreeth Herle1757b262020-03-19 12:43:11 +0100128 def read_oplmn_act(self):
129 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
130 if sw == '9000':
131 return (format_xplmn_w_act(res), sw)
132 else:
133 return (None, sw)
134
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200135 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
Philipp Maier305e1f82021-10-29 16:35:22 +0200136 """get size and write EF.OPLMNwAcT, See note in update_hplmn_act()"""
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200137 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700138 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200139 hplmn = enc_plmn(mcc, mnc)
140 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700141 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200142 return sw
143
Supreeth Herle14084402020-03-19 12:42:10 +0100144 def read_plmn_act(self):
145 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
146 if sw == '9000':
147 return (format_xplmn_w_act(res), sw)
148 else:
149 return (None, sw)
150
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200151 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
Philipp Maier305e1f82021-10-29 16:35:22 +0200152 """get size and write EF.PLMNwAcT, See note in update_hplmn_act()"""
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200153 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700154 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200155 hplmn = enc_plmn(mcc, mnc)
156 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700157 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200158 return sw
159
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200160 def update_plmnsel(self, mcc, mnc):
161 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700162 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200163 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200164 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
165 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200166
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300167 def update_smsp(self, smsp):
168 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
169 return sw
170
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100171 def update_ad(self, mnc=None, opmode=None, ofm=None):
172 """
173 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100174
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100175 See Sec. "4.2.18 EF_AD (Administrative Data)"
176 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200177
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100178 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200179
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100180 Parameters:
181 mnc (str): MNC of IMSI
182 opmode (Hex-str, 1 Byte): MS Operation Mode
183 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
184
185 Returns:
186 str: Return code of write operation
187 """
188
189 ad = EF_AD()
190
191 # read from card
192 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200193 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100194
195 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200196 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100197 mnclen = len(str(mnc))
198 if mnclen == 1:
199 mnclen = 2
200 if mnclen > 3:
201 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200202 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100203 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200204 opmode_num = int(opmode, 16)
205 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
206 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100207 else:
208 raise RuntimeError('invalid opmode "{}"'.format(opmode))
209 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200210 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100211
212 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200213 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100214 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100215 return sw
216
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300217 def read_spn(self):
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200218 (content, sw) = self._scc.read_binary(EF['SPN'])
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300219 if sw == '9000':
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200220 abstract_data = EF_SPN().decode_hex(content)
221 show_in_hplmn = abstract_data['show_in_hplmn']
222 hide_in_oplmn = abstract_data['hide_in_oplmn']
223 name = abstract_data['spn']
224 return ((name, show_in_hplmn, hide_in_oplmn), sw)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300225 else:
226 return (None, sw)
227
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200228 def update_spn(self, name="", show_in_hplmn=False, hide_in_oplmn=False):
229 abstract_data = {
230 'hide_in_oplmn' : hide_in_oplmn,
231 'show_in_hplmn' : show_in_hplmn,
232 'spn' : name,
233 }
234 content = EF_SPN().encode_hex(abstract_data)
235 data, sw = self._scc.update_binary(EF['SPN'], content)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300236 return sw
237
Supreeth Herled21349a2020-04-01 08:37:47 +0200238 def read_binary(self, ef, length=None, offset=0):
239 ef_path = ef in EF and EF[ef] or ef
240 return self._scc.read_binary(ef_path, length, offset)
241
Supreeth Herlead10d662020-04-01 08:43:08 +0200242 def read_record(self, ef, rec_no):
243 ef_path = ef in EF and EF[ef] or ef
244 return self._scc.read_record(ef_path, rec_no)
245
Supreeth Herle98a69272020-03-18 12:14:48 +0100246 def read_gid1(self):
247 (res, sw) = self._scc.read_binary(EF['GID1'])
248 if sw == '9000':
249 return (res, sw)
250 else:
251 return (None, sw)
252
Supreeth Herle6d66af62020-03-19 12:49:16 +0100253 def read_msisdn(self):
254 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
255 if sw == '9000':
256 return (dec_msisdn(res), sw)
257 else:
258 return (None, sw)
259
Supreeth Herlee4e98312020-03-18 11:33:14 +0100260 def read_aids(self):
Philipp Maier305e1f82021-10-29 16:35:22 +0200261 """Fetch all the AIDs present on UICC"""
Philipp Maier1e896f32021-03-10 17:02:53 +0100262 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100263 try:
264 # Find out how many records the EF.DIR has
265 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100266 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100267 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100268 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100269 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
270 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
271 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
272 except Exception as e:
273 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100274 self._aids = []
275 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100276
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100277 def select_adf_by_aid(self, adf="usim"):
Philipp Maier305e1f82021-10-29 16:35:22 +0200278 """Select ADF.U/ISIM in the Card using its full AID"""
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100279 # Find full AID by partial AID:
280 if is_hex(adf):
281 for aid in self._aids:
282 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
283 return self._scc.select_adf(aid)
284 # Find full AID by application name:
285 elif adf in ["usim", "isim"]:
286 # First (known) halves of the U/ISIM AID
287 aid_map = {}
288 aid_map["usim"] = "a0000000871002"
289 aid_map["isim"] = "a0000000871004"
290 for aid in self._aids:
291 if aid_map[adf] in aid:
292 return self._scc.select_adf(aid)
293 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100294
Philipp Maier5c2cc662020-05-12 16:27:12 +0200295 def erase_binary(self, ef):
Philipp Maier305e1f82021-10-29 16:35:22 +0200296 """Erase the contents of a file"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200297 len = self._scc.binary_size(ef)
298 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
299
Philipp Maier5c2cc662020-05-12 16:27:12 +0200300 def erase_record(self, ef, rec_no):
Philipp Maier305e1f82021-10-29 16:35:22 +0200301 """Erase the contents of a single record"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200302 len = self._scc.record_size(ef)
303 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
304
Philipp Maier30b225f2021-10-29 16:41:46 +0200305 def set_apdu_parameter(self, cla, sel_ctrl):
306 """Set apdu parameters (class byte and selection control bytes)"""
307 self._scc.cla_byte = cla
308 self._scc.sel_ctrl = sel_ctrl
309
310 def get_apdu_parameter(self):
311 """Get apdu parameters (class byte and selection control bytes)"""
312 return (self._scc.cla_byte, self._scc.sel_ctrl)
313
Philipp Maierbb73e512021-05-05 16:14:00 +0200314class UsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200315
316 name = 'USIM'
317
Harald Welteca673942020-06-03 15:19:40 +0200318 def __init__(self, ssc):
319 super(UsimCard, self).__init__(ssc)
320
321 def read_ehplmn(self):
322 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
323 if sw == '9000':
324 return (format_xplmn(res), sw)
325 else:
326 return (None, sw)
327
328 def update_ehplmn(self, mcc, mnc):
329 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
330 size = len(data[0]) // 2
331 ehplmn = enc_plmn(mcc, mnc)
332 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
333 return sw
334
herlesupreethf8232db2020-09-29 10:03:06 +0200335 def read_epdgid(self):
336 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
337 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200338 try:
339 addr, addr_type = dec_addr_tlv(res)
340 except:
341 addr = None
342 addr_type = None
343 return (format_addr(addr, addr_type), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200344 else:
345 return (None, sw)
346
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200347 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100348 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
349 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100350 addr_type = get_addr_type(epdgid)
351 if addr_type == None:
352 raise ValueError("Unknown ePDG Id address type or invalid address provided")
353 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100354 else:
355 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200356 data, sw = self._scc.update_binary(
357 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
358 return sw
Harald Welteca673942020-06-03 15:19:40 +0200359
Supreeth Herle99d55552020-03-24 13:03:43 +0100360 def read_ePDGSelection(self):
361 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
362 if sw == '9000':
363 return (format_ePDGSelection(res), sw)
364 else:
365 return (None, sw)
366
Supreeth Herlef964df42020-03-24 13:15:37 +0100367 def update_ePDGSelection(self, mcc, mnc):
368 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
369 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
370 # Reset contents
371 # 80 - Tag value
372 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
373 elif sw == '9000':
374 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
375 return sw
376
herlesupreeth4a3580b2020-09-29 10:11:36 +0200377 def read_ust(self):
378 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
379 if sw == '9000':
380 # Print those which are available
381 return ([res, dec_st(res, table="usim")], sw)
382 else:
383 return ([None, None], sw)
384
Supreeth Herleacc222f2020-03-24 13:26:53 +0100385 def update_ust(self, service, bit=1):
386 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
387 if sw == '9000':
388 content = enc_st(res, service, bit)
389 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
390 return sw
391
Philipp Maierbb73e512021-05-05 16:14:00 +0200392class IsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200393
394 name = 'ISIM'
395
herlesupreethecbada92020-12-23 09:24:29 +0100396 def __init__(self, ssc):
397 super(IsimCard, self).__init__(ssc)
398
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100399 def read_pcscf(self):
400 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
401 pcscf_recs = ""
402 for i in range(0, rec_cnt):
403 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
404 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200405 try:
406 addr, addr_type = dec_addr_tlv(res)
407 except:
408 addr = None
409 addr_type = None
410 content = format_addr(addr, addr_type)
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100411 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
412 else:
413 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
414 return pcscf_recs
415
Supreeth Herlecf727f22020-03-24 17:32:21 +0100416 def update_pcscf(self, pcscf):
417 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100418 addr_type = get_addr_type(pcscf)
419 if addr_type == None:
420 raise ValueError("Unknown PCSCF address type or invalid address provided")
421 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100422 else:
423 # Just the tag value
424 content = '80'
425 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100426 pcscf_tlv = rpad(content, rec_size_bytes*2)
427 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100428 return sw
429
Supreeth Herle05b28072020-03-25 10:23:48 +0100430 def read_domain(self):
431 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
432 if sw == '9000':
433 # Skip the inital tag value ('80') byte and get length of contents
434 length = int(res[2:4], 16)
435 content = h2s(res[4:4+(length*2)])
436 return (content, sw)
437 else:
438 return (None, sw)
439
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100440 def update_domain(self, domain=None, mcc=None, mnc=None):
441 hex_str = ""
442 if domain:
443 hex_str = s2h(domain)
444 elif mcc and mnc:
445 # MCC and MNC always has 3 digits in domain form
446 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
447 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
448
449 # Build TLV
450 tlv = TLV(['80'])
451 content = tlv.build({'80': hex_str})
452
453 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
454 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
455 return sw
456
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100457 def read_impi(self):
458 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
459 if sw == '9000':
460 # Skip the inital tag value ('80') byte and get length of contents
461 length = int(res[2:4], 16)
462 content = h2s(res[4:4+(length*2)])
463 return (content, sw)
464 else:
465 return (None, sw)
466
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100467 def update_impi(self, impi=None):
468 hex_str = ""
469 if impi:
470 hex_str = s2h(impi)
471 # Build TLV
472 tlv = TLV(['80'])
473 content = tlv.build({'80': hex_str})
474
475 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
476 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
477 return sw
478
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100479 def read_impu(self):
480 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
481 impu_recs = ""
482 for i in range(0, rec_cnt):
483 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
484 if sw == '9000':
485 # Skip the inital tag value ('80') byte and get length of contents
486 length = int(res[2:4], 16)
487 content = h2s(res[4:4+(length*2)])
488 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
489 else:
490 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
491 return impu_recs
492
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100493 def update_impu(self, impu=None):
494 hex_str = ""
495 if impu:
496 hex_str = s2h(impu)
497 # Build TLV
498 tlv = TLV(['80'])
499 content = tlv.build({'80': hex_str})
500
501 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
502 impu_tlv = rpad(content, rec_size_bytes*2)
503 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
504 return sw
505
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200506 def read_iari(self):
507 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
508 uiari_recs = ""
509 for i in range(0, rec_cnt):
510 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
511 if sw == '9000':
512 # Skip the inital tag value ('80') byte and get length of contents
513 length = int(res[2:4], 16)
514 content = h2s(res[4:4+(length*2)])
515 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
516 else:
517 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
518 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100519
Philipp Maierbb73e512021-05-05 16:14:00 +0200520class MagicSimBase(abc.ABC, SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100521 """
522 Theses cards uses several record based EFs to store the provider infos,
523 each possible provider uses a specific record number in each EF. The
524 indexes used are ( where N is the number of providers supported ) :
525 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200526 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100527
528 * 3f00/7f4d/8f0c : Operator Name
529
530 bytes 0-15 : provider name, padded with 0xff
531 byte 16 : length of the provider name
532 byte 17 : 01 for valid records, 00 otherwise
533
534 * 3f00/7f4d/8f0d : Programmable Binary EFs
535
536 * 3f00/7f4d/8f0e : Programmable Record EFs
537
538 """
539
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200540 _files = { } # type: Dict[str, Tuple[str, int, bool]]
541 _ki_file = None # type: Optional[str]
542
Sylvain Munaut76504e02010-12-07 00:24:32 +0100543 @classmethod
544 def autodetect(kls, scc):
545 try:
546 for p, l, t in kls._files.values():
547 if not t:
548 continue
549 if scc.record_size(['3f00', '7f4d', p]) != l:
550 return None
551 except:
552 return None
553
554 return kls(scc)
555
556 def _get_count(self):
557 """
558 Selects the file and returns the total number of entries
559 and entry size
560 """
561 f = self._files['name']
562
Harald Weltec0499c82021-01-21 16:06:50 +0100563 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100564 rec_len = int(r[-1][28:30], 16)
565 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200566 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100567
568 if (rec_cnt < 1) or (rec_len != f[1]):
569 raise RuntimeError('Bad card type')
570
571 return rec_cnt
572
573 def program(self, p):
574 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100575 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100576
577 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400578 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100579
580 # Operator name ( 3f00/7f4d/8f0c )
581 self._scc.update_record(self._files['name'][0], 2,
582 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
583 )
584
585 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
586 v = ''
587
588 # inline Ki
589 if self._ki_file is None:
590 v += p['ki']
591
592 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400593 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100594
595 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400596 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100597
598 # Ki
599 if self._ki_file:
600 v += self._ki_file + '10' + p['ki']
601
602 # PLMN_Sel
603 v+= '6f30' + '18' + rpad(hplmn, 36)
604
Alexander Chemeris21885242013-07-02 16:56:55 +0400605 # ACC
606 # This doesn't work with "fake" SuperSIM cards,
607 # but will hopefully work with real SuperSIMs.
608 if p.get('acc') is not None:
609 v+= '6f78' + '02' + lpad(p['acc'], 4)
610
Sylvain Munaut76504e02010-12-07 00:24:32 +0100611 self._scc.update_record(self._files['b_ef'][0], 1,
612 rpad(v, self._files['b_ef'][1]*2)
613 )
614
615 # SMSP ( 3f00/7f4d/8f0e )
616 # FIXME
617
618 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100619 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100620 tl = int(r[-1][4:8], 16)
621
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400622 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100623 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
624
625 def erase(self):
626 # Dummy
627 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200628 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100629 ofs = 1
630 fv = v[1] * 'ff'
631 if k == 'name':
632 ofs = 2
633 fv = fv[0:-4] + '0000'
634 df[v[0]] = (fv, ofs)
635
636 # Write
637 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200638 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100639 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
640
641
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200642class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100643
644 name = 'supersim'
645
646 _files = {
647 'name' : ('8f0c', 18, True),
648 'b_ef' : ('8f0d', 74, True),
649 'r_ef' : ('8f0e', 50, True),
650 }
651
652 _ki_file = None
653
654
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200655class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100656
657 name = 'magicsim'
658
659 _files = {
660 'name' : ('8f0c', 18, True),
661 'b_ef' : ('8f0d', 130, True),
662 'r_ef' : ('8f0e', 102, False),
663 }
664
665 _ki_file = '6f1b'
666
667
Philipp Maierbb73e512021-05-05 16:14:00 +0200668class FakeMagicSim(SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100669 """
670 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200671 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100672 1 to N.
673 """
674
675 name = 'fakemagicsim'
676
677 @classmethod
678 def autodetect(kls, scc):
679 try:
680 if scc.record_size(['3f00', '000c']) != 0x5a:
681 return None
682 except:
683 return None
684
685 return kls(scc)
686
687 def _get_infos(self):
688 """
689 Selects the file and returns the total number of entries
690 and entry size
691 """
692
Harald Weltec0499c82021-01-21 16:06:50 +0100693 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100694 rec_len = int(r[-1][28:30], 16)
695 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200696 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100697
698 if (rec_cnt < 1) or (rec_len != 0x5a):
699 raise RuntimeError('Bad card type')
700
701 return rec_cnt, rec_len
702
703 def program(self, p):
704 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100705 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100706 tl = int(r[-1][4:8], 16)
707
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400708 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100709 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
710
711 # Get total number of entries and entry size
712 rec_cnt, rec_len = self._get_infos()
713
714 # Set first entry
715 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200716 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100717 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200718 enc_iccid(p['iccid']) + # 10b ICCID
719 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
720 p['ki'] + # 16b Ki
721 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100722 )
723 self._scc.update_record('000c', 1, entry)
724
725 def erase(self):
726 # Get total number of entries and entry size
727 rec_cnt, rec_len = self._get_infos()
728
729 # Erase all entries
730 entry = 'ff' * rec_len
731 for i in range(0, rec_cnt):
732 self._scc.update_record('000c', 1+i, entry)
733
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200734
Philipp Maierbb73e512021-05-05 16:14:00 +0200735class GrcardSim(SimCard):
Harald Welte3156d902011-03-22 21:48:19 +0100736 """
737 Greencard (grcard.cn) HZCOS GSM SIM
738 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
739 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
740 """
741
742 name = 'grcardsim'
743
744 @classmethod
745 def autodetect(kls, scc):
746 return None
747
748 def program(self, p):
749 # We don't really know yet what ADM PIN 4 is about
750 #self._scc.verify_chv(4, h2b("4444444444444444"))
751
752 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100753 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200754 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100755 else:
756 pin = h2b("4444444444444444")
757 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100758
759 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100760 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400761 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100762
763 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100764 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400765 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100766
767 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400768 if p.get('acc') is not None:
769 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100770
771 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200772 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100773 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200774 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100775
776 # Set the Ki using proprietary command
777 pdu = '80d4020010' + p['ki']
778 data, sw = self._scc._tp.send_apdu(pdu)
779
780 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100781 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100782 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400783 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100784 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
785
786 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100787 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100788 size = int(r[-1][4:8], 16)
789 # FIXME
790
791 # FIXME: EF.MSISDN
792
Sylvain Munaut76504e02010-12-07 00:24:32 +0100793
Harald Weltee10394b2011-12-07 12:34:14 +0100794class SysmoSIMgr1(GrcardSim):
795 """
796 sysmocom sysmoSIM-GR1
797 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
798 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
799 """
800 name = 'sysmosim-gr1'
801
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200802 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200803 def autodetect(kls, scc):
804 try:
805 # Look for ATR
806 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
807 return kls(scc)
808 except:
809 return None
810 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200811
Harald Welteca673942020-06-03 15:19:40 +0200812class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100813 """
814 sysmocom sysmoUSIM-GR1
815 """
816 name = 'sysmoUSIM-GR1'
817
818 @classmethod
819 def autodetect(kls, scc):
820 # TODO: Access the ATR
821 return None
822
823 def program(self, p):
824 # TODO: check if verify_chv could be used or what it needs
825 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
826 # Unlock the card..
827 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
828
829 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100830 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400831 p['opc'] + # 32b OPC
832 enc_iccid(p['iccid']) + # 10b ICCID
833 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100834 )
835 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
836
Sylvain Munaut053c8952013-07-02 15:12:32 +0200837
Philipp Maierbb73e512021-05-05 16:14:00 +0200838class SysmoSIMgr2(SimCard):
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100839 """
840 sysmocom sysmoSIM-GR2
841 """
842
843 name = 'sysmoSIM-GR2'
844
845 @classmethod
846 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900847 try:
848 # Look for ATR
849 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
850 return kls(scc)
851 except:
852 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100853 return None
854
855 def program(self, p):
856
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200857 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100858 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200859
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100860 # authenticate as SUPER ADM using default key
861 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
862
863 # set ADM pin using proprietary command
864 # INS: D4
865 # P1: 3A for PIN, 3B for PUK
866 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
867 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100868 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200869 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100870 else:
871 pin = h2b("4444444444444444")
872
873 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100874 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200875
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100876 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100877
878 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100879
880 # write EF.ICCID
881 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
882
883 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100884 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200885
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100886 # write EF.IMSI
887 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
888
889 # write EF.ACC
890 if p.get('acc') is not None:
891 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
892
893 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100894 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100895 size = int(r[-1][4:8], 16)
896 hplmn = enc_plmn(p['mcc'], p['mnc'])
897 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
898
899 # set COMP128 version 0 in proprietary file
900 data, sw = self._scc.update_binary('0001', '001000')
901
902 # set Ki in proprietary file
903 data, sw = self._scc.update_binary('0001', p['ki'], 3)
904
905 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100906 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200907
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100908 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200909 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200910 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100911
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100912
Harald Welteca673942020-06-03 15:19:40 +0200913class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100914 """
915 sysmocom sysmoUSIM-SJS1
916 """
917
918 name = 'sysmoUSIM-SJS1'
919
920 def __init__(self, ssc):
921 super(SysmoUSIMSJS1, self).__init__(ssc)
922 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100923 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100924
925 @classmethod
926 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900927 try:
928 # Look for ATR
929 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"):
930 return kls(scc)
931 except:
932 return None
Jan Balke3e840672015-01-26 15:36:27 +0100933 return None
934
Harald Weltea6704252021-01-08 20:19:11 +0100935 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100936 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100937 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100938 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100939 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100940 return sw
941
942 def program(self, p):
943 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100944
945 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100946 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100947
Philipp Maiere9604882017-03-21 17:24:31 +0100948 # write EF.ICCID
949 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
950
Jan Balke3e840672015-01-26 15:36:27 +0100951 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100952 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100953
Jan Balke3e840672015-01-26 15:36:27 +0100954 # set Ki in proprietary file
955 data, sw = self._scc.update_binary('00FF', p['ki'])
956
Philipp Maier1be35bf2018-07-13 11:29:03 +0200957 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200958 if 'opc' in p:
959 content = "01" + p['opc']
960 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100961
Supreeth Herle7947d922019-06-08 07:50:53 +0200962 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100963 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200964 self.update_spn(p['name'], True, True)
Supreeth Herle7947d922019-06-08 07:50:53 +0200965
Supreeth Herlec8796a32019-12-23 12:23:42 +0100966 if p.get('acc') is not None:
967 self.update_acc(p['acc'])
968
Jan Balke3e840672015-01-26 15:36:27 +0100969 # write EF.IMSI
970 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
971
Philipp Maier2d15ea02019-03-20 12:40:36 +0100972 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200973 if p.get('mcc') and p.get('mnc'):
974 sw = self.update_plmnsel(p['mcc'], p['mnc'])
975 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100976 print("Programming PLMNsel failed with code %s"%sw)
977
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200978 # EF.PLMNwAcT
979 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100980 sw = self.update_plmn_act(p['mcc'], p['mnc'])
981 if sw != '9000':
982 print("Programming PLMNwAcT failed with code %s"%sw)
983
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200984 # EF.OPLMNwAcT
985 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100986 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
987 if sw != '9000':
988 print("Programming OPLMNwAcT failed with code %s"%sw)
989
Supreeth Herlef442fb42020-01-21 12:47:32 +0100990 # EF.HPLMNwAcT
991 if p.get('mcc') and p.get('mnc'):
992 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
993 if sw != '9000':
994 print("Programming HPLMNwAcT failed with code %s"%sw)
995
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200996 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100997 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
998 if p.get('mcc') and p.get('mnc'):
999 mnc = p['mnc']
1000 else:
1001 mnc = None
1002 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +01001003 if sw != '9000':
1004 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +01001005
Daniel Willmann1d087ef2017-08-31 10:08:45 +02001006 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +02001007 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001008 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +02001009 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +01001010
Supreeth Herle5a541012019-12-22 08:59:16 +01001011 # EF.MSISDN
1012 # TODO: Alpha Identifier (currently 'ff'O * 20)
1013 # TODO: Capability/Configuration1 Record Identifier
1014 # TODO: Extension1 Record Identifier
1015 if p.get('msisdn') is not None:
1016 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001017 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +01001018
Harald Weltec0499c82021-01-21 16:06:50 +01001019 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +01001020 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
1021
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001022
herlesupreeth4a3580b2020-09-29 10:11:36 +02001023class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001024 """
1025 FairwavesSIM
1026
1027 The SIM card is operating according to the standard.
1028 For Ki/OP/OPC programming the following files are additionally open for writing:
1029 3F00/7F20/FF01 – OP/OPC:
1030 byte 1 = 0x01, bytes 2-17: OPC;
1031 byte 1 = 0x00, bytes 2-17: OP;
1032 3F00/7F20/FF02: Ki
1033 """
1034
Philipp Maier5a876312019-11-11 11:01:46 +01001035 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001036 # Propriatary files
1037 _EF_num = {
1038 'Ki': 'FF02',
1039 'OP/OPC': 'FF01',
1040 }
1041 _EF = {
1042 'Ki': DF['GSM']+[_EF_num['Ki']],
1043 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
1044 }
1045
1046 def __init__(self, ssc):
1047 super(FairwavesSIM, self).__init__(ssc)
1048 self._adm_chv_num = 0x11
1049 self._adm2_chv_num = 0x12
1050
1051
1052 @classmethod
1053 def autodetect(kls, scc):
1054 try:
1055 # Look for ATR
1056 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"):
1057 return kls(scc)
1058 except:
1059 return None
1060 return None
1061
1062
1063 def verify_adm2(self, key):
1064 '''
1065 Authenticate with ADM2 key.
1066
1067 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1068 is a key which has access to proprietary files (Ki and OP/OPC).
1069 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1070 need ADM2 key per se.
1071 '''
1072 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1073 return sw
1074
1075
1076 def read_ki(self):
1077 """
1078 Read Ki in proprietary file.
1079
1080 Requires ADM1 access level
1081 """
1082 return self._scc.read_binary(self._EF['Ki'])
1083
1084
1085 def update_ki(self, ki):
1086 """
1087 Set Ki in proprietary file.
1088
1089 Requires ADM1 access level
1090 """
1091 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1092 return sw
1093
1094
1095 def read_op_opc(self):
1096 """
1097 Read Ki in proprietary file.
1098
1099 Requires ADM1 access level
1100 """
1101 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1102 type = 'OP' if ef[0:2] == '00' else 'OPC'
1103 return ((type, ef[2:]), sw)
1104
1105
1106 def update_op(self, op):
1107 """
1108 Set OP in proprietary file.
1109
1110 Requires ADM1 access level
1111 """
1112 content = '00' + op
1113 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1114 return sw
1115
1116
1117 def update_opc(self, opc):
1118 """
1119 Set OPC in proprietary file.
1120
1121 Requires ADM1 access level
1122 """
1123 content = '01' + opc
1124 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1125 return sw
1126
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001127 def program(self, p):
Philipp Maier64b28372021-10-05 13:58:25 +02001128 # For some reason the card programming only works when the card
1129 # is handled as a classic SIM, even though it is an USIM, so we
1130 # reconfigure the class byte and the select control field on
1131 # the fly. When the programming is done the original values are
1132 # restored.
1133 cla_byte_orig = self._scc.cla_byte
1134 sel_ctrl_orig = self._scc.sel_ctrl
1135 self._scc.cla_byte = "a0"
1136 self._scc.sel_ctrl = "0000"
1137
1138 try:
1139 self._program(p)
1140 finally:
1141 # restore original cla byte and sel ctrl
1142 self._scc.cla_byte = cla_byte_orig
1143 self._scc.sel_ctrl = sel_ctrl_orig
1144
1145 def _program(self, p):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001146 # authenticate as ADM1
1147 if not p['pin_adm']:
1148 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001149 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001150
1151 # TODO: Set operator name
1152 if p.get('smsp') is not None:
1153 sw = self.update_smsp(p['smsp'])
1154 if sw != '9000':
1155 print("Programming SMSP failed with code %s"%sw)
1156 # This SIM doesn't support changing ICCID
1157 if p.get('mcc') is not None and p.get('mnc') is not None:
1158 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1159 if sw != '9000':
1160 print("Programming MCC/MNC failed with code %s"%sw)
1161 if p.get('imsi') is not None:
1162 sw = self.update_imsi(p['imsi'])
1163 if sw != '9000':
1164 print("Programming IMSI failed with code %s"%sw)
1165 if p.get('ki') is not None:
1166 sw = self.update_ki(p['ki'])
1167 if sw != '9000':
1168 print("Programming Ki failed with code %s"%sw)
1169 if p.get('opc') is not None:
1170 sw = self.update_opc(p['opc'])
1171 if sw != '9000':
1172 print("Programming OPC failed with code %s"%sw)
1173 if p.get('acc') is not None:
1174 sw = self.update_acc(p['acc'])
1175 if sw != '9000':
1176 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001177
Philipp Maierbb73e512021-05-05 16:14:00 +02001178class OpenCellsSim(SimCard):
Todd Neal9eeadfc2018-04-25 15:36:29 -05001179 """
1180 OpenCellsSim
1181
1182 """
1183
Philipp Maier5a876312019-11-11 11:01:46 +01001184 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001185
1186 def __init__(self, ssc):
1187 super(OpenCellsSim, self).__init__(ssc)
1188 self._adm_chv_num = 0x0A
1189
1190
1191 @classmethod
1192 def autodetect(kls, scc):
1193 try:
1194 # Look for ATR
1195 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"):
1196 return kls(scc)
1197 except:
1198 return None
1199 return None
1200
1201
1202 def program(self, p):
1203 if not p['pin_adm']:
1204 raise ValueError("Please provide a PIN-ADM as there is no default one")
1205 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1206
1207 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001208 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001209
1210 # write EF.ICCID
1211 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1212
Harald Weltec0499c82021-01-21 16:06:50 +01001213 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001214
1215 # set Ki in proprietary file
1216 data, sw = self._scc.update_binary('FF02', p['ki'])
1217
1218 # set OPC in proprietary file
1219 data, sw = self._scc.update_binary('FF01', p['opc'])
1220
1221 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001222 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001223
1224 # write EF.IMSI
1225 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1226
herlesupreeth4a3580b2020-09-29 10:11:36 +02001227class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001228 """
1229 WavemobileSim
1230
1231 """
1232
1233 name = 'Wavemobile-SIM'
1234
1235 def __init__(self, ssc):
1236 super(WavemobileSim, self).__init__(ssc)
1237 self._adm_chv_num = 0x0A
1238 self._scc.cla_byte = "00"
1239 self._scc.sel_ctrl = "0004" #request an FCP
1240
1241 @classmethod
1242 def autodetect(kls, scc):
1243 try:
1244 # Look for ATR
1245 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"):
1246 return kls(scc)
1247 except:
1248 return None
1249 return None
1250
1251 def program(self, p):
1252 if not p['pin_adm']:
1253 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001254 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001255
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001256 # EF.ICCID
1257 # TODO: Add programming of the ICCID
1258 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001259 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1260
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001261 # KI (Presumably a propritary file)
1262 # TODO: Add programming of KI
1263 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001264 print("Warning: Programming of the KI is not implemented for this type of card.")
1265
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001266 # OPc (Presumably a propritary file)
1267 # TODO: Add programming of OPc
1268 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001269 print("Warning: Programming of the OPc is not implemented for this type of card.")
1270
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001271 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001272 if p.get('smsp'):
1273 sw = self.update_smsp(p['smsp'])
1274 if sw != '9000':
1275 print("Programming SMSP failed with code %s"%sw)
1276
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001277 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001278 if p.get('imsi'):
1279 sw = self.update_imsi(p['imsi'])
1280 if sw != '9000':
1281 print("Programming IMSI failed with code %s"%sw)
1282
1283 # EF.ACC
1284 if p.get('acc'):
1285 sw = self.update_acc(p['acc'])
1286 if sw != '9000':
1287 print("Programming ACC failed with code %s"%sw)
1288
1289 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001290 if p.get('mcc') and p.get('mnc'):
1291 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1292 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001293 print("Programming PLMNsel failed with code %s"%sw)
1294
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001295 # EF.PLMNwAcT
1296 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001297 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1298 if sw != '9000':
1299 print("Programming PLMNwAcT failed with code %s"%sw)
1300
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001301 # EF.OPLMNwAcT
1302 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001303 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1304 if sw != '9000':
1305 print("Programming OPLMNwAcT failed with code %s"%sw)
1306
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001307 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001308 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1309 if p.get('mcc') and p.get('mnc'):
1310 mnc = p['mnc']
1311 else:
1312 mnc = None
1313 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001314 if sw != '9000':
1315 print("Programming AD failed with code %s"%sw)
1316
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001317 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001318
Todd Neal9eeadfc2018-04-25 15:36:29 -05001319
herlesupreethb0c7d122020-12-23 09:25:46 +01001320class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001321 """
1322 sysmocom sysmoISIM-SJA2
1323 """
1324
1325 name = 'sysmoISIM-SJA2'
1326
1327 def __init__(self, ssc):
1328 super(SysmoISIMSJA2, self).__init__(ssc)
1329 self._scc.cla_byte = "00"
1330 self._scc.sel_ctrl = "0004" #request an FCP
1331
1332 @classmethod
1333 def autodetect(kls, scc):
1334 try:
1335 # Try card model #1
1336 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1337 if scc.get_atr() == toBytes(atr):
1338 return kls(scc)
1339
1340 # Try card model #2
1341 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1342 if scc.get_atr() == toBytes(atr):
1343 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001344
1345 # Try card model #3
1346 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1347 if scc.get_atr() == toBytes(atr):
1348 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001349 except:
1350 return None
1351 return None
1352
Harald Weltea6704252021-01-08 20:19:11 +01001353 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001354 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001355 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001356 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001357 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001358 return sw
1359
1360 def program(self, p):
1361 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001362
1363 # This type of card does not allow to reprogram the ICCID.
1364 # Reprogramming the ICCID would mess up the card os software
1365 # license management, so the ICCID must be kept at its factory
1366 # setting!
1367 if p.get('iccid'):
1368 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1369
1370 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001371 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001372
Robert Falkenberg54595362021-04-06 12:04:34 +02001373 # set Service Provider Name
1374 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +02001375 self.update_spn(p['name'], True, True)
Robert Falkenberg54595362021-04-06 12:04:34 +02001376
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001377 # write EF.IMSI
1378 if p.get('imsi'):
1379 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1380
1381 # EF.PLMNsel
1382 if p.get('mcc') and p.get('mnc'):
1383 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1384 if sw != '9000':
1385 print("Programming PLMNsel failed with code %s"%sw)
1386
1387 # EF.PLMNwAcT
1388 if p.get('mcc') and p.get('mnc'):
1389 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1390 if sw != '9000':
1391 print("Programming PLMNwAcT failed with code %s"%sw)
1392
1393 # EF.OPLMNwAcT
1394 if p.get('mcc') and p.get('mnc'):
1395 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1396 if sw != '9000':
1397 print("Programming OPLMNwAcT failed with code %s"%sw)
1398
Harald Welte32f0d412020-05-05 17:35:57 +02001399 # EF.HPLMNwAcT
1400 if p.get('mcc') and p.get('mnc'):
1401 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1402 if sw != '9000':
1403 print("Programming HPLMNwAcT failed with code %s"%sw)
1404
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001405 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001406 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1407 if p.get('mcc') and p.get('mnc'):
1408 mnc = p['mnc']
1409 else:
1410 mnc = None
1411 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001412 if sw != '9000':
1413 print("Programming AD failed with code %s"%sw)
1414
1415 # EF.SMSP
1416 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001417 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001418 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1419
Supreeth Herlec6019232020-03-26 10:00:45 +01001420 # EF.MSISDN
1421 # TODO: Alpha Identifier (currently 'ff'O * 20)
1422 # TODO: Capability/Configuration1 Record Identifier
1423 # TODO: Extension1 Record Identifier
1424 if p.get('msisdn') is not None:
1425 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001426 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001427
Harald Weltec0499c82021-01-21 16:06:50 +01001428 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001429 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1430
Supreeth Herlea97944b2020-03-26 10:03:25 +01001431 # EF.ACC
1432 if p.get('acc'):
1433 sw = self.update_acc(p['acc'])
1434 if sw != '9000':
1435 print("Programming ACC failed with code %s"%sw)
1436
Supreeth Herle80164052020-03-23 12:06:29 +01001437 # Populate AIDs
1438 self.read_aids()
1439
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001440 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1441 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001442 self._scc.select_path(['3f00'])
1443 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001444 if p.get('ki'):
1445 self._scc.update_binary('6f20', p['ki'], 1)
1446 if p.get('opc'):
1447 self._scc.update_binary('6f20', p['opc'], 17)
1448
1449 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001450 data, sw = self.select_adf_by_aid(adf="isim")
1451 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001452 if p.get('ki'):
1453 self._scc.update_binary('af20', p['ki'], 1)
1454 if p.get('opc'):
1455 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001456
Supreeth Herlecf727f22020-03-24 17:32:21 +01001457 # update EF.P-CSCF in ADF.ISIM
1458 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1459 if p.get('pcscf'):
1460 sw = self.update_pcscf(p['pcscf'])
1461 else:
1462 sw = self.update_pcscf("")
1463 if sw != '9000':
1464 print("Programming P-CSCF failed with code %s"%sw)
1465
1466
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001467 # update EF.DOMAIN in ADF.ISIM
1468 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1469 if p.get('ims_hdomain'):
1470 sw = self.update_domain(domain=p['ims_hdomain'])
1471 else:
1472 sw = self.update_domain()
1473
1474 if sw != '9000':
1475 print("Programming Home Network Domain Name failed with code %s"%sw)
1476
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001477 # update EF.IMPI in ADF.ISIM
1478 # TODO: Validate IMPI input
1479 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1480 if p.get('impi'):
1481 sw = self.update_impi(p['impi'])
1482 else:
1483 sw = self.update_impi()
1484 if sw != '9000':
1485 print("Programming IMPI failed with code %s"%sw)
1486
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001487 # update EF.IMPU in ADF.ISIM
1488 # TODO: Validate IMPU input
1489 # Support multiple IMPU if there is enough space
1490 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1491 if p.get('impu'):
1492 sw = self.update_impu(p['impu'])
1493 else:
1494 sw = self.update_impu()
1495 if sw != '9000':
1496 print("Programming IMPU failed with code %s"%sw)
1497
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001498 data, sw = self.select_adf_by_aid(adf="usim")
1499 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001500 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001501 if p.get('ki'):
1502 self._scc.update_binary('af20', p['ki'], 1)
1503 if p.get('opc'):
1504 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001505
Harald Welteca673942020-06-03 15:19:40 +02001506 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001507 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001508 if p.get('mcc') and p.get('mnc'):
1509 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1510 if sw != '9000':
1511 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001512
1513 # update EF.ePDGId in ADF.USIM
1514 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1515 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001516 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001517 else:
1518 sw = self.update_epdgid("")
1519 if sw != '9000':
1520 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001521
Supreeth Herlef964df42020-03-24 13:15:37 +01001522 # update EF.ePDGSelection in ADF.USIM
1523 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1524 if p.get('epdgSelection'):
1525 epdg_plmn = p['epdgSelection']
1526 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1527 else:
1528 sw = self.update_ePDGSelection("", "")
1529 if sw != '9000':
1530 print("Programming ePDGSelection failed with code %s"%sw)
1531
1532
Supreeth Herleacc222f2020-03-24 13:26:53 +01001533 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1534 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001535 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001536 if self.file_exists(EF_USIM_ADF_map['UST']):
1537 if p.get('epdgSelection') and p.get('epdgid'):
1538 sw = self.update_ust(106, 1)
1539 if sw != '9000':
1540 print("Programming UST failed with code %s"%sw)
1541 sw = self.update_ust(107, 1)
1542 if sw != '9000':
1543 print("Programming UST failed with code %s"%sw)
1544
Supreeth Herle44e04622020-03-25 10:34:28 +01001545 sw = self.update_ust(95, 0)
1546 if sw != '9000':
1547 print("Programming UST failed with code %s"%sw)
1548 sw = self.update_ust(99, 0)
1549 if sw != '9000':
1550 print("Programming UST failed with code %s"%sw)
1551 sw = self.update_ust(115, 0)
1552 if sw != '9000':
1553 print("Programming UST failed with code %s"%sw)
1554
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001555 return
1556
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001557
Todd Neal9eeadfc2018-04-25 15:36:29 -05001558# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001559_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001560 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001561 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001562
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001563def card_detect(ctype, scc):
1564 # Detect type if needed
1565 card = None
1566 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1567
Philipp Maier64773092021-10-05 14:42:01 +02001568 if ctype == "auto":
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001569 for kls in _cards_classes:
1570 card = kls.autodetect(scc)
1571 if card:
1572 print("Autodetected card type: %s" % card.name)
1573 card.reset()
1574 break
1575
1576 if card is None:
1577 print("Autodetection failed")
1578 return None
1579
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001580 elif ctype in ctypes:
1581 card = ctypes[ctype](scc)
1582
1583 else:
1584 raise ValueError("Unknown card type: %s" % ctype)
1585
1586 return card