blob: 2319a56dca9092050b982604f46d21ca65746a34 [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"
287 if adf in aid_map:
288 return aid_map[adf]
289 return None
290
291 def _complete_aid(self, aid) -> str:
292 """find the complete version of an ADF.U/ISIM AID"""
293 # Find full AID by partial AID:
294 if is_hex(aid):
295 for aid_known in self._aids:
296 if len(aid_known) >= len(aid) and aid == aid_known[0:len(aid)]:
297 return aid_known
298 return None
299
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100300 def select_adf_by_aid(self, adf="usim"):
Philipp Maier305e1f82021-10-29 16:35:22 +0200301 """Select ADF.U/ISIM in the Card using its full AID"""
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100302 if is_hex(adf):
Philipp Maier46c61542021-11-16 16:36:50 +0100303 aid = adf
304 else:
305 aid = self._get_aid(adf)
306 if aid:
307 aid_full = self._complete_aid(aid)
308 if aid_full:
309 return self._scc.select_adf(aid_full)
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100310 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100311
Philipp Maier5c2cc662020-05-12 16:27:12 +0200312 def erase_binary(self, ef):
Philipp Maier305e1f82021-10-29 16:35:22 +0200313 """Erase the contents of a file"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200314 len = self._scc.binary_size(ef)
315 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
316
Philipp Maier5c2cc662020-05-12 16:27:12 +0200317 def erase_record(self, ef, rec_no):
Philipp Maier305e1f82021-10-29 16:35:22 +0200318 """Erase the contents of a single record"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200319 len = self._scc.record_size(ef)
320 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
321
Philipp Maier30b225f2021-10-29 16:41:46 +0200322 def set_apdu_parameter(self, cla, sel_ctrl):
323 """Set apdu parameters (class byte and selection control bytes)"""
324 self._scc.cla_byte = cla
325 self._scc.sel_ctrl = sel_ctrl
326
327 def get_apdu_parameter(self):
328 """Get apdu parameters (class byte and selection control bytes)"""
329 return (self._scc.cla_byte, self._scc.sel_ctrl)
330
Philipp Maierbb73e512021-05-05 16:14:00 +0200331class UsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200332
333 name = 'USIM'
334
Harald Welteca673942020-06-03 15:19:40 +0200335 def __init__(self, ssc):
336 super(UsimCard, self).__init__(ssc)
337
338 def read_ehplmn(self):
339 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
340 if sw == '9000':
341 return (format_xplmn(res), sw)
342 else:
343 return (None, sw)
344
345 def update_ehplmn(self, mcc, mnc):
346 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
347 size = len(data[0]) // 2
348 ehplmn = enc_plmn(mcc, mnc)
349 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
350 return sw
351
herlesupreethf8232db2020-09-29 10:03:06 +0200352 def read_epdgid(self):
353 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
354 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200355 try:
356 addr, addr_type = dec_addr_tlv(res)
357 except:
358 addr = None
359 addr_type = None
360 return (format_addr(addr, addr_type), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200361 else:
362 return (None, sw)
363
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200364 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100365 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
366 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100367 addr_type = get_addr_type(epdgid)
368 if addr_type == None:
369 raise ValueError("Unknown ePDG Id address type or invalid address provided")
370 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100371 else:
372 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200373 data, sw = self._scc.update_binary(
374 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
375 return sw
Harald Welteca673942020-06-03 15:19:40 +0200376
Supreeth Herle99d55552020-03-24 13:03:43 +0100377 def read_ePDGSelection(self):
378 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
379 if sw == '9000':
380 return (format_ePDGSelection(res), sw)
381 else:
382 return (None, sw)
383
Supreeth Herlef964df42020-03-24 13:15:37 +0100384 def update_ePDGSelection(self, mcc, mnc):
385 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
386 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
387 # Reset contents
388 # 80 - Tag value
389 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
390 elif sw == '9000':
391 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
392 return sw
393
herlesupreeth4a3580b2020-09-29 10:11:36 +0200394 def read_ust(self):
395 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
396 if sw == '9000':
397 # Print those which are available
398 return ([res, dec_st(res, table="usim")], sw)
399 else:
400 return ([None, None], sw)
401
Supreeth Herleacc222f2020-03-24 13:26:53 +0100402 def update_ust(self, service, bit=1):
403 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
404 if sw == '9000':
405 content = enc_st(res, service, bit)
406 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
407 return sw
408
Philipp Maierbb73e512021-05-05 16:14:00 +0200409class IsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200410
411 name = 'ISIM'
412
herlesupreethecbada92020-12-23 09:24:29 +0100413 def __init__(self, ssc):
414 super(IsimCard, self).__init__(ssc)
415
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100416 def read_pcscf(self):
417 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
418 pcscf_recs = ""
419 for i in range(0, rec_cnt):
420 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
421 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200422 try:
423 addr, addr_type = dec_addr_tlv(res)
424 except:
425 addr = None
426 addr_type = None
427 content = format_addr(addr, addr_type)
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100428 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
429 else:
430 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
431 return pcscf_recs
432
Supreeth Herlecf727f22020-03-24 17:32:21 +0100433 def update_pcscf(self, pcscf):
434 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100435 addr_type = get_addr_type(pcscf)
436 if addr_type == None:
437 raise ValueError("Unknown PCSCF address type or invalid address provided")
438 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100439 else:
440 # Just the tag value
441 content = '80'
442 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100443 pcscf_tlv = rpad(content, rec_size_bytes*2)
444 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100445 return sw
446
Supreeth Herle05b28072020-03-25 10:23:48 +0100447 def read_domain(self):
448 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
449 if sw == '9000':
450 # Skip the inital tag value ('80') byte and get length of contents
451 length = int(res[2:4], 16)
452 content = h2s(res[4:4+(length*2)])
453 return (content, sw)
454 else:
455 return (None, sw)
456
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100457 def update_domain(self, domain=None, mcc=None, mnc=None):
458 hex_str = ""
459 if domain:
460 hex_str = s2h(domain)
461 elif mcc and mnc:
462 # MCC and MNC always has 3 digits in domain form
463 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
464 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
465
466 # Build TLV
467 tlv = TLV(['80'])
468 content = tlv.build({'80': hex_str})
469
470 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
471 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
472 return sw
473
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100474 def read_impi(self):
475 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
476 if sw == '9000':
477 # Skip the inital tag value ('80') byte and get length of contents
478 length = int(res[2:4], 16)
479 content = h2s(res[4:4+(length*2)])
480 return (content, sw)
481 else:
482 return (None, sw)
483
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100484 def update_impi(self, impi=None):
485 hex_str = ""
486 if impi:
487 hex_str = s2h(impi)
488 # Build TLV
489 tlv = TLV(['80'])
490 content = tlv.build({'80': hex_str})
491
492 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
493 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
494 return sw
495
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100496 def read_impu(self):
497 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
498 impu_recs = ""
499 for i in range(0, rec_cnt):
500 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
501 if sw == '9000':
502 # Skip the inital tag value ('80') byte and get length of contents
503 length = int(res[2:4], 16)
504 content = h2s(res[4:4+(length*2)])
505 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
506 else:
507 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
508 return impu_recs
509
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100510 def update_impu(self, impu=None):
511 hex_str = ""
512 if impu:
513 hex_str = s2h(impu)
514 # Build TLV
515 tlv = TLV(['80'])
516 content = tlv.build({'80': hex_str})
517
518 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
519 impu_tlv = rpad(content, rec_size_bytes*2)
520 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
521 return sw
522
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200523 def read_iari(self):
524 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
525 uiari_recs = ""
526 for i in range(0, rec_cnt):
527 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
528 if sw == '9000':
529 # Skip the inital tag value ('80') byte and get length of contents
530 length = int(res[2:4], 16)
531 content = h2s(res[4:4+(length*2)])
532 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
533 else:
534 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
535 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100536
Philipp Maierbb73e512021-05-05 16:14:00 +0200537class MagicSimBase(abc.ABC, SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100538 """
539 Theses cards uses several record based EFs to store the provider infos,
540 each possible provider uses a specific record number in each EF. The
541 indexes used are ( where N is the number of providers supported ) :
542 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200543 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100544
545 * 3f00/7f4d/8f0c : Operator Name
546
547 bytes 0-15 : provider name, padded with 0xff
548 byte 16 : length of the provider name
549 byte 17 : 01 for valid records, 00 otherwise
550
551 * 3f00/7f4d/8f0d : Programmable Binary EFs
552
553 * 3f00/7f4d/8f0e : Programmable Record EFs
554
555 """
556
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200557 _files = { } # type: Dict[str, Tuple[str, int, bool]]
558 _ki_file = None # type: Optional[str]
559
Sylvain Munaut76504e02010-12-07 00:24:32 +0100560 @classmethod
561 def autodetect(kls, scc):
562 try:
563 for p, l, t in kls._files.values():
564 if not t:
565 continue
566 if scc.record_size(['3f00', '7f4d', p]) != l:
567 return None
568 except:
569 return None
570
571 return kls(scc)
572
573 def _get_count(self):
574 """
575 Selects the file and returns the total number of entries
576 and entry size
577 """
578 f = self._files['name']
579
Harald Weltec0499c82021-01-21 16:06:50 +0100580 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100581 rec_len = int(r[-1][28:30], 16)
582 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200583 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100584
585 if (rec_cnt < 1) or (rec_len != f[1]):
586 raise RuntimeError('Bad card type')
587
588 return rec_cnt
589
590 def program(self, p):
591 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100592 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100593
594 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400595 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100596
597 # Operator name ( 3f00/7f4d/8f0c )
598 self._scc.update_record(self._files['name'][0], 2,
599 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
600 )
601
602 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
603 v = ''
604
605 # inline Ki
606 if self._ki_file is None:
607 v += p['ki']
608
609 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400610 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100611
612 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400613 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614
615 # Ki
616 if self._ki_file:
617 v += self._ki_file + '10' + p['ki']
618
619 # PLMN_Sel
620 v+= '6f30' + '18' + rpad(hplmn, 36)
621
Alexander Chemeris21885242013-07-02 16:56:55 +0400622 # ACC
623 # This doesn't work with "fake" SuperSIM cards,
624 # but will hopefully work with real SuperSIMs.
625 if p.get('acc') is not None:
626 v+= '6f78' + '02' + lpad(p['acc'], 4)
627
Sylvain Munaut76504e02010-12-07 00:24:32 +0100628 self._scc.update_record(self._files['b_ef'][0], 1,
629 rpad(v, self._files['b_ef'][1]*2)
630 )
631
632 # SMSP ( 3f00/7f4d/8f0e )
633 # FIXME
634
635 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100636 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100637 tl = int(r[-1][4:8], 16)
638
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400639 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100640 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
641
642 def erase(self):
643 # Dummy
644 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200645 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100646 ofs = 1
647 fv = v[1] * 'ff'
648 if k == 'name':
649 ofs = 2
650 fv = fv[0:-4] + '0000'
651 df[v[0]] = (fv, ofs)
652
653 # Write
654 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200655 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100656 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
657
658
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200659class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100660
661 name = 'supersim'
662
663 _files = {
664 'name' : ('8f0c', 18, True),
665 'b_ef' : ('8f0d', 74, True),
666 'r_ef' : ('8f0e', 50, True),
667 }
668
669 _ki_file = None
670
671
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200672class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100673
674 name = 'magicsim'
675
676 _files = {
677 'name' : ('8f0c', 18, True),
678 'b_ef' : ('8f0d', 130, True),
679 'r_ef' : ('8f0e', 102, False),
680 }
681
682 _ki_file = '6f1b'
683
684
Philipp Maierbb73e512021-05-05 16:14:00 +0200685class FakeMagicSim(SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100686 """
687 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200688 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100689 1 to N.
690 """
691
692 name = 'fakemagicsim'
693
694 @classmethod
695 def autodetect(kls, scc):
696 try:
697 if scc.record_size(['3f00', '000c']) != 0x5a:
698 return None
699 except:
700 return None
701
702 return kls(scc)
703
704 def _get_infos(self):
705 """
706 Selects the file and returns the total number of entries
707 and entry size
708 """
709
Harald Weltec0499c82021-01-21 16:06:50 +0100710 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100711 rec_len = int(r[-1][28:30], 16)
712 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200713 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100714
715 if (rec_cnt < 1) or (rec_len != 0x5a):
716 raise RuntimeError('Bad card type')
717
718 return rec_cnt, rec_len
719
720 def program(self, p):
721 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100722 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100723 tl = int(r[-1][4:8], 16)
724
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400725 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100726 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
727
728 # Get total number of entries and entry size
729 rec_cnt, rec_len = self._get_infos()
730
731 # Set first entry
732 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200733 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100734 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200735 enc_iccid(p['iccid']) + # 10b ICCID
736 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
737 p['ki'] + # 16b Ki
738 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100739 )
740 self._scc.update_record('000c', 1, entry)
741
742 def erase(self):
743 # Get total number of entries and entry size
744 rec_cnt, rec_len = self._get_infos()
745
746 # Erase all entries
747 entry = 'ff' * rec_len
748 for i in range(0, rec_cnt):
749 self._scc.update_record('000c', 1+i, entry)
750
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200751
Philipp Maierbb73e512021-05-05 16:14:00 +0200752class GrcardSim(SimCard):
Harald Welte3156d902011-03-22 21:48:19 +0100753 """
754 Greencard (grcard.cn) HZCOS GSM SIM
755 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
756 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
757 """
758
759 name = 'grcardsim'
760
761 @classmethod
762 def autodetect(kls, scc):
763 return None
764
765 def program(self, p):
766 # We don't really know yet what ADM PIN 4 is about
767 #self._scc.verify_chv(4, h2b("4444444444444444"))
768
769 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100770 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200771 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100772 else:
773 pin = h2b("4444444444444444")
774 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100775
776 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100777 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400778 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100779
780 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100781 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400782 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100783
784 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400785 if p.get('acc') is not None:
786 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100787
788 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200789 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100790 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200791 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100792
793 # Set the Ki using proprietary command
794 pdu = '80d4020010' + p['ki']
795 data, sw = self._scc._tp.send_apdu(pdu)
796
797 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100798 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100799 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400800 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100801 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
802
803 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100804 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100805 size = int(r[-1][4:8], 16)
806 # FIXME
807
808 # FIXME: EF.MSISDN
809
Sylvain Munaut76504e02010-12-07 00:24:32 +0100810
Harald Weltee10394b2011-12-07 12:34:14 +0100811class SysmoSIMgr1(GrcardSim):
812 """
813 sysmocom sysmoSIM-GR1
814 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
815 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
816 """
817 name = 'sysmosim-gr1'
818
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200819 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200820 def autodetect(kls, scc):
821 try:
822 # Look for ATR
823 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
824 return kls(scc)
825 except:
826 return None
827 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200828
Harald Welteca673942020-06-03 15:19:40 +0200829class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100830 """
831 sysmocom sysmoUSIM-GR1
832 """
833 name = 'sysmoUSIM-GR1'
834
835 @classmethod
836 def autodetect(kls, scc):
837 # TODO: Access the ATR
838 return None
839
840 def program(self, p):
841 # TODO: check if verify_chv could be used or what it needs
842 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
843 # Unlock the card..
844 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
845
846 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100847 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400848 p['opc'] + # 32b OPC
849 enc_iccid(p['iccid']) + # 10b ICCID
850 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100851 )
852 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
853
Sylvain Munaut053c8952013-07-02 15:12:32 +0200854
Philipp Maierbb73e512021-05-05 16:14:00 +0200855class SysmoSIMgr2(SimCard):
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100856 """
857 sysmocom sysmoSIM-GR2
858 """
859
860 name = 'sysmoSIM-GR2'
861
862 @classmethod
863 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900864 try:
865 # Look for ATR
866 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
867 return kls(scc)
868 except:
869 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100870 return None
871
872 def program(self, p):
873
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200874 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100875 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200876
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100877 # authenticate as SUPER ADM using default key
878 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
879
880 # set ADM pin using proprietary command
881 # INS: D4
882 # P1: 3A for PIN, 3B for PUK
883 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
884 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100885 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200886 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100887 else:
888 pin = h2b("4444444444444444")
889
890 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100891 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200892
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100893 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100894
895 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100896
897 # write EF.ICCID
898 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
899
900 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100901 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200902
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100903 # write EF.IMSI
904 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
905
906 # write EF.ACC
907 if p.get('acc') is not None:
908 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
909
910 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100911 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100912 size = int(r[-1][4:8], 16)
913 hplmn = enc_plmn(p['mcc'], p['mnc'])
914 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
915
916 # set COMP128 version 0 in proprietary file
917 data, sw = self._scc.update_binary('0001', '001000')
918
919 # set Ki in proprietary file
920 data, sw = self._scc.update_binary('0001', p['ki'], 3)
921
922 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100923 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200924
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100925 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200926 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200927 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100928
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100929
Harald Welteca673942020-06-03 15:19:40 +0200930class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100931 """
932 sysmocom sysmoUSIM-SJS1
933 """
934
935 name = 'sysmoUSIM-SJS1'
936
937 def __init__(self, ssc):
938 super(SysmoUSIMSJS1, self).__init__(ssc)
939 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100940 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100941
942 @classmethod
943 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900944 try:
945 # Look for ATR
946 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"):
947 return kls(scc)
948 except:
949 return None
Jan Balke3e840672015-01-26 15:36:27 +0100950 return None
951
Harald Weltea6704252021-01-08 20:19:11 +0100952 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100953 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100954 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100955 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100956 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100957 return sw
958
959 def program(self, p):
960 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100961
962 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100963 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100964
Philipp Maiere9604882017-03-21 17:24:31 +0100965 # write EF.ICCID
966 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
967
Jan Balke3e840672015-01-26 15:36:27 +0100968 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100969 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100970
Jan Balke3e840672015-01-26 15:36:27 +0100971 # set Ki in proprietary file
972 data, sw = self._scc.update_binary('00FF', p['ki'])
973
Philipp Maier1be35bf2018-07-13 11:29:03 +0200974 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200975 if 'opc' in p:
976 content = "01" + p['opc']
977 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100978
Supreeth Herle7947d922019-06-08 07:50:53 +0200979 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100980 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200981 self.update_spn(p['name'], True, True)
Supreeth Herle7947d922019-06-08 07:50:53 +0200982
Supreeth Herlec8796a32019-12-23 12:23:42 +0100983 if p.get('acc') is not None:
984 self.update_acc(p['acc'])
985
Jan Balke3e840672015-01-26 15:36:27 +0100986 # write EF.IMSI
987 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
988
Philipp Maier2d15ea02019-03-20 12:40:36 +0100989 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200990 if p.get('mcc') and p.get('mnc'):
991 sw = self.update_plmnsel(p['mcc'], p['mnc'])
992 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100993 print("Programming PLMNsel failed with code %s"%sw)
994
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200995 # EF.PLMNwAcT
996 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100997 sw = self.update_plmn_act(p['mcc'], p['mnc'])
998 if sw != '9000':
999 print("Programming PLMNwAcT failed with code %s"%sw)
1000
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001001 # EF.OPLMNwAcT
1002 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +01001003 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1004 if sw != '9000':
1005 print("Programming OPLMNwAcT failed with code %s"%sw)
1006
Supreeth Herlef442fb42020-01-21 12:47:32 +01001007 # EF.HPLMNwAcT
1008 if p.get('mcc') and p.get('mnc'):
1009 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1010 if sw != '9000':
1011 print("Programming HPLMNwAcT failed with code %s"%sw)
1012
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001013 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001014 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1015 if p.get('mcc') and p.get('mnc'):
1016 mnc = p['mnc']
1017 else:
1018 mnc = None
1019 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +01001020 if sw != '9000':
1021 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +01001022
Daniel Willmann1d087ef2017-08-31 10:08:45 +02001023 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +02001024 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001025 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +02001026 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +01001027
Supreeth Herle5a541012019-12-22 08:59:16 +01001028 # EF.MSISDN
1029 # TODO: Alpha Identifier (currently 'ff'O * 20)
1030 # TODO: Capability/Configuration1 Record Identifier
1031 # TODO: Extension1 Record Identifier
1032 if p.get('msisdn') is not None:
1033 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001034 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +01001035
Harald Weltec0499c82021-01-21 16:06:50 +01001036 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +01001037 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
1038
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001039
herlesupreeth4a3580b2020-09-29 10:11:36 +02001040class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001041 """
1042 FairwavesSIM
1043
1044 The SIM card is operating according to the standard.
1045 For Ki/OP/OPC programming the following files are additionally open for writing:
1046 3F00/7F20/FF01 – OP/OPC:
1047 byte 1 = 0x01, bytes 2-17: OPC;
1048 byte 1 = 0x00, bytes 2-17: OP;
1049 3F00/7F20/FF02: Ki
1050 """
1051
Philipp Maier5a876312019-11-11 11:01:46 +01001052 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001053 # Propriatary files
1054 _EF_num = {
1055 'Ki': 'FF02',
1056 'OP/OPC': 'FF01',
1057 }
1058 _EF = {
1059 'Ki': DF['GSM']+[_EF_num['Ki']],
1060 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
1061 }
1062
1063 def __init__(self, ssc):
1064 super(FairwavesSIM, self).__init__(ssc)
1065 self._adm_chv_num = 0x11
1066 self._adm2_chv_num = 0x12
1067
1068
1069 @classmethod
1070 def autodetect(kls, scc):
1071 try:
1072 # Look for ATR
1073 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"):
1074 return kls(scc)
1075 except:
1076 return None
1077 return None
1078
1079
1080 def verify_adm2(self, key):
1081 '''
1082 Authenticate with ADM2 key.
1083
1084 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1085 is a key which has access to proprietary files (Ki and OP/OPC).
1086 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1087 need ADM2 key per se.
1088 '''
1089 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1090 return sw
1091
1092
1093 def read_ki(self):
1094 """
1095 Read Ki in proprietary file.
1096
1097 Requires ADM1 access level
1098 """
1099 return self._scc.read_binary(self._EF['Ki'])
1100
1101
1102 def update_ki(self, ki):
1103 """
1104 Set Ki in proprietary file.
1105
1106 Requires ADM1 access level
1107 """
1108 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1109 return sw
1110
1111
1112 def read_op_opc(self):
1113 """
1114 Read Ki in proprietary file.
1115
1116 Requires ADM1 access level
1117 """
1118 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1119 type = 'OP' if ef[0:2] == '00' else 'OPC'
1120 return ((type, ef[2:]), sw)
1121
1122
1123 def update_op(self, op):
1124 """
1125 Set OP in proprietary file.
1126
1127 Requires ADM1 access level
1128 """
1129 content = '00' + op
1130 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1131 return sw
1132
1133
1134 def update_opc(self, opc):
1135 """
1136 Set OPC in proprietary file.
1137
1138 Requires ADM1 access level
1139 """
1140 content = '01' + opc
1141 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1142 return sw
1143
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001144 def program(self, p):
Philipp Maier64b28372021-10-05 13:58:25 +02001145 # For some reason the card programming only works when the card
1146 # is handled as a classic SIM, even though it is an USIM, so we
1147 # reconfigure the class byte and the select control field on
1148 # the fly. When the programming is done the original values are
1149 # restored.
1150 cla_byte_orig = self._scc.cla_byte
1151 sel_ctrl_orig = self._scc.sel_ctrl
1152 self._scc.cla_byte = "a0"
1153 self._scc.sel_ctrl = "0000"
1154
1155 try:
1156 self._program(p)
1157 finally:
1158 # restore original cla byte and sel ctrl
1159 self._scc.cla_byte = cla_byte_orig
1160 self._scc.sel_ctrl = sel_ctrl_orig
1161
1162 def _program(self, p):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001163 # authenticate as ADM1
1164 if not p['pin_adm']:
1165 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001166 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001167
1168 # TODO: Set operator name
1169 if p.get('smsp') is not None:
1170 sw = self.update_smsp(p['smsp'])
1171 if sw != '9000':
1172 print("Programming SMSP failed with code %s"%sw)
1173 # This SIM doesn't support changing ICCID
1174 if p.get('mcc') is not None and p.get('mnc') is not None:
1175 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1176 if sw != '9000':
1177 print("Programming MCC/MNC failed with code %s"%sw)
1178 if p.get('imsi') is not None:
1179 sw = self.update_imsi(p['imsi'])
1180 if sw != '9000':
1181 print("Programming IMSI failed with code %s"%sw)
1182 if p.get('ki') is not None:
1183 sw = self.update_ki(p['ki'])
1184 if sw != '9000':
1185 print("Programming Ki failed with code %s"%sw)
1186 if p.get('opc') is not None:
1187 sw = self.update_opc(p['opc'])
1188 if sw != '9000':
1189 print("Programming OPC failed with code %s"%sw)
1190 if p.get('acc') is not None:
1191 sw = self.update_acc(p['acc'])
1192 if sw != '9000':
1193 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001194
Philipp Maierbb73e512021-05-05 16:14:00 +02001195class OpenCellsSim(SimCard):
Todd Neal9eeadfc2018-04-25 15:36:29 -05001196 """
1197 OpenCellsSim
1198
1199 """
1200
Philipp Maier5a876312019-11-11 11:01:46 +01001201 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001202
1203 def __init__(self, ssc):
1204 super(OpenCellsSim, self).__init__(ssc)
1205 self._adm_chv_num = 0x0A
1206
1207
1208 @classmethod
1209 def autodetect(kls, scc):
1210 try:
1211 # Look for ATR
1212 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"):
1213 return kls(scc)
1214 except:
1215 return None
1216 return None
1217
1218
1219 def program(self, p):
1220 if not p['pin_adm']:
1221 raise ValueError("Please provide a PIN-ADM as there is no default one")
1222 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1223
1224 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001225 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001226
1227 # write EF.ICCID
1228 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1229
Harald Weltec0499c82021-01-21 16:06:50 +01001230 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001231
1232 # set Ki in proprietary file
1233 data, sw = self._scc.update_binary('FF02', p['ki'])
1234
1235 # set OPC in proprietary file
1236 data, sw = self._scc.update_binary('FF01', p['opc'])
1237
1238 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001239 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001240
1241 # write EF.IMSI
1242 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1243
herlesupreeth4a3580b2020-09-29 10:11:36 +02001244class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001245 """
1246 WavemobileSim
1247
1248 """
1249
1250 name = 'Wavemobile-SIM'
1251
1252 def __init__(self, ssc):
1253 super(WavemobileSim, self).__init__(ssc)
1254 self._adm_chv_num = 0x0A
1255 self._scc.cla_byte = "00"
1256 self._scc.sel_ctrl = "0004" #request an FCP
1257
1258 @classmethod
1259 def autodetect(kls, scc):
1260 try:
1261 # Look for ATR
1262 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"):
1263 return kls(scc)
1264 except:
1265 return None
1266 return None
1267
1268 def program(self, p):
1269 if not p['pin_adm']:
1270 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001271 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001272
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001273 # EF.ICCID
1274 # TODO: Add programming of the ICCID
1275 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001276 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1277
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001278 # KI (Presumably a propritary file)
1279 # TODO: Add programming of KI
1280 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001281 print("Warning: Programming of the KI is not implemented for this type of card.")
1282
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001283 # OPc (Presumably a propritary file)
1284 # TODO: Add programming of OPc
1285 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001286 print("Warning: Programming of the OPc is not implemented for this type of card.")
1287
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001288 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001289 if p.get('smsp'):
1290 sw = self.update_smsp(p['smsp'])
1291 if sw != '9000':
1292 print("Programming SMSP failed with code %s"%sw)
1293
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001294 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001295 if p.get('imsi'):
1296 sw = self.update_imsi(p['imsi'])
1297 if sw != '9000':
1298 print("Programming IMSI failed with code %s"%sw)
1299
1300 # EF.ACC
1301 if p.get('acc'):
1302 sw = self.update_acc(p['acc'])
1303 if sw != '9000':
1304 print("Programming ACC failed with code %s"%sw)
1305
1306 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001307 if p.get('mcc') and p.get('mnc'):
1308 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1309 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001310 print("Programming PLMNsel failed with code %s"%sw)
1311
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001312 # EF.PLMNwAcT
1313 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001314 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1315 if sw != '9000':
1316 print("Programming PLMNwAcT failed with code %s"%sw)
1317
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001318 # EF.OPLMNwAcT
1319 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001320 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1321 if sw != '9000':
1322 print("Programming OPLMNwAcT failed with code %s"%sw)
1323
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001324 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001325 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1326 if p.get('mcc') and p.get('mnc'):
1327 mnc = p['mnc']
1328 else:
1329 mnc = None
1330 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001331 if sw != '9000':
1332 print("Programming AD failed with code %s"%sw)
1333
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001334 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001335
Todd Neal9eeadfc2018-04-25 15:36:29 -05001336
herlesupreethb0c7d122020-12-23 09:25:46 +01001337class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001338 """
1339 sysmocom sysmoISIM-SJA2
1340 """
1341
1342 name = 'sysmoISIM-SJA2'
1343
1344 def __init__(self, ssc):
1345 super(SysmoISIMSJA2, self).__init__(ssc)
1346 self._scc.cla_byte = "00"
1347 self._scc.sel_ctrl = "0004" #request an FCP
1348
1349 @classmethod
1350 def autodetect(kls, scc):
1351 try:
1352 # Try card model #1
1353 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1354 if scc.get_atr() == toBytes(atr):
1355 return kls(scc)
1356
1357 # Try card model #2
1358 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1359 if scc.get_atr() == toBytes(atr):
1360 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001361
1362 # Try card model #3
1363 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1364 if scc.get_atr() == toBytes(atr):
1365 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001366 except:
1367 return None
1368 return None
1369
Harald Weltea6704252021-01-08 20:19:11 +01001370 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001371 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001372 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001373 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001374 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001375 return sw
1376
1377 def program(self, p):
1378 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001379
1380 # This type of card does not allow to reprogram the ICCID.
1381 # Reprogramming the ICCID would mess up the card os software
1382 # license management, so the ICCID must be kept at its factory
1383 # setting!
1384 if p.get('iccid'):
1385 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1386
1387 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001388 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001389
Robert Falkenberg54595362021-04-06 12:04:34 +02001390 # set Service Provider Name
1391 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +02001392 self.update_spn(p['name'], True, True)
Robert Falkenberg54595362021-04-06 12:04:34 +02001393
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001394 # write EF.IMSI
1395 if p.get('imsi'):
1396 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1397
1398 # EF.PLMNsel
1399 if p.get('mcc') and p.get('mnc'):
1400 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1401 if sw != '9000':
1402 print("Programming PLMNsel failed with code %s"%sw)
1403
1404 # EF.PLMNwAcT
1405 if p.get('mcc') and p.get('mnc'):
1406 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1407 if sw != '9000':
1408 print("Programming PLMNwAcT failed with code %s"%sw)
1409
1410 # EF.OPLMNwAcT
1411 if p.get('mcc') and p.get('mnc'):
1412 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1413 if sw != '9000':
1414 print("Programming OPLMNwAcT failed with code %s"%sw)
1415
Harald Welte32f0d412020-05-05 17:35:57 +02001416 # EF.HPLMNwAcT
1417 if p.get('mcc') and p.get('mnc'):
1418 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1419 if sw != '9000':
1420 print("Programming HPLMNwAcT failed with code %s"%sw)
1421
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001422 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001423 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1424 if p.get('mcc') and p.get('mnc'):
1425 mnc = p['mnc']
1426 else:
1427 mnc = None
1428 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001429 if sw != '9000':
1430 print("Programming AD failed with code %s"%sw)
1431
1432 # EF.SMSP
1433 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001434 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001435 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1436
Supreeth Herlec6019232020-03-26 10:00:45 +01001437 # EF.MSISDN
1438 # TODO: Alpha Identifier (currently 'ff'O * 20)
1439 # TODO: Capability/Configuration1 Record Identifier
1440 # TODO: Extension1 Record Identifier
1441 if p.get('msisdn') is not None:
1442 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001443 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001444
Harald Weltec0499c82021-01-21 16:06:50 +01001445 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001446 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1447
Supreeth Herlea97944b2020-03-26 10:03:25 +01001448 # EF.ACC
1449 if p.get('acc'):
1450 sw = self.update_acc(p['acc'])
1451 if sw != '9000':
1452 print("Programming ACC failed with code %s"%sw)
1453
Supreeth Herle80164052020-03-23 12:06:29 +01001454 # Populate AIDs
1455 self.read_aids()
1456
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001457 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1458 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001459 self._scc.select_path(['3f00'])
1460 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001461 if p.get('ki'):
1462 self._scc.update_binary('6f20', p['ki'], 1)
1463 if p.get('opc'):
1464 self._scc.update_binary('6f20', p['opc'], 17)
1465
1466 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001467 data, sw = self.select_adf_by_aid(adf="isim")
1468 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001469 if p.get('ki'):
1470 self._scc.update_binary('af20', p['ki'], 1)
1471 if p.get('opc'):
1472 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001473
Supreeth Herlecf727f22020-03-24 17:32:21 +01001474 # update EF.P-CSCF in ADF.ISIM
1475 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1476 if p.get('pcscf'):
1477 sw = self.update_pcscf(p['pcscf'])
1478 else:
1479 sw = self.update_pcscf("")
1480 if sw != '9000':
1481 print("Programming P-CSCF failed with code %s"%sw)
1482
1483
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001484 # update EF.DOMAIN in ADF.ISIM
1485 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1486 if p.get('ims_hdomain'):
1487 sw = self.update_domain(domain=p['ims_hdomain'])
1488 else:
1489 sw = self.update_domain()
1490
1491 if sw != '9000':
1492 print("Programming Home Network Domain Name failed with code %s"%sw)
1493
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001494 # update EF.IMPI in ADF.ISIM
1495 # TODO: Validate IMPI input
1496 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1497 if p.get('impi'):
1498 sw = self.update_impi(p['impi'])
1499 else:
1500 sw = self.update_impi()
1501 if sw != '9000':
1502 print("Programming IMPI failed with code %s"%sw)
1503
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001504 # update EF.IMPU in ADF.ISIM
1505 # TODO: Validate IMPU input
1506 # Support multiple IMPU if there is enough space
1507 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1508 if p.get('impu'):
1509 sw = self.update_impu(p['impu'])
1510 else:
1511 sw = self.update_impu()
1512 if sw != '9000':
1513 print("Programming IMPU failed with code %s"%sw)
1514
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001515 data, sw = self.select_adf_by_aid(adf="usim")
1516 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001517 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001518 if p.get('ki'):
1519 self._scc.update_binary('af20', p['ki'], 1)
1520 if p.get('opc'):
1521 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001522
Harald Welteca673942020-06-03 15:19:40 +02001523 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001524 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001525 if p.get('mcc') and p.get('mnc'):
1526 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1527 if sw != '9000':
1528 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001529
1530 # update EF.ePDGId in ADF.USIM
1531 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1532 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001533 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001534 else:
1535 sw = self.update_epdgid("")
1536 if sw != '9000':
1537 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001538
Supreeth Herlef964df42020-03-24 13:15:37 +01001539 # update EF.ePDGSelection in ADF.USIM
1540 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1541 if p.get('epdgSelection'):
1542 epdg_plmn = p['epdgSelection']
1543 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1544 else:
1545 sw = self.update_ePDGSelection("", "")
1546 if sw != '9000':
1547 print("Programming ePDGSelection failed with code %s"%sw)
1548
1549
Supreeth Herleacc222f2020-03-24 13:26:53 +01001550 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1551 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001552 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001553 if self.file_exists(EF_USIM_ADF_map['UST']):
1554 if p.get('epdgSelection') and p.get('epdgid'):
1555 sw = self.update_ust(106, 1)
1556 if sw != '9000':
1557 print("Programming UST failed with code %s"%sw)
1558 sw = self.update_ust(107, 1)
1559 if sw != '9000':
1560 print("Programming UST failed with code %s"%sw)
1561
Supreeth Herle44e04622020-03-25 10:34:28 +01001562 sw = self.update_ust(95, 0)
1563 if sw != '9000':
1564 print("Programming UST failed with code %s"%sw)
1565 sw = self.update_ust(99, 0)
1566 if sw != '9000':
1567 print("Programming UST failed with code %s"%sw)
1568 sw = self.update_ust(115, 0)
1569 if sw != '9000':
1570 print("Programming UST failed with code %s"%sw)
1571
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001572 return
1573
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001574
Todd Neal9eeadfc2018-04-25 15:36:29 -05001575# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001576_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001577 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001578 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001579
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001580def card_detect(ctype, scc):
1581 # Detect type if needed
1582 card = None
1583 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1584
Philipp Maier64773092021-10-05 14:42:01 +02001585 if ctype == "auto":
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001586 for kls in _cards_classes:
1587 card = kls.autodetect(scc)
1588 if card:
1589 print("Autodetected card type: %s" % card.name)
1590 card.reset()
1591 break
1592
1593 if card is None:
1594 print("Autodetection failed")
1595 return None
1596
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001597 elif ctype in ctypes:
1598 card = ctypes[ctype](scc)
1599
1600 else:
1601 raise ValueError("Unknown card type: %s" % ctype)
1602
1603 return card