blob: ac6d22357d489c9aed52304e62d13d53ae8da0ca [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4""" pySim: Card programmation logic
5"""
6
7#
8# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Welte3156d902011-03-22 21:48:19 +01009# Copyright (C) 2011 Harald Welte <laforge@gnumonks.org>
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030010# Copyright (C) 2017 Alexander.Chemeris <Alexander.Chemeris@gmail.com>
Sylvain Munaut76504e02010-12-07 00:24:32 +010011#
12# This program is free software: you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation, either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program. If not, see <http://www.gnu.org/licenses/>.
24#
25
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030026from pySim.ts_51_011 import EF, DF
Harald Welteca673942020-06-03 15:19:40 +020027from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010028from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030029from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090030from smartcard.util import toBytes
Supreeth Herle79f43dd2020-03-25 11:43:19 +010031from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010032
33class Card(object):
34
35 def __init__(self, scc):
36 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030037 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010038 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010039
Sylvain Munaut76504e02010-12-07 00:24:32 +010040 def reset(self):
41 self._scc.reset_card()
42
Philipp Maierd58c6322020-05-12 16:47:45 +020043 def erase(self):
44 print("warning: erasing is not supported for specified card type!")
45 return
46
Harald Welteca673942020-06-03 15:19:40 +020047 def file_exists(self, fid):
48 res_arr = self._scc.try_select_file(fid)
49 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020050 if res[1] != '9000':
51 return False
Harald Welteca673942020-06-03 15:19:40 +020052 return True
53
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030054 def verify_adm(self, key):
55 '''
56 Authenticate with ADM key
57 '''
58 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
59 return sw
60
61 def read_iccid(self):
62 (res, sw) = self._scc.read_binary(EF['ICCID'])
63 if sw == '9000':
64 return (dec_iccid(res), sw)
65 else:
66 return (None, sw)
67
68 def read_imsi(self):
69 (res, sw) = self._scc.read_binary(EF['IMSI'])
70 if sw == '9000':
71 return (dec_imsi(res), sw)
72 else:
73 return (None, sw)
74
75 def update_imsi(self, imsi):
76 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
77 return sw
78
79 def update_acc(self, acc):
80 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
81 return sw
82
Supreeth Herlea850a472020-03-19 12:44:11 +010083 def read_hplmn_act(self):
84 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
85 if sw == '9000':
86 return (format_xplmn_w_act(res), sw)
87 else:
88 return (None, sw)
89
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030090 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
91 """
92 Update Home PLMN with access technology bit-field
93
94 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
95 in ETSI TS 151 011 for the details of the access_tech field coding.
96 Some common values:
97 access_tech = '0080' # Only GSM is selected
98 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
99 """
100 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100101 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700102 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300103 hplmn = enc_plmn(mcc, mnc)
104 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700105 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300106 return sw
107
Supreeth Herle1757b262020-03-19 12:43:11 +0100108 def read_oplmn_act(self):
109 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
110 if sw == '9000':
111 return (format_xplmn_w_act(res), sw)
112 else:
113 return (None, sw)
114
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200115 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
116 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200117 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200118 """
119 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200120 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700121 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200122 hplmn = enc_plmn(mcc, mnc)
123 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700124 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200125 return sw
126
Supreeth Herle14084402020-03-19 12:42:10 +0100127 def read_plmn_act(self):
128 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
129 if sw == '9000':
130 return (format_xplmn_w_act(res), sw)
131 else:
132 return (None, sw)
133
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200134 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
135 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200136 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200137 """
138 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200139 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700140 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200141 hplmn = enc_plmn(mcc, mnc)
142 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700143 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200144 return sw
145
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200146 def update_plmnsel(self, mcc, mnc):
147 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700148 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200149 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200150 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
151 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200152
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300153 def update_smsp(self, smsp):
154 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
155 return sw
156
Philipp Maieree908ae2019-03-21 16:21:12 +0100157 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200158 #See also: 3GPP TS 31.102, chapter 4.2.18
159 mnclen = len(str(mnc))
160 if mnclen == 1:
161 mnclen = 2
162 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100163 raise RuntimeError('unable to calculate proper mnclen')
164
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200165 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
166
167 # Reset contents to EF.AD in case the file is uninintalized
168 if data.lower() == "ffffffff":
169 data = "00000000"
170
171 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100172 data, sw = self._scc.update_binary(EF['AD'], content)
173 return sw
174
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300175 def read_spn(self):
176 (spn, sw) = self._scc.read_binary(EF['SPN'])
177 if sw == '9000':
178 return (dec_spn(spn), sw)
179 else:
180 return (None, sw)
181
182 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
183 content = enc_spn(name, hplmn_disp, oplmn_disp)
184 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
185 return sw
186
Supreeth Herled21349a2020-04-01 08:37:47 +0200187 def read_binary(self, ef, length=None, offset=0):
188 ef_path = ef in EF and EF[ef] or ef
189 return self._scc.read_binary(ef_path, length, offset)
190
Supreeth Herlead10d662020-04-01 08:43:08 +0200191 def read_record(self, ef, rec_no):
192 ef_path = ef in EF and EF[ef] or ef
193 return self._scc.read_record(ef_path, rec_no)
194
Supreeth Herle98a69272020-03-18 12:14:48 +0100195 def read_gid1(self):
196 (res, sw) = self._scc.read_binary(EF['GID1'])
197 if sw == '9000':
198 return (res, sw)
199 else:
200 return (None, sw)
201
Supreeth Herle6d66af62020-03-19 12:49:16 +0100202 def read_msisdn(self):
203 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
204 if sw == '9000':
205 return (dec_msisdn(res), sw)
206 else:
207 return (None, sw)
208
Supreeth Herlee4e98312020-03-18 11:33:14 +0100209 # Fetch all the AIDs present on UICC
210 def read_aids(self):
211 try:
212 # Find out how many records the EF.DIR has
213 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100214 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100215 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100216 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100217 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
218 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
219 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
220 except Exception as e:
221 print("Can't read AIDs from SIM -- %s" % (str(e),))
222
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100223 # Select ADF.U/ISIM in the Card using its full AID
224 def select_adf_by_aid(self, adf="usim"):
225 # Check for valid ADF name
226 if adf not in ["usim", "isim"]:
227 return None
228
229 # First (known) halves of the U/ISIM AID
230 aid_map = {}
231 aid_map["usim"] = "a0000000871002"
232 aid_map["isim"] = "a0000000871004"
233
234 for aid in self._aids:
235 if aid_map[adf] in aid:
236 (res, sw) = self._scc.select_adf(aid)
237 return sw
238
239 return None
240
Philipp Maier5c2cc662020-05-12 16:27:12 +0200241 # Erase the contents of a file
242 def erase_binary(self, ef):
243 len = self._scc.binary_size(ef)
244 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
245
246 # Erase the contents of a single record
247 def erase_record(self, ef, rec_no):
248 len = self._scc.record_size(ef)
249 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
250
Harald Welteca673942020-06-03 15:19:40 +0200251class UsimCard(Card):
252 def __init__(self, ssc):
253 super(UsimCard, self).__init__(ssc)
254
255 def read_ehplmn(self):
256 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
257 if sw == '9000':
258 return (format_xplmn(res), sw)
259 else:
260 return (None, sw)
261
262 def update_ehplmn(self, mcc, mnc):
263 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
264 size = len(data[0]) // 2
265 ehplmn = enc_plmn(mcc, mnc)
266 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
267 return sw
268
herlesupreethf8232db2020-09-29 10:03:06 +0200269 def read_epdgid(self):
270 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
271 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100272 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200273 else:
274 return (None, sw)
275
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200276 def update_epdgid(self, epdgid):
Supreeth Herle47790342020-03-25 12:51:38 +0100277 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
278 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100279 addr_type = get_addr_type(epdgid)
280 if addr_type == None:
281 raise ValueError("Unknown ePDG Id address type or invalid address provided")
282 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100283 else:
284 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200285 data, sw = self._scc.update_binary(
286 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
287 return sw
Harald Welteca673942020-06-03 15:19:40 +0200288
Supreeth Herle99d55552020-03-24 13:03:43 +0100289 def read_ePDGSelection(self):
290 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
291 if sw == '9000':
292 return (format_ePDGSelection(res), sw)
293 else:
294 return (None, sw)
295
Supreeth Herlef964df42020-03-24 13:15:37 +0100296 def update_ePDGSelection(self, mcc, mnc):
297 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
298 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
299 # Reset contents
300 # 80 - Tag value
301 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
302 elif sw == '9000':
303 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
304 return sw
305
herlesupreeth4a3580b2020-09-29 10:11:36 +0200306 def read_ust(self):
307 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
308 if sw == '9000':
309 # Print those which are available
310 return ([res, dec_st(res, table="usim")], sw)
311 else:
312 return ([None, None], sw)
313
Supreeth Herleacc222f2020-03-24 13:26:53 +0100314 def update_ust(self, service, bit=1):
315 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
316 if sw == '9000':
317 content = enc_st(res, service, bit)
318 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
319 return sw
320
herlesupreethecbada92020-12-23 09:24:29 +0100321class IsimCard(Card):
322 def __init__(self, ssc):
323 super(IsimCard, self).__init__(ssc)
324
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100325 def read_pcscf(self):
326 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
327 pcscf_recs = ""
328 for i in range(0, rec_cnt):
329 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
330 if sw == '9000':
331 content = dec_addr_tlv(res)
332 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
333 else:
334 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
335 return pcscf_recs
336
Supreeth Herlecf727f22020-03-24 17:32:21 +0100337 def update_pcscf(self, pcscf):
338 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100339 addr_type = get_addr_type(pcscf)
340 if addr_type == None:
341 raise ValueError("Unknown PCSCF address type or invalid address provided")
342 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100343 else:
344 # Just the tag value
345 content = '80'
346 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100347 pcscf_tlv = rpad(content, rec_size_bytes*2)
348 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100349 return sw
350
Supreeth Herle05b28072020-03-25 10:23:48 +0100351 def read_domain(self):
352 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
353 if sw == '9000':
354 # Skip the inital tag value ('80') byte and get length of contents
355 length = int(res[2:4], 16)
356 content = h2s(res[4:4+(length*2)])
357 return (content, sw)
358 else:
359 return (None, sw)
360
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100361 def update_domain(self, domain=None, mcc=None, mnc=None):
362 hex_str = ""
363 if domain:
364 hex_str = s2h(domain)
365 elif mcc and mnc:
366 # MCC and MNC always has 3 digits in domain form
367 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
368 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
369
370 # Build TLV
371 tlv = TLV(['80'])
372 content = tlv.build({'80': hex_str})
373
374 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
375 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
376 return sw
377
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100378 def read_impi(self):
379 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
380 if sw == '9000':
381 # Skip the inital tag value ('80') byte and get length of contents
382 length = int(res[2:4], 16)
383 content = h2s(res[4:4+(length*2)])
384 return (content, sw)
385 else:
386 return (None, sw)
387
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100388 def update_impi(self, impi=None):
389 hex_str = ""
390 if impi:
391 hex_str = s2h(impi)
392 # Build TLV
393 tlv = TLV(['80'])
394 content = tlv.build({'80': hex_str})
395
396 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
397 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
398 return sw
399
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100400 def read_impu(self):
401 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
402 impu_recs = ""
403 for i in range(0, rec_cnt):
404 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
405 if sw == '9000':
406 # Skip the inital tag value ('80') byte and get length of contents
407 length = int(res[2:4], 16)
408 content = h2s(res[4:4+(length*2)])
409 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
410 else:
411 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
412 return impu_recs
413
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100414 def update_impu(self, impu=None):
415 hex_str = ""
416 if impu:
417 hex_str = s2h(impu)
418 # Build TLV
419 tlv = TLV(['80'])
420 content = tlv.build({'80': hex_str})
421
422 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
423 impu_tlv = rpad(content, rec_size_bytes*2)
424 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
425 return sw
426
Sylvain Munaut76504e02010-12-07 00:24:32 +0100427
428class _MagicSimBase(Card):
429 """
430 Theses cards uses several record based EFs to store the provider infos,
431 each possible provider uses a specific record number in each EF. The
432 indexes used are ( where N is the number of providers supported ) :
433 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100434 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100435
436 * 3f00/7f4d/8f0c : Operator Name
437
438 bytes 0-15 : provider name, padded with 0xff
439 byte 16 : length of the provider name
440 byte 17 : 01 for valid records, 00 otherwise
441
442 * 3f00/7f4d/8f0d : Programmable Binary EFs
443
444 * 3f00/7f4d/8f0e : Programmable Record EFs
445
446 """
447
448 @classmethod
449 def autodetect(kls, scc):
450 try:
451 for p, l, t in kls._files.values():
452 if not t:
453 continue
454 if scc.record_size(['3f00', '7f4d', p]) != l:
455 return None
456 except:
457 return None
458
459 return kls(scc)
460
461 def _get_count(self):
462 """
463 Selects the file and returns the total number of entries
464 and entry size
465 """
466 f = self._files['name']
467
468 r = self._scc.select_file(['3f00', '7f4d', f[0]])
469 rec_len = int(r[-1][28:30], 16)
470 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200471 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100472
473 if (rec_cnt < 1) or (rec_len != f[1]):
474 raise RuntimeError('Bad card type')
475
476 return rec_cnt
477
478 def program(self, p):
479 # Go to dir
480 self._scc.select_file(['3f00', '7f4d'])
481
482 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400483 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100484
485 # Operator name ( 3f00/7f4d/8f0c )
486 self._scc.update_record(self._files['name'][0], 2,
487 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
488 )
489
490 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
491 v = ''
492
493 # inline Ki
494 if self._ki_file is None:
495 v += p['ki']
496
497 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400498 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100499
500 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400501 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100502
503 # Ki
504 if self._ki_file:
505 v += self._ki_file + '10' + p['ki']
506
507 # PLMN_Sel
508 v+= '6f30' + '18' + rpad(hplmn, 36)
509
Alexander Chemeris21885242013-07-02 16:56:55 +0400510 # ACC
511 # This doesn't work with "fake" SuperSIM cards,
512 # but will hopefully work with real SuperSIMs.
513 if p.get('acc') is not None:
514 v+= '6f78' + '02' + lpad(p['acc'], 4)
515
Sylvain Munaut76504e02010-12-07 00:24:32 +0100516 self._scc.update_record(self._files['b_ef'][0], 1,
517 rpad(v, self._files['b_ef'][1]*2)
518 )
519
520 # SMSP ( 3f00/7f4d/8f0e )
521 # FIXME
522
523 # Write PLMN_Sel forcefully as well
524 r = self._scc.select_file(['3f00', '7f20', '6f30'])
525 tl = int(r[-1][4:8], 16)
526
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400527 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100528 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
529
530 def erase(self):
531 # Dummy
532 df = {}
533 for k, v in self._files.iteritems():
534 ofs = 1
535 fv = v[1] * 'ff'
536 if k == 'name':
537 ofs = 2
538 fv = fv[0:-4] + '0000'
539 df[v[0]] = (fv, ofs)
540
541 # Write
542 for n in range(0,self._get_count()):
543 for k, (msg, ofs) in df.iteritems():
544 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
545
546
547class SuperSim(_MagicSimBase):
548
549 name = 'supersim'
550
551 _files = {
552 'name' : ('8f0c', 18, True),
553 'b_ef' : ('8f0d', 74, True),
554 'r_ef' : ('8f0e', 50, True),
555 }
556
557 _ki_file = None
558
559
560class MagicSim(_MagicSimBase):
561
562 name = 'magicsim'
563
564 _files = {
565 'name' : ('8f0c', 18, True),
566 'b_ef' : ('8f0d', 130, True),
567 'r_ef' : ('8f0e', 102, False),
568 }
569
570 _ki_file = '6f1b'
571
572
573class FakeMagicSim(Card):
574 """
575 Theses cards have a record based EF 3f00/000c that contains the provider
576 informations. See the program method for its format. The records go from
577 1 to N.
578 """
579
580 name = 'fakemagicsim'
581
582 @classmethod
583 def autodetect(kls, scc):
584 try:
585 if scc.record_size(['3f00', '000c']) != 0x5a:
586 return None
587 except:
588 return None
589
590 return kls(scc)
591
592 def _get_infos(self):
593 """
594 Selects the file and returns the total number of entries
595 and entry size
596 """
597
598 r = self._scc.select_file(['3f00', '000c'])
599 rec_len = int(r[-1][28:30], 16)
600 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200601 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100602
603 if (rec_cnt < 1) or (rec_len != 0x5a):
604 raise RuntimeError('Bad card type')
605
606 return rec_cnt, rec_len
607
608 def program(self, p):
609 # Home PLMN
610 r = self._scc.select_file(['3f00', '7f20', '6f30'])
611 tl = int(r[-1][4:8], 16)
612
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400613 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
615
616 # Get total number of entries and entry size
617 rec_cnt, rec_len = self._get_infos()
618
619 # Set first entry
620 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200621 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100622 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200623 enc_iccid(p['iccid']) + # 10b ICCID
624 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
625 p['ki'] + # 16b Ki
626 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100627 )
628 self._scc.update_record('000c', 1, entry)
629
630 def erase(self):
631 # Get total number of entries and entry size
632 rec_cnt, rec_len = self._get_infos()
633
634 # Erase all entries
635 entry = 'ff' * rec_len
636 for i in range(0, rec_cnt):
637 self._scc.update_record('000c', 1+i, entry)
638
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200639
Harald Welte3156d902011-03-22 21:48:19 +0100640class GrcardSim(Card):
641 """
642 Greencard (grcard.cn) HZCOS GSM SIM
643 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
644 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
645 """
646
647 name = 'grcardsim'
648
649 @classmethod
650 def autodetect(kls, scc):
651 return None
652
653 def program(self, p):
654 # We don't really know yet what ADM PIN 4 is about
655 #self._scc.verify_chv(4, h2b("4444444444444444"))
656
657 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100658 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200659 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100660 else:
661 pin = h2b("4444444444444444")
662 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100663
664 # EF.ICCID
665 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400666 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100667
668 # EF.IMSI
669 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400670 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100671
672 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400673 if p.get('acc') is not None:
674 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100675
676 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200677 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200678 r = self._scc.select_file(['3f00', '7f10', '6f42'])
679 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100680
681 # Set the Ki using proprietary command
682 pdu = '80d4020010' + p['ki']
683 data, sw = self._scc._tp.send_apdu(pdu)
684
685 # EF.HPLMN
686 r = self._scc.select_file(['3f00', '7f20', '6f30'])
687 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400688 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100689 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
690
691 # EF.SPN (Service Provider Name)
692 r = self._scc.select_file(['3f00', '7f20', '6f30'])
693 size = int(r[-1][4:8], 16)
694 # FIXME
695
696 # FIXME: EF.MSISDN
697
Sylvain Munaut76504e02010-12-07 00:24:32 +0100698
Harald Weltee10394b2011-12-07 12:34:14 +0100699class SysmoSIMgr1(GrcardSim):
700 """
701 sysmocom sysmoSIM-GR1
702 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
703 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
704 """
705 name = 'sysmosim-gr1'
706
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200707 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200708 def autodetect(kls, scc):
709 try:
710 # Look for ATR
711 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
712 return kls(scc)
713 except:
714 return None
715 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200716
Harald Welteca673942020-06-03 15:19:40 +0200717class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100718 """
719 sysmocom sysmoUSIM-GR1
720 """
721 name = 'sysmoUSIM-GR1'
722
723 @classmethod
724 def autodetect(kls, scc):
725 # TODO: Access the ATR
726 return None
727
728 def program(self, p):
729 # TODO: check if verify_chv could be used or what it needs
730 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
731 # Unlock the card..
732 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
733
734 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100735 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400736 p['opc'] + # 32b OPC
737 enc_iccid(p['iccid']) + # 10b ICCID
738 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100739 )
740 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
741
Sylvain Munaut053c8952013-07-02 15:12:32 +0200742
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100743class SysmoSIMgr2(Card):
744 """
745 sysmocom sysmoSIM-GR2
746 """
747
748 name = 'sysmoSIM-GR2'
749
750 @classmethod
751 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900752 try:
753 # Look for ATR
754 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
755 return kls(scc)
756 except:
757 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100758 return None
759
760 def program(self, p):
761
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200762 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100763 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200764
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100765 # authenticate as SUPER ADM using default key
766 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
767
768 # set ADM pin using proprietary command
769 # INS: D4
770 # P1: 3A for PIN, 3B for PUK
771 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
772 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100773 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200774 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100775 else:
776 pin = h2b("4444444444444444")
777
778 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100779 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200780
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100781 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100782
783 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100784
785 # write EF.ICCID
786 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
787
788 # select DF_GSM
789 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200790
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100791 # write EF.IMSI
792 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
793
794 # write EF.ACC
795 if p.get('acc') is not None:
796 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
797
798 # get size and write EF.HPLMN
799 r = self._scc.select_file(['6f30'])
800 size = int(r[-1][4:8], 16)
801 hplmn = enc_plmn(p['mcc'], p['mnc'])
802 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
803
804 # set COMP128 version 0 in proprietary file
805 data, sw = self._scc.update_binary('0001', '001000')
806
807 # set Ki in proprietary file
808 data, sw = self._scc.update_binary('0001', p['ki'], 3)
809
810 # select DF_TELECOM
811 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200812
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100813 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200814 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200815 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100816
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100817
Harald Welteca673942020-06-03 15:19:40 +0200818class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100819 """
820 sysmocom sysmoUSIM-SJS1
821 """
822
823 name = 'sysmoUSIM-SJS1'
824
825 def __init__(self, ssc):
826 super(SysmoUSIMSJS1, self).__init__(ssc)
827 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100828 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100829
830 @classmethod
831 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900832 try:
833 # Look for ATR
834 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"):
835 return kls(scc)
836 except:
837 return None
Jan Balke3e840672015-01-26 15:36:27 +0100838 return None
839
840 def program(self, p):
841
Philipp Maiere9604882017-03-21 17:24:31 +0100842 # authenticate as ADM using default key (written on the card..)
843 if not p['pin_adm']:
844 raise ValueError("Please provide a PIN-ADM as there is no default one")
845 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100846
847 # select MF
848 r = self._scc.select_file(['3f00'])
849
Philipp Maiere9604882017-03-21 17:24:31 +0100850 # write EF.ICCID
851 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
852
Jan Balke3e840672015-01-26 15:36:27 +0100853 # select DF_GSM
854 r = self._scc.select_file(['7f20'])
855
Jan Balke3e840672015-01-26 15:36:27 +0100856 # set Ki in proprietary file
857 data, sw = self._scc.update_binary('00FF', p['ki'])
858
Philipp Maier1be35bf2018-07-13 11:29:03 +0200859 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200860 if 'opc' in p:
861 content = "01" + p['opc']
862 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100863
Supreeth Herle7947d922019-06-08 07:50:53 +0200864 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100865 if p.get('name') is not None:
866 content = enc_spn(p['name'], True, True)
867 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200868
Supreeth Herlec8796a32019-12-23 12:23:42 +0100869 if p.get('acc') is not None:
870 self.update_acc(p['acc'])
871
Jan Balke3e840672015-01-26 15:36:27 +0100872 # write EF.IMSI
873 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
874
Philipp Maier2d15ea02019-03-20 12:40:36 +0100875 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200876 if p.get('mcc') and p.get('mnc'):
877 sw = self.update_plmnsel(p['mcc'], p['mnc'])
878 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100879 print("Programming PLMNsel failed with code %s"%sw)
880
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200881 # EF.PLMNwAcT
882 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100883 sw = self.update_plmn_act(p['mcc'], p['mnc'])
884 if sw != '9000':
885 print("Programming PLMNwAcT failed with code %s"%sw)
886
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200887 # EF.OPLMNwAcT
888 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100889 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
890 if sw != '9000':
891 print("Programming OPLMNwAcT failed with code %s"%sw)
892
Supreeth Herlef442fb42020-01-21 12:47:32 +0100893 # EF.HPLMNwAcT
894 if p.get('mcc') and p.get('mnc'):
895 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
896 if sw != '9000':
897 print("Programming HPLMNwAcT failed with code %s"%sw)
898
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200899 # EF.AD
900 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100901 sw = self.update_ad(p['mnc'])
902 if sw != '9000':
903 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100904
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200905 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200906 if p.get('smsp'):
907 r = self._scc.select_file(['3f00', '7f10'])
908 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100909
Supreeth Herle5a541012019-12-22 08:59:16 +0100910 # EF.MSISDN
911 # TODO: Alpha Identifier (currently 'ff'O * 20)
912 # TODO: Capability/Configuration1 Record Identifier
913 # TODO: Extension1 Record Identifier
914 if p.get('msisdn') is not None:
915 msisdn = enc_msisdn(p['msisdn'])
916 data = 'ff' * 20 + msisdn + 'ff' * 2
917
918 r = self._scc.select_file(['3f00', '7f10'])
919 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
920
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900921
herlesupreeth4a3580b2020-09-29 10:11:36 +0200922class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900923 """
924 FairwavesSIM
925
926 The SIM card is operating according to the standard.
927 For Ki/OP/OPC programming the following files are additionally open for writing:
928 3F00/7F20/FF01 – OP/OPC:
929 byte 1 = 0x01, bytes 2-17: OPC;
930 byte 1 = 0x00, bytes 2-17: OP;
931 3F00/7F20/FF02: Ki
932 """
933
Philipp Maier5a876312019-11-11 11:01:46 +0100934 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900935 # Propriatary files
936 _EF_num = {
937 'Ki': 'FF02',
938 'OP/OPC': 'FF01',
939 }
940 _EF = {
941 'Ki': DF['GSM']+[_EF_num['Ki']],
942 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
943 }
944
945 def __init__(self, ssc):
946 super(FairwavesSIM, self).__init__(ssc)
947 self._adm_chv_num = 0x11
948 self._adm2_chv_num = 0x12
949
950
951 @classmethod
952 def autodetect(kls, scc):
953 try:
954 # Look for ATR
955 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"):
956 return kls(scc)
957 except:
958 return None
959 return None
960
961
962 def verify_adm2(self, key):
963 '''
964 Authenticate with ADM2 key.
965
966 Fairwaves SIM cards support hierarchical key structure and ADM2 key
967 is a key which has access to proprietary files (Ki and OP/OPC).
968 That said, ADM key inherits permissions of ADM2 key and thus we rarely
969 need ADM2 key per se.
970 '''
971 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
972 return sw
973
974
975 def read_ki(self):
976 """
977 Read Ki in proprietary file.
978
979 Requires ADM1 access level
980 """
981 return self._scc.read_binary(self._EF['Ki'])
982
983
984 def update_ki(self, ki):
985 """
986 Set Ki in proprietary file.
987
988 Requires ADM1 access level
989 """
990 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
991 return sw
992
993
994 def read_op_opc(self):
995 """
996 Read Ki in proprietary file.
997
998 Requires ADM1 access level
999 """
1000 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1001 type = 'OP' if ef[0:2] == '00' else 'OPC'
1002 return ((type, ef[2:]), sw)
1003
1004
1005 def update_op(self, op):
1006 """
1007 Set OP in proprietary file.
1008
1009 Requires ADM1 access level
1010 """
1011 content = '00' + op
1012 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1013 return sw
1014
1015
1016 def update_opc(self, opc):
1017 """
1018 Set OPC in proprietary file.
1019
1020 Requires ADM1 access level
1021 """
1022 content = '01' + opc
1023 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1024 return sw
1025
1026
1027 def program(self, p):
1028 # authenticate as ADM1
1029 if not p['pin_adm']:
1030 raise ValueError("Please provide a PIN-ADM as there is no default one")
1031 sw = self.verify_adm(h2b(p['pin_adm']))
1032 if sw != '9000':
1033 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1034
1035 # TODO: Set operator name
1036 if p.get('smsp') is not None:
1037 sw = self.update_smsp(p['smsp'])
1038 if sw != '9000':
1039 print("Programming SMSP failed with code %s"%sw)
1040 # This SIM doesn't support changing ICCID
1041 if p.get('mcc') is not None and p.get('mnc') is not None:
1042 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1043 if sw != '9000':
1044 print("Programming MCC/MNC failed with code %s"%sw)
1045 if p.get('imsi') is not None:
1046 sw = self.update_imsi(p['imsi'])
1047 if sw != '9000':
1048 print("Programming IMSI failed with code %s"%sw)
1049 if p.get('ki') is not None:
1050 sw = self.update_ki(p['ki'])
1051 if sw != '9000':
1052 print("Programming Ki failed with code %s"%sw)
1053 if p.get('opc') is not None:
1054 sw = self.update_opc(p['opc'])
1055 if sw != '9000':
1056 print("Programming OPC failed with code %s"%sw)
1057 if p.get('acc') is not None:
1058 sw = self.update_acc(p['acc'])
1059 if sw != '9000':
1060 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001061
Todd Neal9eeadfc2018-04-25 15:36:29 -05001062class OpenCellsSim(Card):
1063 """
1064 OpenCellsSim
1065
1066 """
1067
Philipp Maier5a876312019-11-11 11:01:46 +01001068 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001069
1070 def __init__(self, ssc):
1071 super(OpenCellsSim, self).__init__(ssc)
1072 self._adm_chv_num = 0x0A
1073
1074
1075 @classmethod
1076 def autodetect(kls, scc):
1077 try:
1078 # Look for ATR
1079 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"):
1080 return kls(scc)
1081 except:
1082 return None
1083 return None
1084
1085
1086 def program(self, p):
1087 if not p['pin_adm']:
1088 raise ValueError("Please provide a PIN-ADM as there is no default one")
1089 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1090
1091 # select MF
1092 r = self._scc.select_file(['3f00'])
1093
1094 # write EF.ICCID
1095 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1096
1097 r = self._scc.select_file(['7ff0'])
1098
1099 # set Ki in proprietary file
1100 data, sw = self._scc.update_binary('FF02', p['ki'])
1101
1102 # set OPC in proprietary file
1103 data, sw = self._scc.update_binary('FF01', p['opc'])
1104
1105 # select DF_GSM
1106 r = self._scc.select_file(['7f20'])
1107
1108 # write EF.IMSI
1109 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1110
herlesupreeth4a3580b2020-09-29 10:11:36 +02001111class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001112 """
1113 WavemobileSim
1114
1115 """
1116
1117 name = 'Wavemobile-SIM'
1118
1119 def __init__(self, ssc):
1120 super(WavemobileSim, self).__init__(ssc)
1121 self._adm_chv_num = 0x0A
1122 self._scc.cla_byte = "00"
1123 self._scc.sel_ctrl = "0004" #request an FCP
1124
1125 @classmethod
1126 def autodetect(kls, scc):
1127 try:
1128 # Look for ATR
1129 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"):
1130 return kls(scc)
1131 except:
1132 return None
1133 return None
1134
1135 def program(self, p):
1136 if not p['pin_adm']:
1137 raise ValueError("Please provide a PIN-ADM as there is no default one")
1138 sw = self.verify_adm(h2b(p['pin_adm']))
1139 if sw != '9000':
1140 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1141
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001142 # EF.ICCID
1143 # TODO: Add programming of the ICCID
1144 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001145 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1146
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001147 # KI (Presumably a propritary file)
1148 # TODO: Add programming of KI
1149 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001150 print("Warning: Programming of the KI is not implemented for this type of card.")
1151
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001152 # OPc (Presumably a propritary file)
1153 # TODO: Add programming of OPc
1154 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001155 print("Warning: Programming of the OPc is not implemented for this type of card.")
1156
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001157 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001158 if p.get('smsp'):
1159 sw = self.update_smsp(p['smsp'])
1160 if sw != '9000':
1161 print("Programming SMSP failed with code %s"%sw)
1162
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001163 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001164 if p.get('imsi'):
1165 sw = self.update_imsi(p['imsi'])
1166 if sw != '9000':
1167 print("Programming IMSI failed with code %s"%sw)
1168
1169 # EF.ACC
1170 if p.get('acc'):
1171 sw = self.update_acc(p['acc'])
1172 if sw != '9000':
1173 print("Programming ACC failed with code %s"%sw)
1174
1175 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001176 if p.get('mcc') and p.get('mnc'):
1177 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1178 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001179 print("Programming PLMNsel failed with code %s"%sw)
1180
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001181 # EF.PLMNwAcT
1182 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001183 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1184 if sw != '9000':
1185 print("Programming PLMNwAcT failed with code %s"%sw)
1186
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001187 # EF.OPLMNwAcT
1188 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001189 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1190 if sw != '9000':
1191 print("Programming OPLMNwAcT failed with code %s"%sw)
1192
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001193 # EF.AD
1194 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001195 sw = self.update_ad(p['mnc'])
1196 if sw != '9000':
1197 print("Programming AD failed with code %s"%sw)
1198
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001199 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001200
Todd Neal9eeadfc2018-04-25 15:36:29 -05001201
herlesupreethb0c7d122020-12-23 09:25:46 +01001202class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001203 """
1204 sysmocom sysmoISIM-SJA2
1205 """
1206
1207 name = 'sysmoISIM-SJA2'
1208
1209 def __init__(self, ssc):
1210 super(SysmoISIMSJA2, self).__init__(ssc)
1211 self._scc.cla_byte = "00"
1212 self._scc.sel_ctrl = "0004" #request an FCP
1213
1214 @classmethod
1215 def autodetect(kls, scc):
1216 try:
1217 # Try card model #1
1218 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1219 if scc.get_atr() == toBytes(atr):
1220 return kls(scc)
1221
1222 # Try card model #2
1223 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1224 if scc.get_atr() == toBytes(atr):
1225 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001226
1227 # Try card model #3
1228 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1229 if scc.get_atr() == toBytes(atr):
1230 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001231 except:
1232 return None
1233 return None
1234
1235 def program(self, p):
1236 # authenticate as ADM using default key (written on the card..)
1237 if not p['pin_adm']:
1238 raise ValueError("Please provide a PIN-ADM as there is no default one")
1239 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1240
1241 # This type of card does not allow to reprogram the ICCID.
1242 # Reprogramming the ICCID would mess up the card os software
1243 # license management, so the ICCID must be kept at its factory
1244 # setting!
1245 if p.get('iccid'):
1246 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1247
1248 # select DF_GSM
1249 self._scc.select_file(['7f20'])
1250
1251 # write EF.IMSI
1252 if p.get('imsi'):
1253 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1254
1255 # EF.PLMNsel
1256 if p.get('mcc') and p.get('mnc'):
1257 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1258 if sw != '9000':
1259 print("Programming PLMNsel failed with code %s"%sw)
1260
1261 # EF.PLMNwAcT
1262 if p.get('mcc') and p.get('mnc'):
1263 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1264 if sw != '9000':
1265 print("Programming PLMNwAcT failed with code %s"%sw)
1266
1267 # EF.OPLMNwAcT
1268 if p.get('mcc') and p.get('mnc'):
1269 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1270 if sw != '9000':
1271 print("Programming OPLMNwAcT failed with code %s"%sw)
1272
Harald Welte32f0d412020-05-05 17:35:57 +02001273 # EF.HPLMNwAcT
1274 if p.get('mcc') and p.get('mnc'):
1275 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1276 if sw != '9000':
1277 print("Programming HPLMNwAcT failed with code %s"%sw)
1278
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001279 # EF.AD
1280 if p.get('mcc') and p.get('mnc'):
1281 sw = self.update_ad(p['mnc'])
1282 if sw != '9000':
1283 print("Programming AD failed with code %s"%sw)
1284
1285 # EF.SMSP
1286 if p.get('smsp'):
1287 r = self._scc.select_file(['3f00', '7f10'])
1288 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1289
Supreeth Herle80164052020-03-23 12:06:29 +01001290 # Populate AIDs
1291 self.read_aids()
1292
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001293 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1294 # hard linked to EF-USIM_AUTH_KEY)
1295 self._scc.select_file(['3f00'])
1296 self._scc.select_file(['a515'])
1297 if p.get('ki'):
1298 self._scc.update_binary('6f20', p['ki'], 1)
1299 if p.get('opc'):
1300 self._scc.update_binary('6f20', p['opc'], 17)
1301
1302 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001303 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001304 if p.get('ki'):
1305 self._scc.update_binary('af20', p['ki'], 1)
1306 if p.get('opc'):
1307 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001308
Supreeth Herlecf727f22020-03-24 17:32:21 +01001309 # update EF.P-CSCF in ADF.ISIM
1310 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1311 if p.get('pcscf'):
1312 sw = self.update_pcscf(p['pcscf'])
1313 else:
1314 sw = self.update_pcscf("")
1315 if sw != '9000':
1316 print("Programming P-CSCF failed with code %s"%sw)
1317
1318
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001319 # update EF.DOMAIN in ADF.ISIM
1320 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1321 if p.get('ims_hdomain'):
1322 sw = self.update_domain(domain=p['ims_hdomain'])
1323 else:
1324 sw = self.update_domain()
1325
1326 if sw != '9000':
1327 print("Programming Home Network Domain Name failed with code %s"%sw)
1328
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001329 # update EF.IMPI in ADF.ISIM
1330 # TODO: Validate IMPI input
1331 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1332 if p.get('impi'):
1333 sw = self.update_impi(p['impi'])
1334 else:
1335 sw = self.update_impi()
1336 if sw != '9000':
1337 print("Programming IMPI failed with code %s"%sw)
1338
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001339 # update EF.IMPU in ADF.ISIM
1340 # TODO: Validate IMPU input
1341 # Support multiple IMPU if there is enough space
1342 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1343 if p.get('impu'):
1344 sw = self.update_impu(p['impu'])
1345 else:
1346 sw = self.update_impu()
1347 if sw != '9000':
1348 print("Programming IMPU failed with code %s"%sw)
1349
herlesupreeth1a13c442020-09-11 21:16:51 +02001350 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001351 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001352 if p.get('ki'):
1353 self._scc.update_binary('af20', p['ki'], 1)
1354 if p.get('opc'):
1355 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001356
Harald Welteca673942020-06-03 15:19:40 +02001357 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001358 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001359 if p.get('mcc') and p.get('mnc'):
1360 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1361 if sw != '9000':
1362 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001363
1364 # update EF.ePDGId in ADF.USIM
1365 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1366 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001367 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001368 else:
1369 sw = self.update_epdgid("")
1370 if sw != '9000':
1371 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001372
Supreeth Herlef964df42020-03-24 13:15:37 +01001373 # update EF.ePDGSelection in ADF.USIM
1374 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1375 if p.get('epdgSelection'):
1376 epdg_plmn = p['epdgSelection']
1377 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1378 else:
1379 sw = self.update_ePDGSelection("", "")
1380 if sw != '9000':
1381 print("Programming ePDGSelection failed with code %s"%sw)
1382
1383
Supreeth Herleacc222f2020-03-24 13:26:53 +01001384 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1385 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001386 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001387 if self.file_exists(EF_USIM_ADF_map['UST']):
1388 if p.get('epdgSelection') and p.get('epdgid'):
1389 sw = self.update_ust(106, 1)
1390 if sw != '9000':
1391 print("Programming UST failed with code %s"%sw)
1392 sw = self.update_ust(107, 1)
1393 if sw != '9000':
1394 print("Programming UST failed with code %s"%sw)
1395
Supreeth Herle44e04622020-03-25 10:34:28 +01001396 sw = self.update_ust(95, 0)
1397 if sw != '9000':
1398 print("Programming UST failed with code %s"%sw)
1399 sw = self.update_ust(99, 0)
1400 if sw != '9000':
1401 print("Programming UST failed with code %s"%sw)
1402 sw = self.update_ust(115, 0)
1403 if sw != '9000':
1404 print("Programming UST failed with code %s"%sw)
1405
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001406 return
1407
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001408
Todd Neal9eeadfc2018-04-25 15:36:29 -05001409# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001410_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001411 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001412 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001413
1414def card_autodetect(scc):
1415 for kls in _cards_classes:
1416 card = kls.autodetect(scc)
1417 if card is not None:
1418 card.reset()
1419 return card
1420 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001421
1422def card_detect(ctype, scc):
1423 # Detect type if needed
1424 card = None
1425 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1426
1427 if ctype in ("auto", "auto_once"):
1428 for kls in _cards_classes:
1429 card = kls.autodetect(scc)
1430 if card:
1431 print("Autodetected card type: %s" % card.name)
1432 card.reset()
1433 break
1434
1435 if card is None:
1436 print("Autodetection failed")
1437 return None
1438
1439 if ctype == "auto_once":
1440 ctype = card.name
1441
1442 elif ctype in ctypes:
1443 card = ctypes[ctype](scc)
1444
1445 else:
1446 raise ValueError("Unknown card type: %s" % ctype)
1447
1448 return card