blob: 17da5064a7ba2b87bdbf1c82b003e017f53ae395 [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
Sylvain Munaut76504e02010-12-07 00:24:32 +0100378
379class _MagicSimBase(Card):
380 """
381 Theses cards uses several record based EFs to store the provider infos,
382 each possible provider uses a specific record number in each EF. The
383 indexes used are ( where N is the number of providers supported ) :
384 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100385 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100386
387 * 3f00/7f4d/8f0c : Operator Name
388
389 bytes 0-15 : provider name, padded with 0xff
390 byte 16 : length of the provider name
391 byte 17 : 01 for valid records, 00 otherwise
392
393 * 3f00/7f4d/8f0d : Programmable Binary EFs
394
395 * 3f00/7f4d/8f0e : Programmable Record EFs
396
397 """
398
399 @classmethod
400 def autodetect(kls, scc):
401 try:
402 for p, l, t in kls._files.values():
403 if not t:
404 continue
405 if scc.record_size(['3f00', '7f4d', p]) != l:
406 return None
407 except:
408 return None
409
410 return kls(scc)
411
412 def _get_count(self):
413 """
414 Selects the file and returns the total number of entries
415 and entry size
416 """
417 f = self._files['name']
418
419 r = self._scc.select_file(['3f00', '7f4d', f[0]])
420 rec_len = int(r[-1][28:30], 16)
421 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200422 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100423
424 if (rec_cnt < 1) or (rec_len != f[1]):
425 raise RuntimeError('Bad card type')
426
427 return rec_cnt
428
429 def program(self, p):
430 # Go to dir
431 self._scc.select_file(['3f00', '7f4d'])
432
433 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400434 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100435
436 # Operator name ( 3f00/7f4d/8f0c )
437 self._scc.update_record(self._files['name'][0], 2,
438 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
439 )
440
441 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
442 v = ''
443
444 # inline Ki
445 if self._ki_file is None:
446 v += p['ki']
447
448 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400449 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100450
451 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400452 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100453
454 # Ki
455 if self._ki_file:
456 v += self._ki_file + '10' + p['ki']
457
458 # PLMN_Sel
459 v+= '6f30' + '18' + rpad(hplmn, 36)
460
Alexander Chemeris21885242013-07-02 16:56:55 +0400461 # ACC
462 # This doesn't work with "fake" SuperSIM cards,
463 # but will hopefully work with real SuperSIMs.
464 if p.get('acc') is not None:
465 v+= '6f78' + '02' + lpad(p['acc'], 4)
466
Sylvain Munaut76504e02010-12-07 00:24:32 +0100467 self._scc.update_record(self._files['b_ef'][0], 1,
468 rpad(v, self._files['b_ef'][1]*2)
469 )
470
471 # SMSP ( 3f00/7f4d/8f0e )
472 # FIXME
473
474 # Write PLMN_Sel forcefully as well
475 r = self._scc.select_file(['3f00', '7f20', '6f30'])
476 tl = int(r[-1][4:8], 16)
477
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400478 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100479 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
480
481 def erase(self):
482 # Dummy
483 df = {}
484 for k, v in self._files.iteritems():
485 ofs = 1
486 fv = v[1] * 'ff'
487 if k == 'name':
488 ofs = 2
489 fv = fv[0:-4] + '0000'
490 df[v[0]] = (fv, ofs)
491
492 # Write
493 for n in range(0,self._get_count()):
494 for k, (msg, ofs) in df.iteritems():
495 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
496
497
498class SuperSim(_MagicSimBase):
499
500 name = 'supersim'
501
502 _files = {
503 'name' : ('8f0c', 18, True),
504 'b_ef' : ('8f0d', 74, True),
505 'r_ef' : ('8f0e', 50, True),
506 }
507
508 _ki_file = None
509
510
511class MagicSim(_MagicSimBase):
512
513 name = 'magicsim'
514
515 _files = {
516 'name' : ('8f0c', 18, True),
517 'b_ef' : ('8f0d', 130, True),
518 'r_ef' : ('8f0e', 102, False),
519 }
520
521 _ki_file = '6f1b'
522
523
524class FakeMagicSim(Card):
525 """
526 Theses cards have a record based EF 3f00/000c that contains the provider
527 informations. See the program method for its format. The records go from
528 1 to N.
529 """
530
531 name = 'fakemagicsim'
532
533 @classmethod
534 def autodetect(kls, scc):
535 try:
536 if scc.record_size(['3f00', '000c']) != 0x5a:
537 return None
538 except:
539 return None
540
541 return kls(scc)
542
543 def _get_infos(self):
544 """
545 Selects the file and returns the total number of entries
546 and entry size
547 """
548
549 r = self._scc.select_file(['3f00', '000c'])
550 rec_len = int(r[-1][28:30], 16)
551 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200552 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100553
554 if (rec_cnt < 1) or (rec_len != 0x5a):
555 raise RuntimeError('Bad card type')
556
557 return rec_cnt, rec_len
558
559 def program(self, p):
560 # Home PLMN
561 r = self._scc.select_file(['3f00', '7f20', '6f30'])
562 tl = int(r[-1][4:8], 16)
563
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400564 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100565 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
566
567 # Get total number of entries and entry size
568 rec_cnt, rec_len = self._get_infos()
569
570 # Set first entry
571 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200572 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100573 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200574 enc_iccid(p['iccid']) + # 10b ICCID
575 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
576 p['ki'] + # 16b Ki
577 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100578 )
579 self._scc.update_record('000c', 1, entry)
580
581 def erase(self):
582 # Get total number of entries and entry size
583 rec_cnt, rec_len = self._get_infos()
584
585 # Erase all entries
586 entry = 'ff' * rec_len
587 for i in range(0, rec_cnt):
588 self._scc.update_record('000c', 1+i, entry)
589
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200590
Harald Welte3156d902011-03-22 21:48:19 +0100591class GrcardSim(Card):
592 """
593 Greencard (grcard.cn) HZCOS GSM SIM
594 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
595 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
596 """
597
598 name = 'grcardsim'
599
600 @classmethod
601 def autodetect(kls, scc):
602 return None
603
604 def program(self, p):
605 # We don't really know yet what ADM PIN 4 is about
606 #self._scc.verify_chv(4, h2b("4444444444444444"))
607
608 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100609 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200610 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100611 else:
612 pin = h2b("4444444444444444")
613 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100614
615 # EF.ICCID
616 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400617 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100618
619 # EF.IMSI
620 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400621 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100622
623 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400624 if p.get('acc') is not None:
625 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100626
627 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200628 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200629 r = self._scc.select_file(['3f00', '7f10', '6f42'])
630 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100631
632 # Set the Ki using proprietary command
633 pdu = '80d4020010' + p['ki']
634 data, sw = self._scc._tp.send_apdu(pdu)
635
636 # EF.HPLMN
637 r = self._scc.select_file(['3f00', '7f20', '6f30'])
638 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400639 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100640 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
641
642 # EF.SPN (Service Provider Name)
643 r = self._scc.select_file(['3f00', '7f20', '6f30'])
644 size = int(r[-1][4:8], 16)
645 # FIXME
646
647 # FIXME: EF.MSISDN
648
Sylvain Munaut76504e02010-12-07 00:24:32 +0100649
Harald Weltee10394b2011-12-07 12:34:14 +0100650class SysmoSIMgr1(GrcardSim):
651 """
652 sysmocom sysmoSIM-GR1
653 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
654 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
655 """
656 name = 'sysmosim-gr1'
657
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200658 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200659 def autodetect(kls, scc):
660 try:
661 # Look for ATR
662 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
663 return kls(scc)
664 except:
665 return None
666 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200667
Harald Welteca673942020-06-03 15:19:40 +0200668class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100669 """
670 sysmocom sysmoUSIM-GR1
671 """
672 name = 'sysmoUSIM-GR1'
673
674 @classmethod
675 def autodetect(kls, scc):
676 # TODO: Access the ATR
677 return None
678
679 def program(self, p):
680 # TODO: check if verify_chv could be used or what it needs
681 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
682 # Unlock the card..
683 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
684
685 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100686 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400687 p['opc'] + # 32b OPC
688 enc_iccid(p['iccid']) + # 10b ICCID
689 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100690 )
691 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
692
Sylvain Munaut053c8952013-07-02 15:12:32 +0200693
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100694class SysmoSIMgr2(Card):
695 """
696 sysmocom sysmoSIM-GR2
697 """
698
699 name = 'sysmoSIM-GR2'
700
701 @classmethod
702 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900703 try:
704 # Look for ATR
705 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
706 return kls(scc)
707 except:
708 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100709 return None
710
711 def program(self, p):
712
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200713 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100714 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200715
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100716 # authenticate as SUPER ADM using default key
717 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
718
719 # set ADM pin using proprietary command
720 # INS: D4
721 # P1: 3A for PIN, 3B for PUK
722 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
723 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100724 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200725 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100726 else:
727 pin = h2b("4444444444444444")
728
729 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100730 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200731
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100732 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100733
734 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100735
736 # write EF.ICCID
737 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
738
739 # select DF_GSM
740 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200741
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100742 # write EF.IMSI
743 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
744
745 # write EF.ACC
746 if p.get('acc') is not None:
747 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
748
749 # get size and write EF.HPLMN
750 r = self._scc.select_file(['6f30'])
751 size = int(r[-1][4:8], 16)
752 hplmn = enc_plmn(p['mcc'], p['mnc'])
753 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
754
755 # set COMP128 version 0 in proprietary file
756 data, sw = self._scc.update_binary('0001', '001000')
757
758 # set Ki in proprietary file
759 data, sw = self._scc.update_binary('0001', p['ki'], 3)
760
761 # select DF_TELECOM
762 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200763
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100764 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200765 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200766 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100767
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100768
Harald Welteca673942020-06-03 15:19:40 +0200769class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100770 """
771 sysmocom sysmoUSIM-SJS1
772 """
773
774 name = 'sysmoUSIM-SJS1'
775
776 def __init__(self, ssc):
777 super(SysmoUSIMSJS1, self).__init__(ssc)
778 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100779 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100780
781 @classmethod
782 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900783 try:
784 # Look for ATR
785 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"):
786 return kls(scc)
787 except:
788 return None
Jan Balke3e840672015-01-26 15:36:27 +0100789 return None
790
791 def program(self, p):
792
Philipp Maiere9604882017-03-21 17:24:31 +0100793 # authenticate as ADM using default key (written on the card..)
794 if not p['pin_adm']:
795 raise ValueError("Please provide a PIN-ADM as there is no default one")
796 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100797
798 # select MF
799 r = self._scc.select_file(['3f00'])
800
Philipp Maiere9604882017-03-21 17:24:31 +0100801 # write EF.ICCID
802 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
803
Jan Balke3e840672015-01-26 15:36:27 +0100804 # select DF_GSM
805 r = self._scc.select_file(['7f20'])
806
Jan Balke3e840672015-01-26 15:36:27 +0100807 # set Ki in proprietary file
808 data, sw = self._scc.update_binary('00FF', p['ki'])
809
Philipp Maier1be35bf2018-07-13 11:29:03 +0200810 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200811 if 'opc' in p:
812 content = "01" + p['opc']
813 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100814
Supreeth Herle7947d922019-06-08 07:50:53 +0200815 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100816 if p.get('name') is not None:
817 content = enc_spn(p['name'], True, True)
818 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200819
Supreeth Herlec8796a32019-12-23 12:23:42 +0100820 if p.get('acc') is not None:
821 self.update_acc(p['acc'])
822
Jan Balke3e840672015-01-26 15:36:27 +0100823 # write EF.IMSI
824 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
825
Philipp Maier2d15ea02019-03-20 12:40:36 +0100826 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200827 if p.get('mcc') and p.get('mnc'):
828 sw = self.update_plmnsel(p['mcc'], p['mnc'])
829 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100830 print("Programming PLMNsel failed with code %s"%sw)
831
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200832 # EF.PLMNwAcT
833 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100834 sw = self.update_plmn_act(p['mcc'], p['mnc'])
835 if sw != '9000':
836 print("Programming PLMNwAcT failed with code %s"%sw)
837
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200838 # EF.OPLMNwAcT
839 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100840 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
841 if sw != '9000':
842 print("Programming OPLMNwAcT failed with code %s"%sw)
843
Supreeth Herlef442fb42020-01-21 12:47:32 +0100844 # EF.HPLMNwAcT
845 if p.get('mcc') and p.get('mnc'):
846 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
847 if sw != '9000':
848 print("Programming HPLMNwAcT failed with code %s"%sw)
849
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200850 # EF.AD
851 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100852 sw = self.update_ad(p['mnc'])
853 if sw != '9000':
854 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100855
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200856 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200857 if p.get('smsp'):
858 r = self._scc.select_file(['3f00', '7f10'])
859 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100860
Supreeth Herle5a541012019-12-22 08:59:16 +0100861 # EF.MSISDN
862 # TODO: Alpha Identifier (currently 'ff'O * 20)
863 # TODO: Capability/Configuration1 Record Identifier
864 # TODO: Extension1 Record Identifier
865 if p.get('msisdn') is not None:
866 msisdn = enc_msisdn(p['msisdn'])
867 data = 'ff' * 20 + msisdn + 'ff' * 2
868
869 r = self._scc.select_file(['3f00', '7f10'])
870 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
871
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900872
herlesupreeth4a3580b2020-09-29 10:11:36 +0200873class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900874 """
875 FairwavesSIM
876
877 The SIM card is operating according to the standard.
878 For Ki/OP/OPC programming the following files are additionally open for writing:
879 3F00/7F20/FF01 – OP/OPC:
880 byte 1 = 0x01, bytes 2-17: OPC;
881 byte 1 = 0x00, bytes 2-17: OP;
882 3F00/7F20/FF02: Ki
883 """
884
Philipp Maier5a876312019-11-11 11:01:46 +0100885 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900886 # Propriatary files
887 _EF_num = {
888 'Ki': 'FF02',
889 'OP/OPC': 'FF01',
890 }
891 _EF = {
892 'Ki': DF['GSM']+[_EF_num['Ki']],
893 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
894 }
895
896 def __init__(self, ssc):
897 super(FairwavesSIM, self).__init__(ssc)
898 self._adm_chv_num = 0x11
899 self._adm2_chv_num = 0x12
900
901
902 @classmethod
903 def autodetect(kls, scc):
904 try:
905 # Look for ATR
906 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"):
907 return kls(scc)
908 except:
909 return None
910 return None
911
912
913 def verify_adm2(self, key):
914 '''
915 Authenticate with ADM2 key.
916
917 Fairwaves SIM cards support hierarchical key structure and ADM2 key
918 is a key which has access to proprietary files (Ki and OP/OPC).
919 That said, ADM key inherits permissions of ADM2 key and thus we rarely
920 need ADM2 key per se.
921 '''
922 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
923 return sw
924
925
926 def read_ki(self):
927 """
928 Read Ki in proprietary file.
929
930 Requires ADM1 access level
931 """
932 return self._scc.read_binary(self._EF['Ki'])
933
934
935 def update_ki(self, ki):
936 """
937 Set Ki in proprietary file.
938
939 Requires ADM1 access level
940 """
941 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
942 return sw
943
944
945 def read_op_opc(self):
946 """
947 Read Ki in proprietary file.
948
949 Requires ADM1 access level
950 """
951 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
952 type = 'OP' if ef[0:2] == '00' else 'OPC'
953 return ((type, ef[2:]), sw)
954
955
956 def update_op(self, op):
957 """
958 Set OP in proprietary file.
959
960 Requires ADM1 access level
961 """
962 content = '00' + op
963 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
964 return sw
965
966
967 def update_opc(self, opc):
968 """
969 Set OPC in proprietary file.
970
971 Requires ADM1 access level
972 """
973 content = '01' + opc
974 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
975 return sw
976
977
978 def program(self, p):
979 # authenticate as ADM1
980 if not p['pin_adm']:
981 raise ValueError("Please provide a PIN-ADM as there is no default one")
982 sw = self.verify_adm(h2b(p['pin_adm']))
983 if sw != '9000':
984 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
985
986 # TODO: Set operator name
987 if p.get('smsp') is not None:
988 sw = self.update_smsp(p['smsp'])
989 if sw != '9000':
990 print("Programming SMSP failed with code %s"%sw)
991 # This SIM doesn't support changing ICCID
992 if p.get('mcc') is not None and p.get('mnc') is not None:
993 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
994 if sw != '9000':
995 print("Programming MCC/MNC failed with code %s"%sw)
996 if p.get('imsi') is not None:
997 sw = self.update_imsi(p['imsi'])
998 if sw != '9000':
999 print("Programming IMSI failed with code %s"%sw)
1000 if p.get('ki') is not None:
1001 sw = self.update_ki(p['ki'])
1002 if sw != '9000':
1003 print("Programming Ki failed with code %s"%sw)
1004 if p.get('opc') is not None:
1005 sw = self.update_opc(p['opc'])
1006 if sw != '9000':
1007 print("Programming OPC failed with code %s"%sw)
1008 if p.get('acc') is not None:
1009 sw = self.update_acc(p['acc'])
1010 if sw != '9000':
1011 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001012
Todd Neal9eeadfc2018-04-25 15:36:29 -05001013class OpenCellsSim(Card):
1014 """
1015 OpenCellsSim
1016
1017 """
1018
Philipp Maier5a876312019-11-11 11:01:46 +01001019 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001020
1021 def __init__(self, ssc):
1022 super(OpenCellsSim, self).__init__(ssc)
1023 self._adm_chv_num = 0x0A
1024
1025
1026 @classmethod
1027 def autodetect(kls, scc):
1028 try:
1029 # Look for ATR
1030 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"):
1031 return kls(scc)
1032 except:
1033 return None
1034 return None
1035
1036
1037 def program(self, p):
1038 if not p['pin_adm']:
1039 raise ValueError("Please provide a PIN-ADM as there is no default one")
1040 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1041
1042 # select MF
1043 r = self._scc.select_file(['3f00'])
1044
1045 # write EF.ICCID
1046 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1047
1048 r = self._scc.select_file(['7ff0'])
1049
1050 # set Ki in proprietary file
1051 data, sw = self._scc.update_binary('FF02', p['ki'])
1052
1053 # set OPC in proprietary file
1054 data, sw = self._scc.update_binary('FF01', p['opc'])
1055
1056 # select DF_GSM
1057 r = self._scc.select_file(['7f20'])
1058
1059 # write EF.IMSI
1060 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1061
herlesupreeth4a3580b2020-09-29 10:11:36 +02001062class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001063 """
1064 WavemobileSim
1065
1066 """
1067
1068 name = 'Wavemobile-SIM'
1069
1070 def __init__(self, ssc):
1071 super(WavemobileSim, self).__init__(ssc)
1072 self._adm_chv_num = 0x0A
1073 self._scc.cla_byte = "00"
1074 self._scc.sel_ctrl = "0004" #request an FCP
1075
1076 @classmethod
1077 def autodetect(kls, scc):
1078 try:
1079 # Look for ATR
1080 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"):
1081 return kls(scc)
1082 except:
1083 return None
1084 return None
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 sw = self.verify_adm(h2b(p['pin_adm']))
1090 if sw != '9000':
1091 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1092
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001093 # EF.ICCID
1094 # TODO: Add programming of the ICCID
1095 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001096 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1097
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001098 # KI (Presumably a propritary file)
1099 # TODO: Add programming of KI
1100 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001101 print("Warning: Programming of the KI is not implemented for this type of card.")
1102
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001103 # OPc (Presumably a propritary file)
1104 # TODO: Add programming of OPc
1105 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001106 print("Warning: Programming of the OPc is not implemented for this type of card.")
1107
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001108 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001109 if p.get('smsp'):
1110 sw = self.update_smsp(p['smsp'])
1111 if sw != '9000':
1112 print("Programming SMSP failed with code %s"%sw)
1113
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001114 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001115 if p.get('imsi'):
1116 sw = self.update_imsi(p['imsi'])
1117 if sw != '9000':
1118 print("Programming IMSI failed with code %s"%sw)
1119
1120 # EF.ACC
1121 if p.get('acc'):
1122 sw = self.update_acc(p['acc'])
1123 if sw != '9000':
1124 print("Programming ACC failed with code %s"%sw)
1125
1126 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001127 if p.get('mcc') and p.get('mnc'):
1128 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1129 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001130 print("Programming PLMNsel failed with code %s"%sw)
1131
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001132 # EF.PLMNwAcT
1133 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001134 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1135 if sw != '9000':
1136 print("Programming PLMNwAcT failed with code %s"%sw)
1137
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001138 # EF.OPLMNwAcT
1139 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001140 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1141 if sw != '9000':
1142 print("Programming OPLMNwAcT failed with code %s"%sw)
1143
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001144 # EF.AD
1145 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001146 sw = self.update_ad(p['mnc'])
1147 if sw != '9000':
1148 print("Programming AD failed with code %s"%sw)
1149
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001150 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001151
Todd Neal9eeadfc2018-04-25 15:36:29 -05001152
herlesupreethb0c7d122020-12-23 09:25:46 +01001153class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001154 """
1155 sysmocom sysmoISIM-SJA2
1156 """
1157
1158 name = 'sysmoISIM-SJA2'
1159
1160 def __init__(self, ssc):
1161 super(SysmoISIMSJA2, self).__init__(ssc)
1162 self._scc.cla_byte = "00"
1163 self._scc.sel_ctrl = "0004" #request an FCP
1164
1165 @classmethod
1166 def autodetect(kls, scc):
1167 try:
1168 # Try card model #1
1169 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1170 if scc.get_atr() == toBytes(atr):
1171 return kls(scc)
1172
1173 # Try card model #2
1174 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1175 if scc.get_atr() == toBytes(atr):
1176 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001177
1178 # Try card model #3
1179 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1180 if scc.get_atr() == toBytes(atr):
1181 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001182 except:
1183 return None
1184 return None
1185
1186 def program(self, p):
1187 # authenticate as ADM using default key (written on the card..)
1188 if not p['pin_adm']:
1189 raise ValueError("Please provide a PIN-ADM as there is no default one")
1190 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1191
1192 # This type of card does not allow to reprogram the ICCID.
1193 # Reprogramming the ICCID would mess up the card os software
1194 # license management, so the ICCID must be kept at its factory
1195 # setting!
1196 if p.get('iccid'):
1197 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1198
1199 # select DF_GSM
1200 self._scc.select_file(['7f20'])
1201
1202 # write EF.IMSI
1203 if p.get('imsi'):
1204 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1205
1206 # EF.PLMNsel
1207 if p.get('mcc') and p.get('mnc'):
1208 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1209 if sw != '9000':
1210 print("Programming PLMNsel failed with code %s"%sw)
1211
1212 # EF.PLMNwAcT
1213 if p.get('mcc') and p.get('mnc'):
1214 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1215 if sw != '9000':
1216 print("Programming PLMNwAcT failed with code %s"%sw)
1217
1218 # EF.OPLMNwAcT
1219 if p.get('mcc') and p.get('mnc'):
1220 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1221 if sw != '9000':
1222 print("Programming OPLMNwAcT failed with code %s"%sw)
1223
Harald Welte32f0d412020-05-05 17:35:57 +02001224 # EF.HPLMNwAcT
1225 if p.get('mcc') and p.get('mnc'):
1226 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1227 if sw != '9000':
1228 print("Programming HPLMNwAcT failed with code %s"%sw)
1229
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001230 # EF.AD
1231 if p.get('mcc') and p.get('mnc'):
1232 sw = self.update_ad(p['mnc'])
1233 if sw != '9000':
1234 print("Programming AD failed with code %s"%sw)
1235
1236 # EF.SMSP
1237 if p.get('smsp'):
1238 r = self._scc.select_file(['3f00', '7f10'])
1239 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1240
Supreeth Herle80164052020-03-23 12:06:29 +01001241 # Populate AIDs
1242 self.read_aids()
1243
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001244 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1245 # hard linked to EF-USIM_AUTH_KEY)
1246 self._scc.select_file(['3f00'])
1247 self._scc.select_file(['a515'])
1248 if p.get('ki'):
1249 self._scc.update_binary('6f20', p['ki'], 1)
1250 if p.get('opc'):
1251 self._scc.update_binary('6f20', p['opc'], 17)
1252
1253 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001254 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001255 if p.get('ki'):
1256 self._scc.update_binary('af20', p['ki'], 1)
1257 if p.get('opc'):
1258 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001259
Supreeth Herlecf727f22020-03-24 17:32:21 +01001260 # update EF.P-CSCF in ADF.ISIM
1261 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1262 if p.get('pcscf'):
1263 sw = self.update_pcscf(p['pcscf'])
1264 else:
1265 sw = self.update_pcscf("")
1266 if sw != '9000':
1267 print("Programming P-CSCF failed with code %s"%sw)
1268
1269
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001270 # update EF.DOMAIN in ADF.ISIM
1271 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1272 if p.get('ims_hdomain'):
1273 sw = self.update_domain(domain=p['ims_hdomain'])
1274 else:
1275 sw = self.update_domain()
1276
1277 if sw != '9000':
1278 print("Programming Home Network Domain Name failed with code %s"%sw)
1279
herlesupreeth1a13c442020-09-11 21:16:51 +02001280 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001281 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001282 if p.get('ki'):
1283 self._scc.update_binary('af20', p['ki'], 1)
1284 if p.get('opc'):
1285 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001286
Harald Welteca673942020-06-03 15:19:40 +02001287 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001288 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001289 if p.get('mcc') and p.get('mnc'):
1290 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1291 if sw != '9000':
1292 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001293
1294 # update EF.ePDGId in ADF.USIM
1295 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1296 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001297 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001298 else:
1299 sw = self.update_epdgid("")
1300 if sw != '9000':
1301 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001302
Supreeth Herlef964df42020-03-24 13:15:37 +01001303 # update EF.ePDGSelection in ADF.USIM
1304 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1305 if p.get('epdgSelection'):
1306 epdg_plmn = p['epdgSelection']
1307 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1308 else:
1309 sw = self.update_ePDGSelection("", "")
1310 if sw != '9000':
1311 print("Programming ePDGSelection failed with code %s"%sw)
1312
1313
Supreeth Herleacc222f2020-03-24 13:26:53 +01001314 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1315 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001316 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001317 if self.file_exists(EF_USIM_ADF_map['UST']):
1318 if p.get('epdgSelection') and p.get('epdgid'):
1319 sw = self.update_ust(106, 1)
1320 if sw != '9000':
1321 print("Programming UST failed with code %s"%sw)
1322 sw = self.update_ust(107, 1)
1323 if sw != '9000':
1324 print("Programming UST failed with code %s"%sw)
1325
Supreeth Herle44e04622020-03-25 10:34:28 +01001326 sw = self.update_ust(95, 0)
1327 if sw != '9000':
1328 print("Programming UST failed with code %s"%sw)
1329 sw = self.update_ust(99, 0)
1330 if sw != '9000':
1331 print("Programming UST failed with code %s"%sw)
1332 sw = self.update_ust(115, 0)
1333 if sw != '9000':
1334 print("Programming UST failed with code %s"%sw)
1335
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001336 return
1337
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001338
Todd Neal9eeadfc2018-04-25 15:36:29 -05001339# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001340_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001341 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001342 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001343
1344def card_autodetect(scc):
1345 for kls in _cards_classes:
1346 card = kls.autodetect(scc)
1347 if card is not None:
1348 card.reset()
1349 return card
1350 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001351
1352def card_detect(ctype, scc):
1353 # Detect type if needed
1354 card = None
1355 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1356
1357 if ctype in ("auto", "auto_once"):
1358 for kls in _cards_classes:
1359 card = kls.autodetect(scc)
1360 if card:
1361 print("Autodetected card type: %s" % card.name)
1362 card.reset()
1363 break
1364
1365 if card is None:
1366 print("Autodetection failed")
1367 return None
1368
1369 if ctype == "auto_once":
1370 ctype = card.name
1371
1372 elif ctype in ctypes:
1373 card = ctypes[ctype](scc)
1374
1375 else:
1376 raise ValueError("Unknown card type: %s" % ctype)
1377
1378 return card