blob: 45e44a2b937002ed0cda7e50d8a70220c3ec4c27 [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):
Philipp Maier946226a2021-10-29 18:31:03 +020063 rc = self._scc.reset_card()
64 if rc is 1:
65 return self._scc.get_atr()
66 else:
67 return None
Sylvain Munaut76504e02010-12-07 00:24:32 +010068
Philipp Maierd58c6322020-05-12 16:47:45 +020069 def erase(self):
70 print("warning: erasing is not supported for specified card type!")
71 return
72
Harald Welteca673942020-06-03 15:19:40 +020073 def file_exists(self, fid):
Harald Weltec0499c82021-01-21 16:06:50 +010074 res_arr = self._scc.try_select_path(fid)
Harald Welteca673942020-06-03 15:19:40 +020075 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020076 if res[1] != '9000':
77 return False
Harald Welteca673942020-06-03 15:19:40 +020078 return True
79
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030080 def verify_adm(self, key):
Philipp Maier305e1f82021-10-29 16:35:22 +020081 """Authenticate with ADM key"""
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030082 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
83 return sw
84
85 def read_iccid(self):
86 (res, sw) = self._scc.read_binary(EF['ICCID'])
87 if sw == '9000':
88 return (dec_iccid(res), sw)
89 else:
90 return (None, sw)
91
92 def read_imsi(self):
93 (res, sw) = self._scc.read_binary(EF['IMSI'])
94 if sw == '9000':
95 return (dec_imsi(res), sw)
96 else:
97 return (None, sw)
98
99 def update_imsi(self, imsi):
100 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
101 return sw
102
103 def update_acc(self, acc):
Robert Falkenberg75487ae2021-04-01 16:14:27 +0200104 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4, c='0'))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300105 return sw
106
Supreeth Herlea850a472020-03-19 12:44:11 +0100107 def read_hplmn_act(self):
108 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
109 if sw == '9000':
110 return (format_xplmn_w_act(res), sw)
111 else:
112 return (None, sw)
113
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300114 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
115 """
116 Update Home PLMN with access technology bit-field
117
118 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
119 in ETSI TS 151 011 for the details of the access_tech field coding.
120 Some common values:
121 access_tech = '0080' # Only GSM is selected
Harald Weltec9cdce32021-04-11 10:28:28 +0200122 access_tech = 'FFFF' # All technologies selected, even Reserved for Future Use ones
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300123 """
124 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100125 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700126 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300127 hplmn = enc_plmn(mcc, mnc)
128 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700129 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300130 return sw
131
Supreeth Herle1757b262020-03-19 12:43:11 +0100132 def read_oplmn_act(self):
133 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
134 if sw == '9000':
135 return (format_xplmn_w_act(res), sw)
136 else:
137 return (None, sw)
138
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200139 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
Philipp Maier305e1f82021-10-29 16:35:22 +0200140 """get size and write EF.OPLMNwAcT, See note in update_hplmn_act()"""
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200141 data = self._scc.read_binary(EF['OPLMNwAcT'], 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['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200146 return sw
147
Supreeth Herle14084402020-03-19 12:42:10 +0100148 def read_plmn_act(self):
149 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
150 if sw == '9000':
151 return (format_xplmn_w_act(res), sw)
152 else:
153 return (None, sw)
154
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200155 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
Philipp Maier305e1f82021-10-29 16:35:22 +0200156 """get size and write EF.PLMNwAcT, See note in update_hplmn_act()"""
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200157 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700158 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200159 hplmn = enc_plmn(mcc, mnc)
160 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700161 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200162 return sw
163
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200164 def update_plmnsel(self, mcc, mnc):
165 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700166 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200167 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200168 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
169 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200170
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300171 def update_smsp(self, smsp):
172 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
173 return sw
174
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100175 def update_ad(self, mnc=None, opmode=None, ofm=None):
176 """
177 Update Administrative Data (AD)
Philipp Maieree908ae2019-03-21 16:21:12 +0100178
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100179 See Sec. "4.2.18 EF_AD (Administrative Data)"
180 in 3GPP TS 31.102 for the details of the EF_AD contents.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200181
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100182 Set any parameter to None to keep old value(s) on card.
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200183
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100184 Parameters:
185 mnc (str): MNC of IMSI
186 opmode (Hex-str, 1 Byte): MS Operation Mode
187 ofm (Hex-str, 1 Byte): Operational Feature Monitor (OFM) aka Ciphering Indicator
188
189 Returns:
190 str: Return code of write operation
191 """
192
193 ad = EF_AD()
194
195 # read from card
196 raw_hex_data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200197 abstract_data = ad.decode_hex(raw_hex_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100198
199 # perform updates
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200200 if mnc and abstract_data['extensions']:
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100201 mnclen = len(str(mnc))
202 if mnclen == 1:
203 mnclen = 2
204 if mnclen > 3:
205 raise RuntimeError('invalid length of mnc "{}"'.format(mnc))
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200206 abstract_data['extensions']['mnc_len'] = mnclen
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100207 if opmode:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200208 opmode_num = int(opmode, 16)
209 if opmode_num in [int(v) for v in EF_AD.OP_MODE]:
210 abstract_data['ms_operation_mode'] = opmode_num
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100211 else:
212 raise RuntimeError('invalid opmode "{}"'.format(opmode))
213 if ofm:
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200214 abstract_data['ofm'] = bool(int(ofm, 16))
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100215
216 # write to card
Robert Falkenberg9d16fbc2021-04-12 11:43:22 +0200217 raw_hex_data = ad.encode_hex(abstract_data)
Robert Falkenbergd0505bd2021-02-24 14:06:18 +0100218 data, sw = self._scc.update_binary(EF['AD'], raw_hex_data)
Philipp Maieree908ae2019-03-21 16:21:12 +0100219 return sw
220
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300221 def read_spn(self):
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200222 (content, sw) = self._scc.read_binary(EF['SPN'])
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300223 if sw == '9000':
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200224 abstract_data = EF_SPN().decode_hex(content)
225 show_in_hplmn = abstract_data['show_in_hplmn']
226 hide_in_oplmn = abstract_data['hide_in_oplmn']
227 name = abstract_data['spn']
228 return ((name, show_in_hplmn, hide_in_oplmn), sw)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300229 else:
230 return (None, sw)
231
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200232 def update_spn(self, name="", show_in_hplmn=False, hide_in_oplmn=False):
233 abstract_data = {
234 'hide_in_oplmn' : hide_in_oplmn,
235 'show_in_hplmn' : show_in_hplmn,
236 'spn' : name,
237 }
238 content = EF_SPN().encode_hex(abstract_data)
239 data, sw = self._scc.update_binary(EF['SPN'], content)
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300240 return sw
241
Supreeth Herled21349a2020-04-01 08:37:47 +0200242 def read_binary(self, ef, length=None, offset=0):
243 ef_path = ef in EF and EF[ef] or ef
244 return self._scc.read_binary(ef_path, length, offset)
245
Supreeth Herlead10d662020-04-01 08:43:08 +0200246 def read_record(self, ef, rec_no):
247 ef_path = ef in EF and EF[ef] or ef
248 return self._scc.read_record(ef_path, rec_no)
249
Supreeth Herle98a69272020-03-18 12:14:48 +0100250 def read_gid1(self):
251 (res, sw) = self._scc.read_binary(EF['GID1'])
252 if sw == '9000':
253 return (res, sw)
254 else:
255 return (None, sw)
256
Supreeth Herle6d66af62020-03-19 12:49:16 +0100257 def read_msisdn(self):
258 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
259 if sw == '9000':
260 return (dec_msisdn(res), sw)
261 else:
262 return (None, sw)
263
Supreeth Herlee4e98312020-03-18 11:33:14 +0100264 def read_aids(self):
Philipp Maier305e1f82021-10-29 16:35:22 +0200265 """Fetch all the AIDs present on UICC"""
Philipp Maier1e896f32021-03-10 17:02:53 +0100266 self._aids = []
Supreeth Herlee4e98312020-03-18 11:33:14 +0100267 try:
268 # Find out how many records the EF.DIR has
269 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100270 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100271 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100272 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100273 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
274 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
275 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
276 except Exception as e:
277 print("Can't read AIDs from SIM -- %s" % (str(e),))
Philipp Maier1e896f32021-03-10 17:02:53 +0100278 self._aids = []
279 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100280
Philipp Maier46c61542021-11-16 16:36:50 +0100281 @staticmethod
282 def _get_aid(adf="usim") -> str:
283 aid_map = {}
284 # First (known) halves of the U/ISIM AID
285 aid_map["usim"] = "a0000000871002"
286 aid_map["isim"] = "a0000000871004"
Philipp Maier47833bc2021-11-19 14:04:12 +0100287 adf = adf.lower()
Philipp Maier46c61542021-11-16 16:36:50 +0100288 if adf in aid_map:
289 return aid_map[adf]
290 return None
291
292 def _complete_aid(self, aid) -> str:
293 """find the complete version of an ADF.U/ISIM AID"""
294 # Find full AID by partial AID:
295 if is_hex(aid):
296 for aid_known in self._aids:
297 if len(aid_known) >= len(aid) and aid == aid_known[0:len(aid)]:
298 return aid_known
299 return None
300
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100301 def select_adf_by_aid(self, adf="usim"):
Philipp Maier305e1f82021-10-29 16:35:22 +0200302 """Select ADF.U/ISIM in the Card using its full AID"""
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100303 if is_hex(adf):
Philipp Maier46c61542021-11-16 16:36:50 +0100304 aid = adf
305 else:
306 aid = self._get_aid(adf)
307 if aid:
308 aid_full = self._complete_aid(aid)
309 if aid_full:
310 return self._scc.select_adf(aid_full)
Philipp Maier931bc662021-11-18 11:25:34 +0100311 else:
312 # If we cannot get the full AID, try with short AID
313 return self._scc.select_adf(aid)
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100314 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100315
Philipp Maier5c2cc662020-05-12 16:27:12 +0200316 def erase_binary(self, ef):
Philipp Maier305e1f82021-10-29 16:35:22 +0200317 """Erase the contents of a file"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200318 len = self._scc.binary_size(ef)
319 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
320
Philipp Maier5c2cc662020-05-12 16:27:12 +0200321 def erase_record(self, ef, rec_no):
Philipp Maier305e1f82021-10-29 16:35:22 +0200322 """Erase the contents of a single record"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200323 len = self._scc.record_size(ef)
324 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
325
Philipp Maier30b225f2021-10-29 16:41:46 +0200326 def set_apdu_parameter(self, cla, sel_ctrl):
327 """Set apdu parameters (class byte and selection control bytes)"""
328 self._scc.cla_byte = cla
329 self._scc.sel_ctrl = sel_ctrl
330
331 def get_apdu_parameter(self):
332 """Get apdu parameters (class byte and selection control bytes)"""
333 return (self._scc.cla_byte, self._scc.sel_ctrl)
334
Philipp Maierbb73e512021-05-05 16:14:00 +0200335class UsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200336
337 name = 'USIM'
338
Harald Welteca673942020-06-03 15:19:40 +0200339 def __init__(self, ssc):
340 super(UsimCard, self).__init__(ssc)
341
342 def read_ehplmn(self):
343 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
344 if sw == '9000':
345 return (format_xplmn(res), sw)
346 else:
347 return (None, sw)
348
349 def update_ehplmn(self, mcc, mnc):
350 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
351 size = len(data[0]) // 2
352 ehplmn = enc_plmn(mcc, mnc)
353 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
354 return sw
355
herlesupreethf8232db2020-09-29 10:03:06 +0200356 def read_epdgid(self):
357 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
358 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200359 try:
360 addr, addr_type = dec_addr_tlv(res)
361 except:
362 addr = None
363 addr_type = None
364 return (format_addr(addr, addr_type), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200365 else:
366 return (None, sw)
367
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200368 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100369 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
370 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100371 addr_type = get_addr_type(epdgid)
372 if addr_type == None:
373 raise ValueError("Unknown ePDG Id address type or invalid address provided")
374 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100375 else:
376 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200377 data, sw = self._scc.update_binary(
378 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
379 return sw
Harald Welteca673942020-06-03 15:19:40 +0200380
Supreeth Herle99d55552020-03-24 13:03:43 +0100381 def read_ePDGSelection(self):
382 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
383 if sw == '9000':
384 return (format_ePDGSelection(res), sw)
385 else:
386 return (None, sw)
387
Supreeth Herlef964df42020-03-24 13:15:37 +0100388 def update_ePDGSelection(self, mcc, mnc):
389 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
390 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
391 # Reset contents
392 # 80 - Tag value
393 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
394 elif sw == '9000':
395 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
396 return sw
397
herlesupreeth4a3580b2020-09-29 10:11:36 +0200398 def read_ust(self):
399 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
400 if sw == '9000':
401 # Print those which are available
402 return ([res, dec_st(res, table="usim")], sw)
403 else:
404 return ([None, None], sw)
405
Supreeth Herleacc222f2020-03-24 13:26:53 +0100406 def update_ust(self, service, bit=1):
407 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
408 if sw == '9000':
409 content = enc_st(res, service, bit)
410 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
411 return sw
412
Philipp Maierbb73e512021-05-05 16:14:00 +0200413class IsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200414
415 name = 'ISIM'
416
herlesupreethecbada92020-12-23 09:24:29 +0100417 def __init__(self, ssc):
418 super(IsimCard, self).__init__(ssc)
419
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100420 def read_pcscf(self):
421 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
422 pcscf_recs = ""
423 for i in range(0, rec_cnt):
424 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
425 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200426 try:
427 addr, addr_type = dec_addr_tlv(res)
428 except:
429 addr = None
430 addr_type = None
431 content = format_addr(addr, addr_type)
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100432 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
433 else:
434 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
435 return pcscf_recs
436
Supreeth Herlecf727f22020-03-24 17:32:21 +0100437 def update_pcscf(self, pcscf):
438 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100439 addr_type = get_addr_type(pcscf)
440 if addr_type == None:
441 raise ValueError("Unknown PCSCF address type or invalid address provided")
442 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100443 else:
444 # Just the tag value
445 content = '80'
446 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100447 pcscf_tlv = rpad(content, rec_size_bytes*2)
448 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100449 return sw
450
Supreeth Herle05b28072020-03-25 10:23:48 +0100451 def read_domain(self):
452 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
453 if sw == '9000':
454 # Skip the inital tag value ('80') byte and get length of contents
455 length = int(res[2:4], 16)
456 content = h2s(res[4:4+(length*2)])
457 return (content, sw)
458 else:
459 return (None, sw)
460
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100461 def update_domain(self, domain=None, mcc=None, mnc=None):
462 hex_str = ""
463 if domain:
464 hex_str = s2h(domain)
465 elif mcc and mnc:
466 # MCC and MNC always has 3 digits in domain form
467 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
468 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
469
470 # Build TLV
471 tlv = TLV(['80'])
472 content = tlv.build({'80': hex_str})
473
474 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
475 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
476 return sw
477
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100478 def read_impi(self):
479 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
480 if sw == '9000':
481 # Skip the inital tag value ('80') byte and get length of contents
482 length = int(res[2:4], 16)
483 content = h2s(res[4:4+(length*2)])
484 return (content, sw)
485 else:
486 return (None, sw)
487
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100488 def update_impi(self, impi=None):
489 hex_str = ""
490 if impi:
491 hex_str = s2h(impi)
492 # Build TLV
493 tlv = TLV(['80'])
494 content = tlv.build({'80': hex_str})
495
496 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
497 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
498 return sw
499
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100500 def read_impu(self):
501 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
502 impu_recs = ""
503 for i in range(0, rec_cnt):
504 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
505 if sw == '9000':
506 # Skip the inital tag value ('80') byte and get length of contents
507 length = int(res[2:4], 16)
508 content = h2s(res[4:4+(length*2)])
509 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
510 else:
511 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
512 return impu_recs
513
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100514 def update_impu(self, impu=None):
515 hex_str = ""
516 if impu:
517 hex_str = s2h(impu)
518 # Build TLV
519 tlv = TLV(['80'])
520 content = tlv.build({'80': hex_str})
521
522 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
523 impu_tlv = rpad(content, rec_size_bytes*2)
524 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
525 return sw
526
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200527 def read_iari(self):
528 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
529 uiari_recs = ""
530 for i in range(0, rec_cnt):
531 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
532 if sw == '9000':
533 # Skip the inital tag value ('80') byte and get length of contents
534 length = int(res[2:4], 16)
535 content = h2s(res[4:4+(length*2)])
536 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
537 else:
538 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
539 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100540
Philipp Maierbb73e512021-05-05 16:14:00 +0200541class MagicSimBase(abc.ABC, SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100542 """
543 Theses cards uses several record based EFs to store the provider infos,
544 each possible provider uses a specific record number in each EF. The
545 indexes used are ( where N is the number of providers supported ) :
546 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200547 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100548
549 * 3f00/7f4d/8f0c : Operator Name
550
551 bytes 0-15 : provider name, padded with 0xff
552 byte 16 : length of the provider name
553 byte 17 : 01 for valid records, 00 otherwise
554
555 * 3f00/7f4d/8f0d : Programmable Binary EFs
556
557 * 3f00/7f4d/8f0e : Programmable Record EFs
558
559 """
560
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200561 _files = { } # type: Dict[str, Tuple[str, int, bool]]
562 _ki_file = None # type: Optional[str]
563
Sylvain Munaut76504e02010-12-07 00:24:32 +0100564 @classmethod
565 def autodetect(kls, scc):
566 try:
567 for p, l, t in kls._files.values():
568 if not t:
569 continue
570 if scc.record_size(['3f00', '7f4d', p]) != l:
571 return None
572 except:
573 return None
574
575 return kls(scc)
576
577 def _get_count(self):
578 """
579 Selects the file and returns the total number of entries
580 and entry size
581 """
582 f = self._files['name']
583
Harald Weltec0499c82021-01-21 16:06:50 +0100584 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100585 rec_len = int(r[-1][28:30], 16)
586 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200587 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100588
589 if (rec_cnt < 1) or (rec_len != f[1]):
590 raise RuntimeError('Bad card type')
591
592 return rec_cnt
593
594 def program(self, p):
595 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100596 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100597
598 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400599 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100600
601 # Operator name ( 3f00/7f4d/8f0c )
602 self._scc.update_record(self._files['name'][0], 2,
603 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
604 )
605
606 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
607 v = ''
608
609 # inline Ki
610 if self._ki_file is None:
611 v += p['ki']
612
613 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400614 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100615
616 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400617 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100618
619 # Ki
620 if self._ki_file:
621 v += self._ki_file + '10' + p['ki']
622
623 # PLMN_Sel
624 v+= '6f30' + '18' + rpad(hplmn, 36)
625
Alexander Chemeris21885242013-07-02 16:56:55 +0400626 # ACC
627 # This doesn't work with "fake" SuperSIM cards,
628 # but will hopefully work with real SuperSIMs.
629 if p.get('acc') is not None:
630 v+= '6f78' + '02' + lpad(p['acc'], 4)
631
Sylvain Munaut76504e02010-12-07 00:24:32 +0100632 self._scc.update_record(self._files['b_ef'][0], 1,
633 rpad(v, self._files['b_ef'][1]*2)
634 )
635
636 # SMSP ( 3f00/7f4d/8f0e )
637 # FIXME
638
639 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100640 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100641 tl = int(r[-1][4:8], 16)
642
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400643 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100644 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
645
646 def erase(self):
647 # Dummy
648 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200649 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100650 ofs = 1
651 fv = v[1] * 'ff'
652 if k == 'name':
653 ofs = 2
654 fv = fv[0:-4] + '0000'
655 df[v[0]] = (fv, ofs)
656
657 # Write
658 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200659 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100660 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
661
662
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200663class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100664
665 name = 'supersim'
666
667 _files = {
668 'name' : ('8f0c', 18, True),
669 'b_ef' : ('8f0d', 74, True),
670 'r_ef' : ('8f0e', 50, True),
671 }
672
673 _ki_file = None
674
675
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200676class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100677
678 name = 'magicsim'
679
680 _files = {
681 'name' : ('8f0c', 18, True),
682 'b_ef' : ('8f0d', 130, True),
683 'r_ef' : ('8f0e', 102, False),
684 }
685
686 _ki_file = '6f1b'
687
688
Philipp Maierbb73e512021-05-05 16:14:00 +0200689class FakeMagicSim(SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100690 """
691 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200692 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100693 1 to N.
694 """
695
696 name = 'fakemagicsim'
697
698 @classmethod
699 def autodetect(kls, scc):
700 try:
701 if scc.record_size(['3f00', '000c']) != 0x5a:
702 return None
703 except:
704 return None
705
706 return kls(scc)
707
708 def _get_infos(self):
709 """
710 Selects the file and returns the total number of entries
711 and entry size
712 """
713
Harald Weltec0499c82021-01-21 16:06:50 +0100714 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100715 rec_len = int(r[-1][28:30], 16)
716 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200717 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100718
719 if (rec_cnt < 1) or (rec_len != 0x5a):
720 raise RuntimeError('Bad card type')
721
722 return rec_cnt, rec_len
723
724 def program(self, p):
725 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100726 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100727 tl = int(r[-1][4:8], 16)
728
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400729 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100730 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
731
732 # Get total number of entries and entry size
733 rec_cnt, rec_len = self._get_infos()
734
735 # Set first entry
736 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200737 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100738 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200739 enc_iccid(p['iccid']) + # 10b ICCID
740 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
741 p['ki'] + # 16b Ki
742 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100743 )
744 self._scc.update_record('000c', 1, entry)
745
746 def erase(self):
747 # Get total number of entries and entry size
748 rec_cnt, rec_len = self._get_infos()
749
750 # Erase all entries
751 entry = 'ff' * rec_len
752 for i in range(0, rec_cnt):
753 self._scc.update_record('000c', 1+i, entry)
754
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200755
Philipp Maierbb73e512021-05-05 16:14:00 +0200756class GrcardSim(SimCard):
Harald Welte3156d902011-03-22 21:48:19 +0100757 """
758 Greencard (grcard.cn) HZCOS GSM SIM
759 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
760 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
761 """
762
763 name = 'grcardsim'
764
765 @classmethod
766 def autodetect(kls, scc):
767 return None
768
769 def program(self, p):
770 # We don't really know yet what ADM PIN 4 is about
771 #self._scc.verify_chv(4, h2b("4444444444444444"))
772
773 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100774 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200775 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100776 else:
777 pin = h2b("4444444444444444")
778 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100779
780 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100781 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400782 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100783
784 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100785 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400786 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100787
788 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400789 if p.get('acc') is not None:
790 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100791
792 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200793 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100794 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200795 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100796
797 # Set the Ki using proprietary command
798 pdu = '80d4020010' + p['ki']
799 data, sw = self._scc._tp.send_apdu(pdu)
800
801 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100802 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100803 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400804 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100805 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
806
807 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100808 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100809 size = int(r[-1][4:8], 16)
810 # FIXME
811
812 # FIXME: EF.MSISDN
813
Sylvain Munaut76504e02010-12-07 00:24:32 +0100814
Harald Weltee10394b2011-12-07 12:34:14 +0100815class SysmoSIMgr1(GrcardSim):
816 """
817 sysmocom sysmoSIM-GR1
818 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
819 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
820 """
821 name = 'sysmosim-gr1'
822
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200823 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200824 def autodetect(kls, scc):
825 try:
826 # Look for ATR
827 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
828 return kls(scc)
829 except:
830 return None
831 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200832
Harald Welteca673942020-06-03 15:19:40 +0200833class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100834 """
835 sysmocom sysmoUSIM-GR1
836 """
837 name = 'sysmoUSIM-GR1'
838
839 @classmethod
840 def autodetect(kls, scc):
841 # TODO: Access the ATR
842 return None
843
844 def program(self, p):
845 # TODO: check if verify_chv could be used or what it needs
846 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
847 # Unlock the card..
848 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
849
850 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100851 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400852 p['opc'] + # 32b OPC
853 enc_iccid(p['iccid']) + # 10b ICCID
854 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100855 )
856 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
857
Sylvain Munaut053c8952013-07-02 15:12:32 +0200858
Philipp Maierbb73e512021-05-05 16:14:00 +0200859class SysmoSIMgr2(SimCard):
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100860 """
861 sysmocom sysmoSIM-GR2
862 """
863
864 name = 'sysmoSIM-GR2'
865
866 @classmethod
867 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900868 try:
869 # Look for ATR
870 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
871 return kls(scc)
872 except:
873 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100874 return None
875
876 def program(self, p):
877
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200878 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100879 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200880
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100881 # authenticate as SUPER ADM using default key
882 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
883
884 # set ADM pin using proprietary command
885 # INS: D4
886 # P1: 3A for PIN, 3B for PUK
887 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
888 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100889 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200890 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100891 else:
892 pin = h2b("4444444444444444")
893
894 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100895 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200896
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100897 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100898
899 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100900
901 # write EF.ICCID
902 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
903
904 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100905 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200906
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100907 # write EF.IMSI
908 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
909
910 # write EF.ACC
911 if p.get('acc') is not None:
912 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
913
914 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100915 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100916 size = int(r[-1][4:8], 16)
917 hplmn = enc_plmn(p['mcc'], p['mnc'])
918 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
919
920 # set COMP128 version 0 in proprietary file
921 data, sw = self._scc.update_binary('0001', '001000')
922
923 # set Ki in proprietary file
924 data, sw = self._scc.update_binary('0001', p['ki'], 3)
925
926 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100927 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200928
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100929 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200930 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200931 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100932
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100933
Harald Welteca673942020-06-03 15:19:40 +0200934class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100935 """
936 sysmocom sysmoUSIM-SJS1
937 """
938
939 name = 'sysmoUSIM-SJS1'
940
941 def __init__(self, ssc):
942 super(SysmoUSIMSJS1, self).__init__(ssc)
943 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100944 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100945
946 @classmethod
947 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900948 try:
949 # Look for ATR
950 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"):
951 return kls(scc)
952 except:
953 return None
Jan Balke3e840672015-01-26 15:36:27 +0100954 return None
955
Harald Weltea6704252021-01-08 20:19:11 +0100956 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100957 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100958 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100959 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100960 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100961 return sw
962
963 def program(self, p):
964 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100965
966 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100967 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100968
Philipp Maiere9604882017-03-21 17:24:31 +0100969 # write EF.ICCID
970 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
971
Jan Balke3e840672015-01-26 15:36:27 +0100972 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100973 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100974
Jan Balke3e840672015-01-26 15:36:27 +0100975 # set Ki in proprietary file
976 data, sw = self._scc.update_binary('00FF', p['ki'])
977
Philipp Maier1be35bf2018-07-13 11:29:03 +0200978 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200979 if 'opc' in p:
980 content = "01" + p['opc']
981 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100982
Supreeth Herle7947d922019-06-08 07:50:53 +0200983 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100984 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200985 self.update_spn(p['name'], True, True)
Supreeth Herle7947d922019-06-08 07:50:53 +0200986
Supreeth Herlec8796a32019-12-23 12:23:42 +0100987 if p.get('acc') is not None:
988 self.update_acc(p['acc'])
989
Jan Balke3e840672015-01-26 15:36:27 +0100990 # write EF.IMSI
991 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
992
Philipp Maier2d15ea02019-03-20 12:40:36 +0100993 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200994 if p.get('mcc') and p.get('mnc'):
995 sw = self.update_plmnsel(p['mcc'], p['mnc'])
996 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100997 print("Programming PLMNsel failed with code %s"%sw)
998
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200999 # EF.PLMNwAcT
1000 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +01001001 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1002 if sw != '9000':
1003 print("Programming PLMNwAcT failed with code %s"%sw)
1004
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001005 # EF.OPLMNwAcT
1006 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +01001007 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1008 if sw != '9000':
1009 print("Programming OPLMNwAcT failed with code %s"%sw)
1010
Supreeth Herlef442fb42020-01-21 12:47:32 +01001011 # EF.HPLMNwAcT
1012 if p.get('mcc') and p.get('mnc'):
1013 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1014 if sw != '9000':
1015 print("Programming HPLMNwAcT failed with code %s"%sw)
1016
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001017 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001018 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1019 if p.get('mcc') and p.get('mnc'):
1020 mnc = p['mnc']
1021 else:
1022 mnc = None
1023 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +01001024 if sw != '9000':
1025 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +01001026
Daniel Willmann1d087ef2017-08-31 10:08:45 +02001027 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +02001028 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001029 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +02001030 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +01001031
Supreeth Herle5a541012019-12-22 08:59:16 +01001032 # EF.MSISDN
1033 # TODO: Alpha Identifier (currently 'ff'O * 20)
1034 # TODO: Capability/Configuration1 Record Identifier
1035 # TODO: Extension1 Record Identifier
1036 if p.get('msisdn') is not None:
1037 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001038 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +01001039
Harald Weltec0499c82021-01-21 16:06:50 +01001040 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +01001041 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
1042
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001043
herlesupreeth4a3580b2020-09-29 10:11:36 +02001044class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001045 """
1046 FairwavesSIM
1047
1048 The SIM card is operating according to the standard.
1049 For Ki/OP/OPC programming the following files are additionally open for writing:
1050 3F00/7F20/FF01 – OP/OPC:
1051 byte 1 = 0x01, bytes 2-17: OPC;
1052 byte 1 = 0x00, bytes 2-17: OP;
1053 3F00/7F20/FF02: Ki
1054 """
1055
Philipp Maier5a876312019-11-11 11:01:46 +01001056 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001057 # Propriatary files
1058 _EF_num = {
1059 'Ki': 'FF02',
1060 'OP/OPC': 'FF01',
1061 }
1062 _EF = {
1063 'Ki': DF['GSM']+[_EF_num['Ki']],
1064 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
1065 }
1066
1067 def __init__(self, ssc):
1068 super(FairwavesSIM, self).__init__(ssc)
1069 self._adm_chv_num = 0x11
1070 self._adm2_chv_num = 0x12
1071
1072
1073 @classmethod
1074 def autodetect(kls, scc):
1075 try:
1076 # Look for ATR
1077 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"):
1078 return kls(scc)
1079 except:
1080 return None
1081 return None
1082
1083
1084 def verify_adm2(self, key):
1085 '''
1086 Authenticate with ADM2 key.
1087
1088 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1089 is a key which has access to proprietary files (Ki and OP/OPC).
1090 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1091 need ADM2 key per se.
1092 '''
1093 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1094 return sw
1095
1096
1097 def read_ki(self):
1098 """
1099 Read Ki in proprietary file.
1100
1101 Requires ADM1 access level
1102 """
1103 return self._scc.read_binary(self._EF['Ki'])
1104
1105
1106 def update_ki(self, ki):
1107 """
1108 Set Ki in proprietary file.
1109
1110 Requires ADM1 access level
1111 """
1112 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1113 return sw
1114
1115
1116 def read_op_opc(self):
1117 """
1118 Read Ki in proprietary file.
1119
1120 Requires ADM1 access level
1121 """
1122 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1123 type = 'OP' if ef[0:2] == '00' else 'OPC'
1124 return ((type, ef[2:]), sw)
1125
1126
1127 def update_op(self, op):
1128 """
1129 Set OP in proprietary file.
1130
1131 Requires ADM1 access level
1132 """
1133 content = '00' + op
1134 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1135 return sw
1136
1137
1138 def update_opc(self, opc):
1139 """
1140 Set OPC in proprietary file.
1141
1142 Requires ADM1 access level
1143 """
1144 content = '01' + opc
1145 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1146 return sw
1147
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001148 def program(self, p):
Philipp Maier64b28372021-10-05 13:58:25 +02001149 # For some reason the card programming only works when the card
1150 # is handled as a classic SIM, even though it is an USIM, so we
1151 # reconfigure the class byte and the select control field on
1152 # the fly. When the programming is done the original values are
1153 # restored.
1154 cla_byte_orig = self._scc.cla_byte
1155 sel_ctrl_orig = self._scc.sel_ctrl
1156 self._scc.cla_byte = "a0"
1157 self._scc.sel_ctrl = "0000"
1158
1159 try:
1160 self._program(p)
1161 finally:
1162 # restore original cla byte and sel ctrl
1163 self._scc.cla_byte = cla_byte_orig
1164 self._scc.sel_ctrl = sel_ctrl_orig
1165
1166 def _program(self, p):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001167 # authenticate as ADM1
1168 if not p['pin_adm']:
1169 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001170 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001171
1172 # TODO: Set operator name
1173 if p.get('smsp') is not None:
1174 sw = self.update_smsp(p['smsp'])
1175 if sw != '9000':
1176 print("Programming SMSP failed with code %s"%sw)
1177 # This SIM doesn't support changing ICCID
1178 if p.get('mcc') is not None and p.get('mnc') is not None:
1179 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1180 if sw != '9000':
1181 print("Programming MCC/MNC failed with code %s"%sw)
1182 if p.get('imsi') is not None:
1183 sw = self.update_imsi(p['imsi'])
1184 if sw != '9000':
1185 print("Programming IMSI failed with code %s"%sw)
1186 if p.get('ki') is not None:
1187 sw = self.update_ki(p['ki'])
1188 if sw != '9000':
1189 print("Programming Ki failed with code %s"%sw)
1190 if p.get('opc') is not None:
1191 sw = self.update_opc(p['opc'])
1192 if sw != '9000':
1193 print("Programming OPC failed with code %s"%sw)
1194 if p.get('acc') is not None:
1195 sw = self.update_acc(p['acc'])
1196 if sw != '9000':
1197 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001198
Philipp Maierbb73e512021-05-05 16:14:00 +02001199class OpenCellsSim(SimCard):
Todd Neal9eeadfc2018-04-25 15:36:29 -05001200 """
1201 OpenCellsSim
1202
1203 """
1204
Philipp Maier5a876312019-11-11 11:01:46 +01001205 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001206
1207 def __init__(self, ssc):
1208 super(OpenCellsSim, self).__init__(ssc)
1209 self._adm_chv_num = 0x0A
1210
1211
1212 @classmethod
1213 def autodetect(kls, scc):
1214 try:
1215 # Look for ATR
1216 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"):
1217 return kls(scc)
1218 except:
1219 return None
1220 return None
1221
1222
1223 def program(self, p):
1224 if not p['pin_adm']:
1225 raise ValueError("Please provide a PIN-ADM as there is no default one")
1226 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1227
1228 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001229 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001230
1231 # write EF.ICCID
1232 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1233
Harald Weltec0499c82021-01-21 16:06:50 +01001234 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001235
1236 # set Ki in proprietary file
1237 data, sw = self._scc.update_binary('FF02', p['ki'])
1238
1239 # set OPC in proprietary file
1240 data, sw = self._scc.update_binary('FF01', p['opc'])
1241
1242 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001243 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001244
1245 # write EF.IMSI
1246 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1247
herlesupreeth4a3580b2020-09-29 10:11:36 +02001248class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001249 """
1250 WavemobileSim
1251
1252 """
1253
1254 name = 'Wavemobile-SIM'
1255
1256 def __init__(self, ssc):
1257 super(WavemobileSim, self).__init__(ssc)
1258 self._adm_chv_num = 0x0A
1259 self._scc.cla_byte = "00"
1260 self._scc.sel_ctrl = "0004" #request an FCP
1261
1262 @classmethod
1263 def autodetect(kls, scc):
1264 try:
1265 # Look for ATR
1266 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"):
1267 return kls(scc)
1268 except:
1269 return None
1270 return None
1271
1272 def program(self, p):
1273 if not p['pin_adm']:
1274 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001275 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001276
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001277 # EF.ICCID
1278 # TODO: Add programming of the ICCID
1279 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001280 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1281
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001282 # KI (Presumably a propritary file)
1283 # TODO: Add programming of KI
1284 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001285 print("Warning: Programming of the KI is not implemented for this type of card.")
1286
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001287 # OPc (Presumably a propritary file)
1288 # TODO: Add programming of OPc
1289 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001290 print("Warning: Programming of the OPc is not implemented for this type of card.")
1291
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001292 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001293 if p.get('smsp'):
1294 sw = self.update_smsp(p['smsp'])
1295 if sw != '9000':
1296 print("Programming SMSP failed with code %s"%sw)
1297
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001298 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001299 if p.get('imsi'):
1300 sw = self.update_imsi(p['imsi'])
1301 if sw != '9000':
1302 print("Programming IMSI failed with code %s"%sw)
1303
1304 # EF.ACC
1305 if p.get('acc'):
1306 sw = self.update_acc(p['acc'])
1307 if sw != '9000':
1308 print("Programming ACC failed with code %s"%sw)
1309
1310 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001311 if p.get('mcc') and p.get('mnc'):
1312 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1313 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001314 print("Programming PLMNsel failed with code %s"%sw)
1315
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001316 # EF.PLMNwAcT
1317 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001318 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1319 if sw != '9000':
1320 print("Programming PLMNwAcT failed with code %s"%sw)
1321
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001322 # EF.OPLMNwAcT
1323 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001324 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1325 if sw != '9000':
1326 print("Programming OPLMNwAcT failed with code %s"%sw)
1327
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001328 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001329 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1330 if p.get('mcc') and p.get('mnc'):
1331 mnc = p['mnc']
1332 else:
1333 mnc = None
1334 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001335 if sw != '9000':
1336 print("Programming AD failed with code %s"%sw)
1337
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001338 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001339
Todd Neal9eeadfc2018-04-25 15:36:29 -05001340
herlesupreethb0c7d122020-12-23 09:25:46 +01001341class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001342 """
1343 sysmocom sysmoISIM-SJA2
1344 """
1345
1346 name = 'sysmoISIM-SJA2'
1347
1348 def __init__(self, ssc):
1349 super(SysmoISIMSJA2, self).__init__(ssc)
1350 self._scc.cla_byte = "00"
1351 self._scc.sel_ctrl = "0004" #request an FCP
1352
1353 @classmethod
1354 def autodetect(kls, scc):
1355 try:
1356 # Try card model #1
1357 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1358 if scc.get_atr() == toBytes(atr):
1359 return kls(scc)
1360
1361 # Try card model #2
1362 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1363 if scc.get_atr() == toBytes(atr):
1364 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001365
1366 # Try card model #3
1367 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1368 if scc.get_atr() == toBytes(atr):
1369 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001370 except:
1371 return None
1372 return None
1373
Harald Weltea6704252021-01-08 20:19:11 +01001374 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001375 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001376 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001377 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001378 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001379 return sw
1380
1381 def program(self, p):
1382 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001383
1384 # This type of card does not allow to reprogram the ICCID.
1385 # Reprogramming the ICCID would mess up the card os software
1386 # license management, so the ICCID must be kept at its factory
1387 # setting!
1388 if p.get('iccid'):
1389 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1390
1391 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001392 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001393
Robert Falkenberg54595362021-04-06 12:04:34 +02001394 # set Service Provider Name
1395 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +02001396 self.update_spn(p['name'], True, True)
Robert Falkenberg54595362021-04-06 12:04:34 +02001397
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001398 # write EF.IMSI
1399 if p.get('imsi'):
1400 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1401
1402 # EF.PLMNsel
1403 if p.get('mcc') and p.get('mnc'):
1404 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1405 if sw != '9000':
1406 print("Programming PLMNsel failed with code %s"%sw)
1407
1408 # EF.PLMNwAcT
1409 if p.get('mcc') and p.get('mnc'):
1410 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1411 if sw != '9000':
1412 print("Programming PLMNwAcT failed with code %s"%sw)
1413
1414 # EF.OPLMNwAcT
1415 if p.get('mcc') and p.get('mnc'):
1416 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1417 if sw != '9000':
1418 print("Programming OPLMNwAcT failed with code %s"%sw)
1419
Harald Welte32f0d412020-05-05 17:35:57 +02001420 # EF.HPLMNwAcT
1421 if p.get('mcc') and p.get('mnc'):
1422 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1423 if sw != '9000':
1424 print("Programming HPLMNwAcT failed with code %s"%sw)
1425
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001426 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001427 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1428 if p.get('mcc') and p.get('mnc'):
1429 mnc = p['mnc']
1430 else:
1431 mnc = None
1432 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001433 if sw != '9000':
1434 print("Programming AD failed with code %s"%sw)
1435
1436 # EF.SMSP
1437 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001438 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001439 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1440
Supreeth Herlec6019232020-03-26 10:00:45 +01001441 # EF.MSISDN
1442 # TODO: Alpha Identifier (currently 'ff'O * 20)
1443 # TODO: Capability/Configuration1 Record Identifier
1444 # TODO: Extension1 Record Identifier
1445 if p.get('msisdn') is not None:
1446 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001447 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001448
Harald Weltec0499c82021-01-21 16:06:50 +01001449 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001450 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1451
Supreeth Herlea97944b2020-03-26 10:03:25 +01001452 # EF.ACC
1453 if p.get('acc'):
1454 sw = self.update_acc(p['acc'])
1455 if sw != '9000':
1456 print("Programming ACC failed with code %s"%sw)
1457
Supreeth Herle80164052020-03-23 12:06:29 +01001458 # Populate AIDs
1459 self.read_aids()
1460
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001461 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1462 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001463 self._scc.select_path(['3f00'])
1464 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001465 if p.get('ki'):
1466 self._scc.update_binary('6f20', p['ki'], 1)
1467 if p.get('opc'):
1468 self._scc.update_binary('6f20', p['opc'], 17)
1469
1470 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001471 data, sw = self.select_adf_by_aid(adf="isim")
1472 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001473 if p.get('ki'):
1474 self._scc.update_binary('af20', p['ki'], 1)
1475 if p.get('opc'):
1476 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001477
Supreeth Herlecf727f22020-03-24 17:32:21 +01001478 # update EF.P-CSCF in ADF.ISIM
1479 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1480 if p.get('pcscf'):
1481 sw = self.update_pcscf(p['pcscf'])
1482 else:
1483 sw = self.update_pcscf("")
1484 if sw != '9000':
1485 print("Programming P-CSCF failed with code %s"%sw)
1486
1487
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001488 # update EF.DOMAIN in ADF.ISIM
1489 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1490 if p.get('ims_hdomain'):
1491 sw = self.update_domain(domain=p['ims_hdomain'])
1492 else:
1493 sw = self.update_domain()
1494
1495 if sw != '9000':
1496 print("Programming Home Network Domain Name failed with code %s"%sw)
1497
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001498 # update EF.IMPI in ADF.ISIM
1499 # TODO: Validate IMPI input
1500 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1501 if p.get('impi'):
1502 sw = self.update_impi(p['impi'])
1503 else:
1504 sw = self.update_impi()
1505 if sw != '9000':
1506 print("Programming IMPI failed with code %s"%sw)
1507
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001508 # update EF.IMPU in ADF.ISIM
1509 # TODO: Validate IMPU input
1510 # Support multiple IMPU if there is enough space
1511 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1512 if p.get('impu'):
1513 sw = self.update_impu(p['impu'])
1514 else:
1515 sw = self.update_impu()
1516 if sw != '9000':
1517 print("Programming IMPU failed with code %s"%sw)
1518
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001519 data, sw = self.select_adf_by_aid(adf="usim")
1520 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001521 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001522 if p.get('ki'):
1523 self._scc.update_binary('af20', p['ki'], 1)
1524 if p.get('opc'):
1525 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001526
Harald Welteca673942020-06-03 15:19:40 +02001527 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001528 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001529 if p.get('mcc') and p.get('mnc'):
1530 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1531 if sw != '9000':
1532 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001533
1534 # update EF.ePDGId in ADF.USIM
1535 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1536 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001537 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001538 else:
1539 sw = self.update_epdgid("")
1540 if sw != '9000':
1541 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001542
Supreeth Herlef964df42020-03-24 13:15:37 +01001543 # update EF.ePDGSelection in ADF.USIM
1544 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1545 if p.get('epdgSelection'):
1546 epdg_plmn = p['epdgSelection']
1547 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1548 else:
1549 sw = self.update_ePDGSelection("", "")
1550 if sw != '9000':
1551 print("Programming ePDGSelection failed with code %s"%sw)
1552
1553
Supreeth Herleacc222f2020-03-24 13:26:53 +01001554 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1555 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001556 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001557 if self.file_exists(EF_USIM_ADF_map['UST']):
1558 if p.get('epdgSelection') and p.get('epdgid'):
1559 sw = self.update_ust(106, 1)
1560 if sw != '9000':
1561 print("Programming UST failed with code %s"%sw)
1562 sw = self.update_ust(107, 1)
1563 if sw != '9000':
1564 print("Programming UST failed with code %s"%sw)
1565
Supreeth Herle44e04622020-03-25 10:34:28 +01001566 sw = self.update_ust(95, 0)
1567 if sw != '9000':
1568 print("Programming UST failed with code %s"%sw)
1569 sw = self.update_ust(99, 0)
1570 if sw != '9000':
1571 print("Programming UST failed with code %s"%sw)
1572 sw = self.update_ust(115, 0)
1573 if sw != '9000':
1574 print("Programming UST failed with code %s"%sw)
1575
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001576 return
1577
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001578
Todd Neal9eeadfc2018-04-25 15:36:29 -05001579# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001580_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001581 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001582 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001583
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001584def card_detect(ctype, scc):
1585 # Detect type if needed
1586 card = None
1587 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1588
Philipp Maier64773092021-10-05 14:42:01 +02001589 if ctype == "auto":
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001590 for kls in _cards_classes:
1591 card = kls.autodetect(scc)
1592 if card:
1593 print("Autodetected card type: %s" % card.name)
1594 card.reset()
1595 break
1596
1597 if card is None:
1598 print("Autodetection failed")
1599 return None
1600
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001601 elif ctype in ctypes:
1602 card = ctypes[ctype](scc)
1603
1604 else:
1605 raise ValueError("Unknown card type: %s" % ctype)
1606
1607 return card