blob: 8f5004e4a10447288b42cb41b4a7dcde963ac2c6 [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
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100281 def select_adf_by_aid(self, adf="usim"):
Philipp Maier305e1f82021-10-29 16:35:22 +0200282 """Select ADF.U/ISIM in the Card using its full AID"""
Philipp Maiercba6dbc2021-03-11 13:03:18 +0100283 # Find full AID by partial AID:
284 if is_hex(adf):
285 for aid in self._aids:
286 if len(aid) >= len(adf) and adf == aid[0:len(adf)]:
287 return self._scc.select_adf(aid)
288 # Find full AID by application name:
289 elif adf in ["usim", "isim"]:
290 # First (known) halves of the U/ISIM AID
291 aid_map = {}
292 aid_map["usim"] = "a0000000871002"
293 aid_map["isim"] = "a0000000871004"
294 for aid in self._aids:
295 if aid_map[adf] in aid:
296 return self._scc.select_adf(aid)
297 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100298
Philipp Maier5c2cc662020-05-12 16:27:12 +0200299 def erase_binary(self, ef):
Philipp Maier305e1f82021-10-29 16:35:22 +0200300 """Erase the contents of a file"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200301 len = self._scc.binary_size(ef)
302 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
303
Philipp Maier5c2cc662020-05-12 16:27:12 +0200304 def erase_record(self, ef, rec_no):
Philipp Maier305e1f82021-10-29 16:35:22 +0200305 """Erase the contents of a single record"""
Philipp Maier5c2cc662020-05-12 16:27:12 +0200306 len = self._scc.record_size(ef)
307 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
308
Philipp Maier30b225f2021-10-29 16:41:46 +0200309 def set_apdu_parameter(self, cla, sel_ctrl):
310 """Set apdu parameters (class byte and selection control bytes)"""
311 self._scc.cla_byte = cla
312 self._scc.sel_ctrl = sel_ctrl
313
314 def get_apdu_parameter(self):
315 """Get apdu parameters (class byte and selection control bytes)"""
316 return (self._scc.cla_byte, self._scc.sel_ctrl)
317
Philipp Maierbb73e512021-05-05 16:14:00 +0200318class UsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200319
320 name = 'USIM'
321
Harald Welteca673942020-06-03 15:19:40 +0200322 def __init__(self, ssc):
323 super(UsimCard, self).__init__(ssc)
324
325 def read_ehplmn(self):
326 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
327 if sw == '9000':
328 return (format_xplmn(res), sw)
329 else:
330 return (None, sw)
331
332 def update_ehplmn(self, mcc, mnc):
333 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
334 size = len(data[0]) // 2
335 ehplmn = enc_plmn(mcc, mnc)
336 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
337 return sw
338
herlesupreethf8232db2020-09-29 10:03:06 +0200339 def read_epdgid(self):
340 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
341 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200342 try:
343 addr, addr_type = dec_addr_tlv(res)
344 except:
345 addr = None
346 addr_type = None
347 return (format_addr(addr, addr_type), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200348 else:
349 return (None, sw)
350
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200351 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100352 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
353 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100354 addr_type = get_addr_type(epdgid)
355 if addr_type == None:
356 raise ValueError("Unknown ePDG Id address type or invalid address provided")
357 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100358 else:
359 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200360 data, sw = self._scc.update_binary(
361 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
362 return sw
Harald Welteca673942020-06-03 15:19:40 +0200363
Supreeth Herle99d55552020-03-24 13:03:43 +0100364 def read_ePDGSelection(self):
365 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
366 if sw == '9000':
367 return (format_ePDGSelection(res), sw)
368 else:
369 return (None, sw)
370
Supreeth Herlef964df42020-03-24 13:15:37 +0100371 def update_ePDGSelection(self, mcc, mnc):
372 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
373 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
374 # Reset contents
375 # 80 - Tag value
376 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
377 elif sw == '9000':
378 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
379 return sw
380
herlesupreeth4a3580b2020-09-29 10:11:36 +0200381 def read_ust(self):
382 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
383 if sw == '9000':
384 # Print those which are available
385 return ([res, dec_st(res, table="usim")], sw)
386 else:
387 return ([None, None], sw)
388
Supreeth Herleacc222f2020-03-24 13:26:53 +0100389 def update_ust(self, service, bit=1):
390 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
391 if sw == '9000':
392 content = enc_st(res, service, bit)
393 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
394 return sw
395
Philipp Maierbb73e512021-05-05 16:14:00 +0200396class IsimCard(SimCard):
Philipp Maierfc5f28d2021-05-05 12:18:41 +0200397
398 name = 'ISIM'
399
herlesupreethecbada92020-12-23 09:24:29 +0100400 def __init__(self, ssc):
401 super(IsimCard, self).__init__(ssc)
402
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100403 def read_pcscf(self):
404 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
405 pcscf_recs = ""
406 for i in range(0, rec_cnt):
407 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
408 if sw == '9000':
Philipp Maierbe18f2a2021-04-30 15:00:27 +0200409 try:
410 addr, addr_type = dec_addr_tlv(res)
411 except:
412 addr = None
413 addr_type = None
414 content = format_addr(addr, addr_type)
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100415 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
416 else:
417 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
418 return pcscf_recs
419
Supreeth Herlecf727f22020-03-24 17:32:21 +0100420 def update_pcscf(self, pcscf):
421 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100422 addr_type = get_addr_type(pcscf)
423 if addr_type == None:
424 raise ValueError("Unknown PCSCF address type or invalid address provided")
425 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100426 else:
427 # Just the tag value
428 content = '80'
429 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100430 pcscf_tlv = rpad(content, rec_size_bytes*2)
431 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100432 return sw
433
Supreeth Herle05b28072020-03-25 10:23:48 +0100434 def read_domain(self):
435 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
436 if sw == '9000':
437 # Skip the inital tag value ('80') byte and get length of contents
438 length = int(res[2:4], 16)
439 content = h2s(res[4:4+(length*2)])
440 return (content, sw)
441 else:
442 return (None, sw)
443
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100444 def update_domain(self, domain=None, mcc=None, mnc=None):
445 hex_str = ""
446 if domain:
447 hex_str = s2h(domain)
448 elif mcc and mnc:
449 # MCC and MNC always has 3 digits in domain form
450 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
451 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
452
453 # Build TLV
454 tlv = TLV(['80'])
455 content = tlv.build({'80': hex_str})
456
457 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
458 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
459 return sw
460
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100461 def read_impi(self):
462 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
463 if sw == '9000':
464 # Skip the inital tag value ('80') byte and get length of contents
465 length = int(res[2:4], 16)
466 content = h2s(res[4:4+(length*2)])
467 return (content, sw)
468 else:
469 return (None, sw)
470
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100471 def update_impi(self, impi=None):
472 hex_str = ""
473 if impi:
474 hex_str = s2h(impi)
475 # Build TLV
476 tlv = TLV(['80'])
477 content = tlv.build({'80': hex_str})
478
479 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
480 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
481 return sw
482
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100483 def read_impu(self):
484 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
485 impu_recs = ""
486 for i in range(0, rec_cnt):
487 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
488 if sw == '9000':
489 # Skip the inital tag value ('80') byte and get length of contents
490 length = int(res[2:4], 16)
491 content = h2s(res[4:4+(length*2)])
492 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
493 else:
494 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
495 return impu_recs
496
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100497 def update_impu(self, impu=None):
498 hex_str = ""
499 if impu:
500 hex_str = s2h(impu)
501 # Build TLV
502 tlv = TLV(['80'])
503 content = tlv.build({'80': hex_str})
504
505 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
506 impu_tlv = rpad(content, rec_size_bytes*2)
507 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
508 return sw
509
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200510 def read_iari(self):
511 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
512 uiari_recs = ""
513 for i in range(0, rec_cnt):
514 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
515 if sw == '9000':
516 # Skip the inital tag value ('80') byte and get length of contents
517 length = int(res[2:4], 16)
518 content = h2s(res[4:4+(length*2)])
519 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
520 else:
521 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
522 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100523
Philipp Maierbb73e512021-05-05 16:14:00 +0200524class MagicSimBase(abc.ABC, SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100525 """
526 Theses cards uses several record based EFs to store the provider infos,
527 each possible provider uses a specific record number in each EF. The
528 indexes used are ( where N is the number of providers supported ) :
529 - [2 .. N+1] for the operator name
Harald Weltec9cdce32021-04-11 10:28:28 +0200530 - [1 .. N] for the programmable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100531
532 * 3f00/7f4d/8f0c : Operator Name
533
534 bytes 0-15 : provider name, padded with 0xff
535 byte 16 : length of the provider name
536 byte 17 : 01 for valid records, 00 otherwise
537
538 * 3f00/7f4d/8f0d : Programmable Binary EFs
539
540 * 3f00/7f4d/8f0e : Programmable Record EFs
541
542 """
543
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +0200544 _files = { } # type: Dict[str, Tuple[str, int, bool]]
545 _ki_file = None # type: Optional[str]
546
Sylvain Munaut76504e02010-12-07 00:24:32 +0100547 @classmethod
548 def autodetect(kls, scc):
549 try:
550 for p, l, t in kls._files.values():
551 if not t:
552 continue
553 if scc.record_size(['3f00', '7f4d', p]) != l:
554 return None
555 except:
556 return None
557
558 return kls(scc)
559
560 def _get_count(self):
561 """
562 Selects the file and returns the total number of entries
563 and entry size
564 """
565 f = self._files['name']
566
Harald Weltec0499c82021-01-21 16:06:50 +0100567 r = self._scc.select_path(['3f00', '7f4d', f[0]])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100568 rec_len = int(r[-1][28:30], 16)
569 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200570 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100571
572 if (rec_cnt < 1) or (rec_len != f[1]):
573 raise RuntimeError('Bad card type')
574
575 return rec_cnt
576
577 def program(self, p):
578 # Go to dir
Harald Weltec0499c82021-01-21 16:06:50 +0100579 self._scc.select_path(['3f00', '7f4d'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100580
581 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400582 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100583
584 # Operator name ( 3f00/7f4d/8f0c )
585 self._scc.update_record(self._files['name'][0], 2,
586 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
587 )
588
589 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
590 v = ''
591
592 # inline Ki
593 if self._ki_file is None:
594 v += p['ki']
595
596 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400597 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100598
599 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400600 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100601
602 # Ki
603 if self._ki_file:
604 v += self._ki_file + '10' + p['ki']
605
606 # PLMN_Sel
607 v+= '6f30' + '18' + rpad(hplmn, 36)
608
Alexander Chemeris21885242013-07-02 16:56:55 +0400609 # ACC
610 # This doesn't work with "fake" SuperSIM cards,
611 # but will hopefully work with real SuperSIMs.
612 if p.get('acc') is not None:
613 v+= '6f78' + '02' + lpad(p['acc'], 4)
614
Sylvain Munaut76504e02010-12-07 00:24:32 +0100615 self._scc.update_record(self._files['b_ef'][0], 1,
616 rpad(v, self._files['b_ef'][1]*2)
617 )
618
619 # SMSP ( 3f00/7f4d/8f0e )
620 # FIXME
621
622 # Write PLMN_Sel forcefully as well
Harald Weltec0499c82021-01-21 16:06:50 +0100623 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100624 tl = int(r[-1][4:8], 16)
625
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400626 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100627 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
628
629 def erase(self):
630 # Dummy
631 df = {}
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200632 for k, v in self._files.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100633 ofs = 1
634 fv = v[1] * 'ff'
635 if k == 'name':
636 ofs = 2
637 fv = fv[0:-4] + '0000'
638 df[v[0]] = (fv, ofs)
639
640 # Write
641 for n in range(0,self._get_count()):
Vadim Yanitskiyd9a8d2f2021-05-02 02:12:47 +0200642 for k, (msg, ofs) in df.items():
Sylvain Munaut76504e02010-12-07 00:24:32 +0100643 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
644
645
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200646class SuperSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100647
648 name = 'supersim'
649
650 _files = {
651 'name' : ('8f0c', 18, True),
652 'b_ef' : ('8f0d', 74, True),
653 'r_ef' : ('8f0e', 50, True),
654 }
655
656 _ki_file = None
657
658
Vadim Yanitskiy85302d62021-05-02 02:18:42 +0200659class MagicSim(MagicSimBase):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100660
661 name = 'magicsim'
662
663 _files = {
664 'name' : ('8f0c', 18, True),
665 'b_ef' : ('8f0d', 130, True),
666 'r_ef' : ('8f0e', 102, False),
667 }
668
669 _ki_file = '6f1b'
670
671
Philipp Maierbb73e512021-05-05 16:14:00 +0200672class FakeMagicSim(SimCard):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100673 """
674 Theses cards have a record based EF 3f00/000c that contains the provider
Harald Weltec9cdce32021-04-11 10:28:28 +0200675 information. See the program method for its format. The records go from
Sylvain Munaut76504e02010-12-07 00:24:32 +0100676 1 to N.
677 """
678
679 name = 'fakemagicsim'
680
681 @classmethod
682 def autodetect(kls, scc):
683 try:
684 if scc.record_size(['3f00', '000c']) != 0x5a:
685 return None
686 except:
687 return None
688
689 return kls(scc)
690
691 def _get_infos(self):
692 """
693 Selects the file and returns the total number of entries
694 and entry size
695 """
696
Harald Weltec0499c82021-01-21 16:06:50 +0100697 r = self._scc.select_path(['3f00', '000c'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100698 rec_len = int(r[-1][28:30], 16)
699 tlen = int(r[-1][4:8],16)
Vadim Yanitskiyeb395862021-05-02 02:23:48 +0200700 rec_cnt = (tlen // rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100701
702 if (rec_cnt < 1) or (rec_len != 0x5a):
703 raise RuntimeError('Bad card type')
704
705 return rec_cnt, rec_len
706
707 def program(self, p):
708 # Home PLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100709 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100710 tl = int(r[-1][4:8], 16)
711
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400712 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100713 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
714
715 # Get total number of entries and entry size
716 rec_cnt, rec_len = self._get_infos()
717
718 # Set first entry
719 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200720 '81' + # 1b Status: Valid & Active
Harald Welte4f6ca432021-02-01 17:51:56 +0100721 rpad(s2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200722 enc_iccid(p['iccid']) + # 10b ICCID
723 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
724 p['ki'] + # 16b Ki
725 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100726 )
727 self._scc.update_record('000c', 1, entry)
728
729 def erase(self):
730 # Get total number of entries and entry size
731 rec_cnt, rec_len = self._get_infos()
732
733 # Erase all entries
734 entry = 'ff' * rec_len
735 for i in range(0, rec_cnt):
736 self._scc.update_record('000c', 1+i, entry)
737
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200738
Philipp Maierbb73e512021-05-05 16:14:00 +0200739class GrcardSim(SimCard):
Harald Welte3156d902011-03-22 21:48:19 +0100740 """
741 Greencard (grcard.cn) HZCOS GSM SIM
742 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
743 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
744 """
745
746 name = 'grcardsim'
747
748 @classmethod
749 def autodetect(kls, scc):
750 return None
751
752 def program(self, p):
753 # We don't really know yet what ADM PIN 4 is about
754 #self._scc.verify_chv(4, h2b("4444444444444444"))
755
756 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100757 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200758 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100759 else:
760 pin = h2b("4444444444444444")
761 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100762
763 # EF.ICCID
Harald Weltec0499c82021-01-21 16:06:50 +0100764 r = self._scc.select_path(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400765 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100766
767 # EF.IMSI
Harald Weltec0499c82021-01-21 16:06:50 +0100768 r = self._scc.select_path(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400769 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100770
771 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400772 if p.get('acc') is not None:
773 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100774
775 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200776 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +0100777 r = self._scc.select_path(['3f00', '7f10', '6f42'])
Harald Welte23888da2019-08-28 23:19:11 +0200778 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100779
780 # Set the Ki using proprietary command
781 pdu = '80d4020010' + p['ki']
782 data, sw = self._scc._tp.send_apdu(pdu)
783
784 # EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100785 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100786 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400787 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100788 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
789
790 # EF.SPN (Service Provider Name)
Harald Weltec0499c82021-01-21 16:06:50 +0100791 r = self._scc.select_path(['3f00', '7f20', '6f30'])
Harald Welte3156d902011-03-22 21:48:19 +0100792 size = int(r[-1][4:8], 16)
793 # FIXME
794
795 # FIXME: EF.MSISDN
796
Sylvain Munaut76504e02010-12-07 00:24:32 +0100797
Harald Weltee10394b2011-12-07 12:34:14 +0100798class SysmoSIMgr1(GrcardSim):
799 """
800 sysmocom sysmoSIM-GR1
801 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
802 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
803 """
804 name = 'sysmosim-gr1'
805
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200806 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200807 def autodetect(kls, scc):
808 try:
809 # Look for ATR
810 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
811 return kls(scc)
812 except:
813 return None
814 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200815
Harald Welteca673942020-06-03 15:19:40 +0200816class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100817 """
818 sysmocom sysmoUSIM-GR1
819 """
820 name = 'sysmoUSIM-GR1'
821
822 @classmethod
823 def autodetect(kls, scc):
824 # TODO: Access the ATR
825 return None
826
827 def program(self, p):
828 # TODO: check if verify_chv could be used or what it needs
829 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
830 # Unlock the card..
831 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
832
833 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100834 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400835 p['opc'] + # 32b OPC
836 enc_iccid(p['iccid']) + # 10b ICCID
837 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100838 )
839 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
840
Sylvain Munaut053c8952013-07-02 15:12:32 +0200841
Philipp Maierbb73e512021-05-05 16:14:00 +0200842class SysmoSIMgr2(SimCard):
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100843 """
844 sysmocom sysmoSIM-GR2
845 """
846
847 name = 'sysmoSIM-GR2'
848
849 @classmethod
850 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900851 try:
852 # Look for ATR
853 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
854 return kls(scc)
855 except:
856 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100857 return None
858
859 def program(self, p):
860
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200861 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100862 r = self._scc.select_path(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200863
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100864 # authenticate as SUPER ADM using default key
865 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
866
867 # set ADM pin using proprietary command
868 # INS: D4
869 # P1: 3A for PIN, 3B for PUK
870 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
871 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100872 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200873 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100874 else:
875 pin = h2b("4444444444444444")
876
877 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100878 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200879
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100880 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100881
882 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100883
884 # write EF.ICCID
885 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
886
887 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100888 r = self._scc.select_path(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200889
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100890 # write EF.IMSI
891 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
892
893 # write EF.ACC
894 if p.get('acc') is not None:
895 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
896
897 # get size and write EF.HPLMN
Harald Weltec0499c82021-01-21 16:06:50 +0100898 r = self._scc.select_path(['6f30'])
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100899 size = int(r[-1][4:8], 16)
900 hplmn = enc_plmn(p['mcc'], p['mnc'])
901 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
902
903 # set COMP128 version 0 in proprietary file
904 data, sw = self._scc.update_binary('0001', '001000')
905
906 # set Ki in proprietary file
907 data, sw = self._scc.update_binary('0001', p['ki'], 3)
908
909 # select DF_TELECOM
Harald Weltec0499c82021-01-21 16:06:50 +0100910 r = self._scc.select_path(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200911
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100912 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200913 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200914 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100915
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100916
Harald Welteca673942020-06-03 15:19:40 +0200917class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100918 """
919 sysmocom sysmoUSIM-SJS1
920 """
921
922 name = 'sysmoUSIM-SJS1'
923
924 def __init__(self, ssc):
925 super(SysmoUSIMSJS1, self).__init__(ssc)
926 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100927 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100928
929 @classmethod
930 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900931 try:
932 # Look for ATR
933 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"):
934 return kls(scc)
935 except:
936 return None
Jan Balke3e840672015-01-26 15:36:27 +0100937 return None
938
Harald Weltea6704252021-01-08 20:19:11 +0100939 def verify_adm(self, key):
Philipp Maiere9604882017-03-21 17:24:31 +0100940 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +0100941 if not key:
Philipp Maiere9604882017-03-21 17:24:31 +0100942 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +0100943 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +0100944 return sw
945
946 def program(self, p):
947 self.verify_adm(h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100948
949 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +0100950 r = self._scc.select_path(['3f00'])
Jan Balke3e840672015-01-26 15:36:27 +0100951
Philipp Maiere9604882017-03-21 17:24:31 +0100952 # write EF.ICCID
953 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
954
Jan Balke3e840672015-01-26 15:36:27 +0100955 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +0100956 r = self._scc.select_path(['7f20'])
Jan Balke3e840672015-01-26 15:36:27 +0100957
Jan Balke3e840672015-01-26 15:36:27 +0100958 # set Ki in proprietary file
959 data, sw = self._scc.update_binary('00FF', p['ki'])
960
Philipp Maier1be35bf2018-07-13 11:29:03 +0200961 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200962 if 'opc' in p:
963 content = "01" + p['opc']
964 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100965
Supreeth Herle7947d922019-06-08 07:50:53 +0200966 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100967 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +0200968 self.update_spn(p['name'], True, True)
Supreeth Herle7947d922019-06-08 07:50:53 +0200969
Supreeth Herlec8796a32019-12-23 12:23:42 +0100970 if p.get('acc') is not None:
971 self.update_acc(p['acc'])
972
Jan Balke3e840672015-01-26 15:36:27 +0100973 # write EF.IMSI
974 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
975
Philipp Maier2d15ea02019-03-20 12:40:36 +0100976 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200977 if p.get('mcc') and p.get('mnc'):
978 sw = self.update_plmnsel(p['mcc'], p['mnc'])
979 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100980 print("Programming PLMNsel failed with code %s"%sw)
981
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200982 # EF.PLMNwAcT
983 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100984 sw = self.update_plmn_act(p['mcc'], p['mnc'])
985 if sw != '9000':
986 print("Programming PLMNwAcT failed with code %s"%sw)
987
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200988 # EF.OPLMNwAcT
989 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100990 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
991 if sw != '9000':
992 print("Programming OPLMNwAcT failed with code %s"%sw)
993
Supreeth Herlef442fb42020-01-21 12:47:32 +0100994 # EF.HPLMNwAcT
995 if p.get('mcc') and p.get('mnc'):
996 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
997 if sw != '9000':
998 print("Programming HPLMNwAcT failed with code %s"%sw)
999
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001000 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001001 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1002 if p.get('mcc') and p.get('mnc'):
1003 mnc = p['mnc']
1004 else:
1005 mnc = None
1006 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maieree908ae2019-03-21 16:21:12 +01001007 if sw != '9000':
1008 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +01001009
Daniel Willmann1d087ef2017-08-31 10:08:45 +02001010 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +02001011 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001012 r = self._scc.select_path(['3f00', '7f10'])
Harald Welte23888da2019-08-28 23:19:11 +02001013 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +01001014
Supreeth Herle5a541012019-12-22 08:59:16 +01001015 # EF.MSISDN
1016 # TODO: Alpha Identifier (currently 'ff'O * 20)
1017 # TODO: Capability/Configuration1 Record Identifier
1018 # TODO: Extension1 Record Identifier
1019 if p.get('msisdn') is not None:
1020 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001021 data = 'ff' * 20 + msisdn
Supreeth Herle5a541012019-12-22 08:59:16 +01001022
Harald Weltec0499c82021-01-21 16:06:50 +01001023 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herle5a541012019-12-22 08:59:16 +01001024 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
1025
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001026
herlesupreeth4a3580b2020-09-29 10:11:36 +02001027class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001028 """
1029 FairwavesSIM
1030
1031 The SIM card is operating according to the standard.
1032 For Ki/OP/OPC programming the following files are additionally open for writing:
1033 3F00/7F20/FF01 – OP/OPC:
1034 byte 1 = 0x01, bytes 2-17: OPC;
1035 byte 1 = 0x00, bytes 2-17: OP;
1036 3F00/7F20/FF02: Ki
1037 """
1038
Philipp Maier5a876312019-11-11 11:01:46 +01001039 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001040 # Propriatary files
1041 _EF_num = {
1042 'Ki': 'FF02',
1043 'OP/OPC': 'FF01',
1044 }
1045 _EF = {
1046 'Ki': DF['GSM']+[_EF_num['Ki']],
1047 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
1048 }
1049
1050 def __init__(self, ssc):
1051 super(FairwavesSIM, self).__init__(ssc)
1052 self._adm_chv_num = 0x11
1053 self._adm2_chv_num = 0x12
1054
1055
1056 @classmethod
1057 def autodetect(kls, scc):
1058 try:
1059 # Look for ATR
1060 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"):
1061 return kls(scc)
1062 except:
1063 return None
1064 return None
1065
1066
1067 def verify_adm2(self, key):
1068 '''
1069 Authenticate with ADM2 key.
1070
1071 Fairwaves SIM cards support hierarchical key structure and ADM2 key
1072 is a key which has access to proprietary files (Ki and OP/OPC).
1073 That said, ADM key inherits permissions of ADM2 key and thus we rarely
1074 need ADM2 key per se.
1075 '''
1076 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
1077 return sw
1078
1079
1080 def read_ki(self):
1081 """
1082 Read Ki in proprietary file.
1083
1084 Requires ADM1 access level
1085 """
1086 return self._scc.read_binary(self._EF['Ki'])
1087
1088
1089 def update_ki(self, ki):
1090 """
1091 Set Ki in proprietary file.
1092
1093 Requires ADM1 access level
1094 """
1095 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1096 return sw
1097
1098
1099 def read_op_opc(self):
1100 """
1101 Read Ki in proprietary file.
1102
1103 Requires ADM1 access level
1104 """
1105 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1106 type = 'OP' if ef[0:2] == '00' else 'OPC'
1107 return ((type, ef[2:]), sw)
1108
1109
1110 def update_op(self, op):
1111 """
1112 Set OP in proprietary file.
1113
1114 Requires ADM1 access level
1115 """
1116 content = '00' + op
1117 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1118 return sw
1119
1120
1121 def update_opc(self, opc):
1122 """
1123 Set OPC in proprietary file.
1124
1125 Requires ADM1 access level
1126 """
1127 content = '01' + opc
1128 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1129 return sw
1130
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001131 def program(self, p):
Philipp Maier64b28372021-10-05 13:58:25 +02001132 # For some reason the card programming only works when the card
1133 # is handled as a classic SIM, even though it is an USIM, so we
1134 # reconfigure the class byte and the select control field on
1135 # the fly. When the programming is done the original values are
1136 # restored.
1137 cla_byte_orig = self._scc.cla_byte
1138 sel_ctrl_orig = self._scc.sel_ctrl
1139 self._scc.cla_byte = "a0"
1140 self._scc.sel_ctrl = "0000"
1141
1142 try:
1143 self._program(p)
1144 finally:
1145 # restore original cla byte and sel ctrl
1146 self._scc.cla_byte = cla_byte_orig
1147 self._scc.sel_ctrl = sel_ctrl_orig
1148
1149 def _program(self, p):
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001150 # authenticate as ADM1
1151 if not p['pin_adm']:
1152 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001153 self.verify_adm(h2b(p['pin_adm']))
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001154
1155 # TODO: Set operator name
1156 if p.get('smsp') is not None:
1157 sw = self.update_smsp(p['smsp'])
1158 if sw != '9000':
1159 print("Programming SMSP failed with code %s"%sw)
1160 # This SIM doesn't support changing ICCID
1161 if p.get('mcc') is not None and p.get('mnc') is not None:
1162 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1163 if sw != '9000':
1164 print("Programming MCC/MNC failed with code %s"%sw)
1165 if p.get('imsi') is not None:
1166 sw = self.update_imsi(p['imsi'])
1167 if sw != '9000':
1168 print("Programming IMSI failed with code %s"%sw)
1169 if p.get('ki') is not None:
1170 sw = self.update_ki(p['ki'])
1171 if sw != '9000':
1172 print("Programming Ki failed with code %s"%sw)
1173 if p.get('opc') is not None:
1174 sw = self.update_opc(p['opc'])
1175 if sw != '9000':
1176 print("Programming OPC failed with code %s"%sw)
1177 if p.get('acc') is not None:
1178 sw = self.update_acc(p['acc'])
1179 if sw != '9000':
1180 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001181
Philipp Maierbb73e512021-05-05 16:14:00 +02001182class OpenCellsSim(SimCard):
Todd Neal9eeadfc2018-04-25 15:36:29 -05001183 """
1184 OpenCellsSim
1185
1186 """
1187
Philipp Maier5a876312019-11-11 11:01:46 +01001188 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001189
1190 def __init__(self, ssc):
1191 super(OpenCellsSim, self).__init__(ssc)
1192 self._adm_chv_num = 0x0A
1193
1194
1195 @classmethod
1196 def autodetect(kls, scc):
1197 try:
1198 # Look for ATR
1199 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"):
1200 return kls(scc)
1201 except:
1202 return None
1203 return None
1204
1205
1206 def program(self, p):
1207 if not p['pin_adm']:
1208 raise ValueError("Please provide a PIN-ADM as there is no default one")
1209 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1210
1211 # select MF
Harald Weltec0499c82021-01-21 16:06:50 +01001212 r = self._scc.select_path(['3f00'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001213
1214 # write EF.ICCID
1215 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1216
Harald Weltec0499c82021-01-21 16:06:50 +01001217 r = self._scc.select_path(['7ff0'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001218
1219 # set Ki in proprietary file
1220 data, sw = self._scc.update_binary('FF02', p['ki'])
1221
1222 # set OPC in proprietary file
1223 data, sw = self._scc.update_binary('FF01', p['opc'])
1224
1225 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001226 r = self._scc.select_path(['7f20'])
Todd Neal9eeadfc2018-04-25 15:36:29 -05001227
1228 # write EF.IMSI
1229 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1230
herlesupreeth4a3580b2020-09-29 10:11:36 +02001231class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001232 """
1233 WavemobileSim
1234
1235 """
1236
1237 name = 'Wavemobile-SIM'
1238
1239 def __init__(self, ssc):
1240 super(WavemobileSim, self).__init__(ssc)
1241 self._adm_chv_num = 0x0A
1242 self._scc.cla_byte = "00"
1243 self._scc.sel_ctrl = "0004" #request an FCP
1244
1245 @classmethod
1246 def autodetect(kls, scc):
1247 try:
1248 # Look for ATR
1249 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"):
1250 return kls(scc)
1251 except:
1252 return None
1253 return None
1254
1255 def program(self, p):
1256 if not p['pin_adm']:
1257 raise ValueError("Please provide a PIN-ADM as there is no default one")
Philipp Maier05f42ee2021-03-11 13:59:44 +01001258 self.verify_adm(h2b(p['pin_adm']))
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001259
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001260 # EF.ICCID
1261 # TODO: Add programming of the ICCID
1262 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001263 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1264
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001265 # KI (Presumably a propritary file)
1266 # TODO: Add programming of KI
1267 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001268 print("Warning: Programming of the KI is not implemented for this type of card.")
1269
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001270 # OPc (Presumably a propritary file)
1271 # TODO: Add programming of OPc
1272 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001273 print("Warning: Programming of the OPc is not implemented for this type of card.")
1274
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001275 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001276 if p.get('smsp'):
1277 sw = self.update_smsp(p['smsp'])
1278 if sw != '9000':
1279 print("Programming SMSP failed with code %s"%sw)
1280
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001281 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001282 if p.get('imsi'):
1283 sw = self.update_imsi(p['imsi'])
1284 if sw != '9000':
1285 print("Programming IMSI failed with code %s"%sw)
1286
1287 # EF.ACC
1288 if p.get('acc'):
1289 sw = self.update_acc(p['acc'])
1290 if sw != '9000':
1291 print("Programming ACC failed with code %s"%sw)
1292
1293 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001294 if p.get('mcc') and p.get('mnc'):
1295 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1296 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001297 print("Programming PLMNsel failed with code %s"%sw)
1298
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001299 # EF.PLMNwAcT
1300 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001301 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1302 if sw != '9000':
1303 print("Programming PLMNwAcT failed with code %s"%sw)
1304
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001305 # EF.OPLMNwAcT
1306 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001307 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1308 if sw != '9000':
1309 print("Programming OPLMNwAcT failed with code %s"%sw)
1310
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001311 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001312 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1313 if p.get('mcc') and p.get('mnc'):
1314 mnc = p['mnc']
1315 else:
1316 mnc = None
1317 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier6e507a72019-04-01 16:33:48 +02001318 if sw != '9000':
1319 print("Programming AD failed with code %s"%sw)
1320
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001321 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001322
Todd Neal9eeadfc2018-04-25 15:36:29 -05001323
herlesupreethb0c7d122020-12-23 09:25:46 +01001324class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001325 """
1326 sysmocom sysmoISIM-SJA2
1327 """
1328
1329 name = 'sysmoISIM-SJA2'
1330
1331 def __init__(self, ssc):
1332 super(SysmoISIMSJA2, self).__init__(ssc)
1333 self._scc.cla_byte = "00"
1334 self._scc.sel_ctrl = "0004" #request an FCP
1335
1336 @classmethod
1337 def autodetect(kls, scc):
1338 try:
1339 # Try card model #1
1340 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1341 if scc.get_atr() == toBytes(atr):
1342 return kls(scc)
1343
1344 # Try card model #2
1345 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1346 if scc.get_atr() == toBytes(atr):
1347 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001348
1349 # Try card model #3
1350 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1351 if scc.get_atr() == toBytes(atr):
1352 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001353 except:
1354 return None
1355 return None
1356
Harald Weltea6704252021-01-08 20:19:11 +01001357 def verify_adm(self, key):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001358 # authenticate as ADM using default key (written on the card..)
Harald Weltea6704252021-01-08 20:19:11 +01001359 if not key:
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001360 raise ValueError("Please provide a PIN-ADM as there is no default one")
Harald Weltea6704252021-01-08 20:19:11 +01001361 (res, sw) = self._scc.verify_chv(0x0A, key)
Harald Weltea6704252021-01-08 20:19:11 +01001362 return sw
1363
1364 def program(self, p):
1365 self.verify_adm(h2b(p['pin_adm']))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001366
1367 # This type of card does not allow to reprogram the ICCID.
1368 # Reprogramming the ICCID would mess up the card os software
1369 # license management, so the ICCID must be kept at its factory
1370 # setting!
1371 if p.get('iccid'):
1372 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1373
1374 # select DF_GSM
Harald Weltec0499c82021-01-21 16:06:50 +01001375 self._scc.select_path(['7f20'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001376
Robert Falkenberg54595362021-04-06 12:04:34 +02001377 # set Service Provider Name
1378 if p.get('name') is not None:
Robert Falkenbergb07a3e92021-05-07 15:23:20 +02001379 self.update_spn(p['name'], True, True)
Robert Falkenberg54595362021-04-06 12:04:34 +02001380
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001381 # write EF.IMSI
1382 if p.get('imsi'):
1383 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1384
1385 # EF.PLMNsel
1386 if p.get('mcc') and p.get('mnc'):
1387 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1388 if sw != '9000':
1389 print("Programming PLMNsel failed with code %s"%sw)
1390
1391 # EF.PLMNwAcT
1392 if p.get('mcc') and p.get('mnc'):
1393 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1394 if sw != '9000':
1395 print("Programming PLMNwAcT failed with code %s"%sw)
1396
1397 # EF.OPLMNwAcT
1398 if p.get('mcc') and p.get('mnc'):
1399 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1400 if sw != '9000':
1401 print("Programming OPLMNwAcT failed with code %s"%sw)
1402
Harald Welte32f0d412020-05-05 17:35:57 +02001403 # EF.HPLMNwAcT
1404 if p.get('mcc') and p.get('mnc'):
1405 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1406 if sw != '9000':
1407 print("Programming HPLMNwAcT failed with code %s"%sw)
1408
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001409 # EF.AD
Robert Falkenbergd0505bd2021-02-24 14:06:18 +01001410 if (p.get('mcc') and p.get('mnc')) or p.get('opmode'):
1411 if p.get('mcc') and p.get('mnc'):
1412 mnc = p['mnc']
1413 else:
1414 mnc = None
1415 sw = self.update_ad(mnc=mnc, opmode=p.get('opmode'))
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001416 if sw != '9000':
1417 print("Programming AD failed with code %s"%sw)
1418
1419 # EF.SMSP
1420 if p.get('smsp'):
Harald Weltec0499c82021-01-21 16:06:50 +01001421 r = self._scc.select_path(['3f00', '7f10'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001422 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1423
Supreeth Herlec6019232020-03-26 10:00:45 +01001424 # EF.MSISDN
1425 # TODO: Alpha Identifier (currently 'ff'O * 20)
1426 # TODO: Capability/Configuration1 Record Identifier
1427 # TODO: Extension1 Record Identifier
1428 if p.get('msisdn') is not None:
1429 msisdn = enc_msisdn(p['msisdn'])
Philipp Maierb46cb3f2021-04-20 22:38:21 +02001430 content = 'ff' * 20 + msisdn
Supreeth Herlec6019232020-03-26 10:00:45 +01001431
Harald Weltec0499c82021-01-21 16:06:50 +01001432 r = self._scc.select_path(['3f00', '7f10'])
Supreeth Herlec6019232020-03-26 10:00:45 +01001433 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1434
Supreeth Herlea97944b2020-03-26 10:03:25 +01001435 # EF.ACC
1436 if p.get('acc'):
1437 sw = self.update_acc(p['acc'])
1438 if sw != '9000':
1439 print("Programming ACC failed with code %s"%sw)
1440
Supreeth Herle80164052020-03-23 12:06:29 +01001441 # Populate AIDs
1442 self.read_aids()
1443
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001444 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1445 # hard linked to EF-USIM_AUTH_KEY)
Harald Weltec0499c82021-01-21 16:06:50 +01001446 self._scc.select_path(['3f00'])
1447 self._scc.select_path(['a515'])
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001448 if p.get('ki'):
1449 self._scc.update_binary('6f20', p['ki'], 1)
1450 if p.get('opc'):
1451 self._scc.update_binary('6f20', p['opc'], 17)
1452
1453 # update EF-USIM_AUTH_KEY in ADF.ISIM
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001454 data, sw = self.select_adf_by_aid(adf="isim")
1455 if sw == '9000':
Philipp Maierd9507862020-03-11 12:18:29 +01001456 if p.get('ki'):
1457 self._scc.update_binary('af20', p['ki'], 1)
1458 if p.get('opc'):
1459 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001460
Supreeth Herlecf727f22020-03-24 17:32:21 +01001461 # update EF.P-CSCF in ADF.ISIM
1462 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1463 if p.get('pcscf'):
1464 sw = self.update_pcscf(p['pcscf'])
1465 else:
1466 sw = self.update_pcscf("")
1467 if sw != '9000':
1468 print("Programming P-CSCF failed with code %s"%sw)
1469
1470
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001471 # update EF.DOMAIN in ADF.ISIM
1472 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1473 if p.get('ims_hdomain'):
1474 sw = self.update_domain(domain=p['ims_hdomain'])
1475 else:
1476 sw = self.update_domain()
1477
1478 if sw != '9000':
1479 print("Programming Home Network Domain Name failed with code %s"%sw)
1480
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001481 # update EF.IMPI in ADF.ISIM
1482 # TODO: Validate IMPI input
1483 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1484 if p.get('impi'):
1485 sw = self.update_impi(p['impi'])
1486 else:
1487 sw = self.update_impi()
1488 if sw != '9000':
1489 print("Programming IMPI failed with code %s"%sw)
1490
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001491 # update EF.IMPU in ADF.ISIM
1492 # TODO: Validate IMPU input
1493 # Support multiple IMPU if there is enough space
1494 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1495 if p.get('impu'):
1496 sw = self.update_impu(p['impu'])
1497 else:
1498 sw = self.update_impu()
1499 if sw != '9000':
1500 print("Programming IMPU failed with code %s"%sw)
1501
Philipp Maiercba6dbc2021-03-11 13:03:18 +01001502 data, sw = self.select_adf_by_aid(adf="usim")
1503 if sw == '9000':
Harald Welteca673942020-06-03 15:19:40 +02001504 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001505 if p.get('ki'):
1506 self._scc.update_binary('af20', p['ki'], 1)
1507 if p.get('opc'):
1508 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001509
Harald Welteca673942020-06-03 15:19:40 +02001510 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001511 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001512 if p.get('mcc') and p.get('mnc'):
1513 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1514 if sw != '9000':
1515 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001516
1517 # update EF.ePDGId in ADF.USIM
1518 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1519 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001520 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001521 else:
1522 sw = self.update_epdgid("")
1523 if sw != '9000':
1524 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001525
Supreeth Herlef964df42020-03-24 13:15:37 +01001526 # update EF.ePDGSelection in ADF.USIM
1527 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1528 if p.get('epdgSelection'):
1529 epdg_plmn = p['epdgSelection']
1530 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1531 else:
1532 sw = self.update_ePDGSelection("", "")
1533 if sw != '9000':
1534 print("Programming ePDGSelection failed with code %s"%sw)
1535
1536
Supreeth Herleacc222f2020-03-24 13:26:53 +01001537 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1538 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001539 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001540 if self.file_exists(EF_USIM_ADF_map['UST']):
1541 if p.get('epdgSelection') and p.get('epdgid'):
1542 sw = self.update_ust(106, 1)
1543 if sw != '9000':
1544 print("Programming UST failed with code %s"%sw)
1545 sw = self.update_ust(107, 1)
1546 if sw != '9000':
1547 print("Programming UST failed with code %s"%sw)
1548
Supreeth Herle44e04622020-03-25 10:34:28 +01001549 sw = self.update_ust(95, 0)
1550 if sw != '9000':
1551 print("Programming UST failed with code %s"%sw)
1552 sw = self.update_ust(99, 0)
1553 if sw != '9000':
1554 print("Programming UST failed with code %s"%sw)
1555 sw = self.update_ust(115, 0)
1556 if sw != '9000':
1557 print("Programming UST failed with code %s"%sw)
1558
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001559 return
1560
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001561
Todd Neal9eeadfc2018-04-25 15:36:29 -05001562# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001563_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001564 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001565 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001566
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001567def card_detect(ctype, scc):
1568 # Detect type if needed
1569 card = None
1570 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1571
Philipp Maier64773092021-10-05 14:42:01 +02001572 if ctype == "auto":
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001573 for kls in _cards_classes:
1574 card = kls.autodetect(scc)
1575 if card:
1576 print("Autodetected card type: %s" % card.name)
1577 card.reset()
1578 break
1579
1580 if card is None:
1581 print("Autodetection failed")
1582 return None
1583
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001584 elif ctype in ctypes:
1585 card = ctypes[ctype](scc)
1586
1587 else:
1588 raise ValueError("Unknown card type: %s" % ctype)
1589
1590 return card