blob: b7be6e885fcf67dd7f5dab34b92b57d70ea9e1e2 [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:
339 content = enc_addr_tlv(pcscf)
340 else:
341 # Just the tag value
342 content = '80'
343 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
344 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, rpad(content, rec_size_bytes*2))
345 return sw
346
Supreeth Herle05b28072020-03-25 10:23:48 +0100347 def read_domain(self):
348 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
349 if sw == '9000':
350 # Skip the inital tag value ('80') byte and get length of contents
351 length = int(res[2:4], 16)
352 content = h2s(res[4:4+(length*2)])
353 return (content, sw)
354 else:
355 return (None, sw)
356
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100357 def update_domain(self, domain=None, mcc=None, mnc=None):
358 hex_str = ""
359 if domain:
360 hex_str = s2h(domain)
361 elif mcc and mnc:
362 # MCC and MNC always has 3 digits in domain form
363 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
364 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
365
366 # Build TLV
367 tlv = TLV(['80'])
368 content = tlv.build({'80': hex_str})
369
370 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
371 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
372 return sw
373
Sylvain Munaut76504e02010-12-07 00:24:32 +0100374
375class _MagicSimBase(Card):
376 """
377 Theses cards uses several record based EFs to store the provider infos,
378 each possible provider uses a specific record number in each EF. The
379 indexes used are ( where N is the number of providers supported ) :
380 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100381 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100382
383 * 3f00/7f4d/8f0c : Operator Name
384
385 bytes 0-15 : provider name, padded with 0xff
386 byte 16 : length of the provider name
387 byte 17 : 01 for valid records, 00 otherwise
388
389 * 3f00/7f4d/8f0d : Programmable Binary EFs
390
391 * 3f00/7f4d/8f0e : Programmable Record EFs
392
393 """
394
395 @classmethod
396 def autodetect(kls, scc):
397 try:
398 for p, l, t in kls._files.values():
399 if not t:
400 continue
401 if scc.record_size(['3f00', '7f4d', p]) != l:
402 return None
403 except:
404 return None
405
406 return kls(scc)
407
408 def _get_count(self):
409 """
410 Selects the file and returns the total number of entries
411 and entry size
412 """
413 f = self._files['name']
414
415 r = self._scc.select_file(['3f00', '7f4d', f[0]])
416 rec_len = int(r[-1][28:30], 16)
417 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200418 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100419
420 if (rec_cnt < 1) or (rec_len != f[1]):
421 raise RuntimeError('Bad card type')
422
423 return rec_cnt
424
425 def program(self, p):
426 # Go to dir
427 self._scc.select_file(['3f00', '7f4d'])
428
429 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400430 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100431
432 # Operator name ( 3f00/7f4d/8f0c )
433 self._scc.update_record(self._files['name'][0], 2,
434 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
435 )
436
437 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
438 v = ''
439
440 # inline Ki
441 if self._ki_file is None:
442 v += p['ki']
443
444 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400445 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100446
447 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400448 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100449
450 # Ki
451 if self._ki_file:
452 v += self._ki_file + '10' + p['ki']
453
454 # PLMN_Sel
455 v+= '6f30' + '18' + rpad(hplmn, 36)
456
Alexander Chemeris21885242013-07-02 16:56:55 +0400457 # ACC
458 # This doesn't work with "fake" SuperSIM cards,
459 # but will hopefully work with real SuperSIMs.
460 if p.get('acc') is not None:
461 v+= '6f78' + '02' + lpad(p['acc'], 4)
462
Sylvain Munaut76504e02010-12-07 00:24:32 +0100463 self._scc.update_record(self._files['b_ef'][0], 1,
464 rpad(v, self._files['b_ef'][1]*2)
465 )
466
467 # SMSP ( 3f00/7f4d/8f0e )
468 # FIXME
469
470 # Write PLMN_Sel forcefully as well
471 r = self._scc.select_file(['3f00', '7f20', '6f30'])
472 tl = int(r[-1][4:8], 16)
473
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400474 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100475 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
476
477 def erase(self):
478 # Dummy
479 df = {}
480 for k, v in self._files.iteritems():
481 ofs = 1
482 fv = v[1] * 'ff'
483 if k == 'name':
484 ofs = 2
485 fv = fv[0:-4] + '0000'
486 df[v[0]] = (fv, ofs)
487
488 # Write
489 for n in range(0,self._get_count()):
490 for k, (msg, ofs) in df.iteritems():
491 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
492
493
494class SuperSim(_MagicSimBase):
495
496 name = 'supersim'
497
498 _files = {
499 'name' : ('8f0c', 18, True),
500 'b_ef' : ('8f0d', 74, True),
501 'r_ef' : ('8f0e', 50, True),
502 }
503
504 _ki_file = None
505
506
507class MagicSim(_MagicSimBase):
508
509 name = 'magicsim'
510
511 _files = {
512 'name' : ('8f0c', 18, True),
513 'b_ef' : ('8f0d', 130, True),
514 'r_ef' : ('8f0e', 102, False),
515 }
516
517 _ki_file = '6f1b'
518
519
520class FakeMagicSim(Card):
521 """
522 Theses cards have a record based EF 3f00/000c that contains the provider
523 informations. See the program method for its format. The records go from
524 1 to N.
525 """
526
527 name = 'fakemagicsim'
528
529 @classmethod
530 def autodetect(kls, scc):
531 try:
532 if scc.record_size(['3f00', '000c']) != 0x5a:
533 return None
534 except:
535 return None
536
537 return kls(scc)
538
539 def _get_infos(self):
540 """
541 Selects the file and returns the total number of entries
542 and entry size
543 """
544
545 r = self._scc.select_file(['3f00', '000c'])
546 rec_len = int(r[-1][28:30], 16)
547 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200548 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100549
550 if (rec_cnt < 1) or (rec_len != 0x5a):
551 raise RuntimeError('Bad card type')
552
553 return rec_cnt, rec_len
554
555 def program(self, p):
556 # Home PLMN
557 r = self._scc.select_file(['3f00', '7f20', '6f30'])
558 tl = int(r[-1][4:8], 16)
559
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400560 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100561 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
562
563 # Get total number of entries and entry size
564 rec_cnt, rec_len = self._get_infos()
565
566 # Set first entry
567 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200568 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100569 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200570 enc_iccid(p['iccid']) + # 10b ICCID
571 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
572 p['ki'] + # 16b Ki
573 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100574 )
575 self._scc.update_record('000c', 1, entry)
576
577 def erase(self):
578 # Get total number of entries and entry size
579 rec_cnt, rec_len = self._get_infos()
580
581 # Erase all entries
582 entry = 'ff' * rec_len
583 for i in range(0, rec_cnt):
584 self._scc.update_record('000c', 1+i, entry)
585
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200586
Harald Welte3156d902011-03-22 21:48:19 +0100587class GrcardSim(Card):
588 """
589 Greencard (grcard.cn) HZCOS GSM SIM
590 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
591 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
592 """
593
594 name = 'grcardsim'
595
596 @classmethod
597 def autodetect(kls, scc):
598 return None
599
600 def program(self, p):
601 # We don't really know yet what ADM PIN 4 is about
602 #self._scc.verify_chv(4, h2b("4444444444444444"))
603
604 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100605 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200606 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100607 else:
608 pin = h2b("4444444444444444")
609 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100610
611 # EF.ICCID
612 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400613 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100614
615 # EF.IMSI
616 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400617 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100618
619 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400620 if p.get('acc') is not None:
621 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100622
623 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200624 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200625 r = self._scc.select_file(['3f00', '7f10', '6f42'])
626 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100627
628 # Set the Ki using proprietary command
629 pdu = '80d4020010' + p['ki']
630 data, sw = self._scc._tp.send_apdu(pdu)
631
632 # EF.HPLMN
633 r = self._scc.select_file(['3f00', '7f20', '6f30'])
634 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400635 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100636 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
637
638 # EF.SPN (Service Provider Name)
639 r = self._scc.select_file(['3f00', '7f20', '6f30'])
640 size = int(r[-1][4:8], 16)
641 # FIXME
642
643 # FIXME: EF.MSISDN
644
Sylvain Munaut76504e02010-12-07 00:24:32 +0100645
Harald Weltee10394b2011-12-07 12:34:14 +0100646class SysmoSIMgr1(GrcardSim):
647 """
648 sysmocom sysmoSIM-GR1
649 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
650 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
651 """
652 name = 'sysmosim-gr1'
653
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200654 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200655 def autodetect(kls, scc):
656 try:
657 # Look for ATR
658 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
659 return kls(scc)
660 except:
661 return None
662 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200663
Harald Welteca673942020-06-03 15:19:40 +0200664class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100665 """
666 sysmocom sysmoUSIM-GR1
667 """
668 name = 'sysmoUSIM-GR1'
669
670 @classmethod
671 def autodetect(kls, scc):
672 # TODO: Access the ATR
673 return None
674
675 def program(self, p):
676 # TODO: check if verify_chv could be used or what it needs
677 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
678 # Unlock the card..
679 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
680
681 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100682 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400683 p['opc'] + # 32b OPC
684 enc_iccid(p['iccid']) + # 10b ICCID
685 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100686 )
687 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
688
Sylvain Munaut053c8952013-07-02 15:12:32 +0200689
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100690class SysmoSIMgr2(Card):
691 """
692 sysmocom sysmoSIM-GR2
693 """
694
695 name = 'sysmoSIM-GR2'
696
697 @classmethod
698 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900699 try:
700 # Look for ATR
701 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
702 return kls(scc)
703 except:
704 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100705 return None
706
707 def program(self, p):
708
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200709 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100710 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200711
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100712 # authenticate as SUPER ADM using default key
713 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
714
715 # set ADM pin using proprietary command
716 # INS: D4
717 # P1: 3A for PIN, 3B for PUK
718 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
719 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100720 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200721 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100722 else:
723 pin = h2b("4444444444444444")
724
725 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100726 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200727
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100728 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100729
730 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100731
732 # write EF.ICCID
733 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
734
735 # select DF_GSM
736 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200737
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100738 # write EF.IMSI
739 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
740
741 # write EF.ACC
742 if p.get('acc') is not None:
743 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
744
745 # get size and write EF.HPLMN
746 r = self._scc.select_file(['6f30'])
747 size = int(r[-1][4:8], 16)
748 hplmn = enc_plmn(p['mcc'], p['mnc'])
749 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
750
751 # set COMP128 version 0 in proprietary file
752 data, sw = self._scc.update_binary('0001', '001000')
753
754 # set Ki in proprietary file
755 data, sw = self._scc.update_binary('0001', p['ki'], 3)
756
757 # select DF_TELECOM
758 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200759
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100760 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200761 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200762 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100763
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100764
Harald Welteca673942020-06-03 15:19:40 +0200765class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100766 """
767 sysmocom sysmoUSIM-SJS1
768 """
769
770 name = 'sysmoUSIM-SJS1'
771
772 def __init__(self, ssc):
773 super(SysmoUSIMSJS1, self).__init__(ssc)
774 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100775 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100776
777 @classmethod
778 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900779 try:
780 # Look for ATR
781 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"):
782 return kls(scc)
783 except:
784 return None
Jan Balke3e840672015-01-26 15:36:27 +0100785 return None
786
787 def program(self, p):
788
Philipp Maiere9604882017-03-21 17:24:31 +0100789 # authenticate as ADM using default key (written on the card..)
790 if not p['pin_adm']:
791 raise ValueError("Please provide a PIN-ADM as there is no default one")
792 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100793
794 # select MF
795 r = self._scc.select_file(['3f00'])
796
Philipp Maiere9604882017-03-21 17:24:31 +0100797 # write EF.ICCID
798 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
799
Jan Balke3e840672015-01-26 15:36:27 +0100800 # select DF_GSM
801 r = self._scc.select_file(['7f20'])
802
Jan Balke3e840672015-01-26 15:36:27 +0100803 # set Ki in proprietary file
804 data, sw = self._scc.update_binary('00FF', p['ki'])
805
Philipp Maier1be35bf2018-07-13 11:29:03 +0200806 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200807 if 'opc' in p:
808 content = "01" + p['opc']
809 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100810
Supreeth Herle7947d922019-06-08 07:50:53 +0200811 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100812 if p.get('name') is not None:
813 content = enc_spn(p['name'], True, True)
814 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200815
Supreeth Herlec8796a32019-12-23 12:23:42 +0100816 if p.get('acc') is not None:
817 self.update_acc(p['acc'])
818
Jan Balke3e840672015-01-26 15:36:27 +0100819 # write EF.IMSI
820 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
821
Philipp Maier2d15ea02019-03-20 12:40:36 +0100822 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200823 if p.get('mcc') and p.get('mnc'):
824 sw = self.update_plmnsel(p['mcc'], p['mnc'])
825 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100826 print("Programming PLMNsel failed with code %s"%sw)
827
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200828 # EF.PLMNwAcT
829 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100830 sw = self.update_plmn_act(p['mcc'], p['mnc'])
831 if sw != '9000':
832 print("Programming PLMNwAcT failed with code %s"%sw)
833
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200834 # EF.OPLMNwAcT
835 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100836 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
837 if sw != '9000':
838 print("Programming OPLMNwAcT failed with code %s"%sw)
839
Supreeth Herlef442fb42020-01-21 12:47:32 +0100840 # EF.HPLMNwAcT
841 if p.get('mcc') and p.get('mnc'):
842 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
843 if sw != '9000':
844 print("Programming HPLMNwAcT failed with code %s"%sw)
845
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200846 # EF.AD
847 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100848 sw = self.update_ad(p['mnc'])
849 if sw != '9000':
850 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100851
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200852 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200853 if p.get('smsp'):
854 r = self._scc.select_file(['3f00', '7f10'])
855 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100856
Supreeth Herle5a541012019-12-22 08:59:16 +0100857 # EF.MSISDN
858 # TODO: Alpha Identifier (currently 'ff'O * 20)
859 # TODO: Capability/Configuration1 Record Identifier
860 # TODO: Extension1 Record Identifier
861 if p.get('msisdn') is not None:
862 msisdn = enc_msisdn(p['msisdn'])
863 data = 'ff' * 20 + msisdn + 'ff' * 2
864
865 r = self._scc.select_file(['3f00', '7f10'])
866 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
867
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900868
herlesupreeth4a3580b2020-09-29 10:11:36 +0200869class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900870 """
871 FairwavesSIM
872
873 The SIM card is operating according to the standard.
874 For Ki/OP/OPC programming the following files are additionally open for writing:
875 3F00/7F20/FF01 – OP/OPC:
876 byte 1 = 0x01, bytes 2-17: OPC;
877 byte 1 = 0x00, bytes 2-17: OP;
878 3F00/7F20/FF02: Ki
879 """
880
Philipp Maier5a876312019-11-11 11:01:46 +0100881 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900882 # Propriatary files
883 _EF_num = {
884 'Ki': 'FF02',
885 'OP/OPC': 'FF01',
886 }
887 _EF = {
888 'Ki': DF['GSM']+[_EF_num['Ki']],
889 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
890 }
891
892 def __init__(self, ssc):
893 super(FairwavesSIM, self).__init__(ssc)
894 self._adm_chv_num = 0x11
895 self._adm2_chv_num = 0x12
896
897
898 @classmethod
899 def autodetect(kls, scc):
900 try:
901 # Look for ATR
902 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"):
903 return kls(scc)
904 except:
905 return None
906 return None
907
908
909 def verify_adm2(self, key):
910 '''
911 Authenticate with ADM2 key.
912
913 Fairwaves SIM cards support hierarchical key structure and ADM2 key
914 is a key which has access to proprietary files (Ki and OP/OPC).
915 That said, ADM key inherits permissions of ADM2 key and thus we rarely
916 need ADM2 key per se.
917 '''
918 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
919 return sw
920
921
922 def read_ki(self):
923 """
924 Read Ki in proprietary file.
925
926 Requires ADM1 access level
927 """
928 return self._scc.read_binary(self._EF['Ki'])
929
930
931 def update_ki(self, ki):
932 """
933 Set Ki in proprietary file.
934
935 Requires ADM1 access level
936 """
937 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
938 return sw
939
940
941 def read_op_opc(self):
942 """
943 Read Ki in proprietary file.
944
945 Requires ADM1 access level
946 """
947 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
948 type = 'OP' if ef[0:2] == '00' else 'OPC'
949 return ((type, ef[2:]), sw)
950
951
952 def update_op(self, op):
953 """
954 Set OP in proprietary file.
955
956 Requires ADM1 access level
957 """
958 content = '00' + op
959 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
960 return sw
961
962
963 def update_opc(self, opc):
964 """
965 Set OPC in proprietary file.
966
967 Requires ADM1 access level
968 """
969 content = '01' + opc
970 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
971 return sw
972
973
974 def program(self, p):
975 # authenticate as ADM1
976 if not p['pin_adm']:
977 raise ValueError("Please provide a PIN-ADM as there is no default one")
978 sw = self.verify_adm(h2b(p['pin_adm']))
979 if sw != '9000':
980 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
981
982 # TODO: Set operator name
983 if p.get('smsp') is not None:
984 sw = self.update_smsp(p['smsp'])
985 if sw != '9000':
986 print("Programming SMSP failed with code %s"%sw)
987 # This SIM doesn't support changing ICCID
988 if p.get('mcc') is not None and p.get('mnc') is not None:
989 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
990 if sw != '9000':
991 print("Programming MCC/MNC failed with code %s"%sw)
992 if p.get('imsi') is not None:
993 sw = self.update_imsi(p['imsi'])
994 if sw != '9000':
995 print("Programming IMSI failed with code %s"%sw)
996 if p.get('ki') is not None:
997 sw = self.update_ki(p['ki'])
998 if sw != '9000':
999 print("Programming Ki failed with code %s"%sw)
1000 if p.get('opc') is not None:
1001 sw = self.update_opc(p['opc'])
1002 if sw != '9000':
1003 print("Programming OPC failed with code %s"%sw)
1004 if p.get('acc') is not None:
1005 sw = self.update_acc(p['acc'])
1006 if sw != '9000':
1007 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001008
Todd Neal9eeadfc2018-04-25 15:36:29 -05001009class OpenCellsSim(Card):
1010 """
1011 OpenCellsSim
1012
1013 """
1014
Philipp Maier5a876312019-11-11 11:01:46 +01001015 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001016
1017 def __init__(self, ssc):
1018 super(OpenCellsSim, self).__init__(ssc)
1019 self._adm_chv_num = 0x0A
1020
1021
1022 @classmethod
1023 def autodetect(kls, scc):
1024 try:
1025 # Look for ATR
1026 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"):
1027 return kls(scc)
1028 except:
1029 return None
1030 return None
1031
1032
1033 def program(self, p):
1034 if not p['pin_adm']:
1035 raise ValueError("Please provide a PIN-ADM as there is no default one")
1036 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1037
1038 # select MF
1039 r = self._scc.select_file(['3f00'])
1040
1041 # write EF.ICCID
1042 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1043
1044 r = self._scc.select_file(['7ff0'])
1045
1046 # set Ki in proprietary file
1047 data, sw = self._scc.update_binary('FF02', p['ki'])
1048
1049 # set OPC in proprietary file
1050 data, sw = self._scc.update_binary('FF01', p['opc'])
1051
1052 # select DF_GSM
1053 r = self._scc.select_file(['7f20'])
1054
1055 # write EF.IMSI
1056 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1057
herlesupreeth4a3580b2020-09-29 10:11:36 +02001058class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001059 """
1060 WavemobileSim
1061
1062 """
1063
1064 name = 'Wavemobile-SIM'
1065
1066 def __init__(self, ssc):
1067 super(WavemobileSim, self).__init__(ssc)
1068 self._adm_chv_num = 0x0A
1069 self._scc.cla_byte = "00"
1070 self._scc.sel_ctrl = "0004" #request an FCP
1071
1072 @classmethod
1073 def autodetect(kls, scc):
1074 try:
1075 # Look for ATR
1076 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"):
1077 return kls(scc)
1078 except:
1079 return None
1080 return None
1081
1082 def program(self, p):
1083 if not p['pin_adm']:
1084 raise ValueError("Please provide a PIN-ADM as there is no default one")
1085 sw = self.verify_adm(h2b(p['pin_adm']))
1086 if sw != '9000':
1087 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1088
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001089 # EF.ICCID
1090 # TODO: Add programming of the ICCID
1091 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001092 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1093
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001094 # KI (Presumably a propritary file)
1095 # TODO: Add programming of KI
1096 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001097 print("Warning: Programming of the KI is not implemented for this type of card.")
1098
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001099 # OPc (Presumably a propritary file)
1100 # TODO: Add programming of OPc
1101 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001102 print("Warning: Programming of the OPc is not implemented for this type of card.")
1103
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001104 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001105 if p.get('smsp'):
1106 sw = self.update_smsp(p['smsp'])
1107 if sw != '9000':
1108 print("Programming SMSP failed with code %s"%sw)
1109
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001110 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001111 if p.get('imsi'):
1112 sw = self.update_imsi(p['imsi'])
1113 if sw != '9000':
1114 print("Programming IMSI failed with code %s"%sw)
1115
1116 # EF.ACC
1117 if p.get('acc'):
1118 sw = self.update_acc(p['acc'])
1119 if sw != '9000':
1120 print("Programming ACC failed with code %s"%sw)
1121
1122 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001123 if p.get('mcc') and p.get('mnc'):
1124 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1125 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001126 print("Programming PLMNsel failed with code %s"%sw)
1127
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001128 # EF.PLMNwAcT
1129 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001130 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1131 if sw != '9000':
1132 print("Programming PLMNwAcT failed with code %s"%sw)
1133
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001134 # EF.OPLMNwAcT
1135 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001136 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1137 if sw != '9000':
1138 print("Programming OPLMNwAcT failed with code %s"%sw)
1139
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001140 # EF.AD
1141 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001142 sw = self.update_ad(p['mnc'])
1143 if sw != '9000':
1144 print("Programming AD failed with code %s"%sw)
1145
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001146 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001147
Todd Neal9eeadfc2018-04-25 15:36:29 -05001148
herlesupreethb0c7d122020-12-23 09:25:46 +01001149class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001150 """
1151 sysmocom sysmoISIM-SJA2
1152 """
1153
1154 name = 'sysmoISIM-SJA2'
1155
1156 def __init__(self, ssc):
1157 super(SysmoISIMSJA2, self).__init__(ssc)
1158 self._scc.cla_byte = "00"
1159 self._scc.sel_ctrl = "0004" #request an FCP
1160
1161 @classmethod
1162 def autodetect(kls, scc):
1163 try:
1164 # Try card model #1
1165 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1166 if scc.get_atr() == toBytes(atr):
1167 return kls(scc)
1168
1169 # Try card model #2
1170 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1171 if scc.get_atr() == toBytes(atr):
1172 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001173
1174 # Try card model #3
1175 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1176 if scc.get_atr() == toBytes(atr):
1177 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001178 except:
1179 return None
1180 return None
1181
1182 def program(self, p):
1183 # authenticate as ADM using default key (written on the card..)
1184 if not p['pin_adm']:
1185 raise ValueError("Please provide a PIN-ADM as there is no default one")
1186 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1187
1188 # This type of card does not allow to reprogram the ICCID.
1189 # Reprogramming the ICCID would mess up the card os software
1190 # license management, so the ICCID must be kept at its factory
1191 # setting!
1192 if p.get('iccid'):
1193 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1194
1195 # select DF_GSM
1196 self._scc.select_file(['7f20'])
1197
1198 # write EF.IMSI
1199 if p.get('imsi'):
1200 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1201
1202 # EF.PLMNsel
1203 if p.get('mcc') and p.get('mnc'):
1204 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1205 if sw != '9000':
1206 print("Programming PLMNsel failed with code %s"%sw)
1207
1208 # EF.PLMNwAcT
1209 if p.get('mcc') and p.get('mnc'):
1210 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1211 if sw != '9000':
1212 print("Programming PLMNwAcT failed with code %s"%sw)
1213
1214 # EF.OPLMNwAcT
1215 if p.get('mcc') and p.get('mnc'):
1216 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1217 if sw != '9000':
1218 print("Programming OPLMNwAcT failed with code %s"%sw)
1219
Harald Welte32f0d412020-05-05 17:35:57 +02001220 # EF.HPLMNwAcT
1221 if p.get('mcc') and p.get('mnc'):
1222 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1223 if sw != '9000':
1224 print("Programming HPLMNwAcT failed with code %s"%sw)
1225
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001226 # EF.AD
1227 if p.get('mcc') and p.get('mnc'):
1228 sw = self.update_ad(p['mnc'])
1229 if sw != '9000':
1230 print("Programming AD failed with code %s"%sw)
1231
1232 # EF.SMSP
1233 if p.get('smsp'):
1234 r = self._scc.select_file(['3f00', '7f10'])
1235 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1236
Supreeth Herle80164052020-03-23 12:06:29 +01001237 # Populate AIDs
1238 self.read_aids()
1239
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001240 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1241 # hard linked to EF-USIM_AUTH_KEY)
1242 self._scc.select_file(['3f00'])
1243 self._scc.select_file(['a515'])
1244 if p.get('ki'):
1245 self._scc.update_binary('6f20', p['ki'], 1)
1246 if p.get('opc'):
1247 self._scc.update_binary('6f20', p['opc'], 17)
1248
1249 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001250 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001251 if p.get('ki'):
1252 self._scc.update_binary('af20', p['ki'], 1)
1253 if p.get('opc'):
1254 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001255
Supreeth Herlecf727f22020-03-24 17:32:21 +01001256 # update EF.P-CSCF in ADF.ISIM
1257 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1258 if p.get('pcscf'):
1259 sw = self.update_pcscf(p['pcscf'])
1260 else:
1261 sw = self.update_pcscf("")
1262 if sw != '9000':
1263 print("Programming P-CSCF failed with code %s"%sw)
1264
1265
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001266 # update EF.DOMAIN in ADF.ISIM
1267 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1268 if p.get('ims_hdomain'):
1269 sw = self.update_domain(domain=p['ims_hdomain'])
1270 else:
1271 sw = self.update_domain()
1272
1273 if sw != '9000':
1274 print("Programming Home Network Domain Name failed with code %s"%sw)
1275
herlesupreeth1a13c442020-09-11 21:16:51 +02001276 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001277 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001278 if p.get('ki'):
1279 self._scc.update_binary('af20', p['ki'], 1)
1280 if p.get('opc'):
1281 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001282
Harald Welteca673942020-06-03 15:19:40 +02001283 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001284 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001285 if p.get('mcc') and p.get('mnc'):
1286 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1287 if sw != '9000':
1288 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001289
1290 # update EF.ePDGId in ADF.USIM
1291 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1292 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001293 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001294 else:
1295 sw = self.update_epdgid("")
1296 if sw != '9000':
1297 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001298
Supreeth Herlef964df42020-03-24 13:15:37 +01001299 # update EF.ePDGSelection in ADF.USIM
1300 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1301 if p.get('epdgSelection'):
1302 epdg_plmn = p['epdgSelection']
1303 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1304 else:
1305 sw = self.update_ePDGSelection("", "")
1306 if sw != '9000':
1307 print("Programming ePDGSelection failed with code %s"%sw)
1308
1309
Supreeth Herleacc222f2020-03-24 13:26:53 +01001310 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1311 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001312 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001313 if self.file_exists(EF_USIM_ADF_map['UST']):
1314 if p.get('epdgSelection') and p.get('epdgid'):
1315 sw = self.update_ust(106, 1)
1316 if sw != '9000':
1317 print("Programming UST failed with code %s"%sw)
1318 sw = self.update_ust(107, 1)
1319 if sw != '9000':
1320 print("Programming UST failed with code %s"%sw)
1321
Supreeth Herle44e04622020-03-25 10:34:28 +01001322 sw = self.update_ust(95, 0)
1323 if sw != '9000':
1324 print("Programming UST failed with code %s"%sw)
1325 sw = self.update_ust(99, 0)
1326 if sw != '9000':
1327 print("Programming UST failed with code %s"%sw)
1328 sw = self.update_ust(115, 0)
1329 if sw != '9000':
1330 print("Programming UST failed with code %s"%sw)
1331
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001332 return
1333
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001334
Todd Neal9eeadfc2018-04-25 15:36:29 -05001335# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001336_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001337 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001338 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001339
1340def card_autodetect(scc):
1341 for kls in _cards_classes:
1342 card = kls.autodetect(scc)
1343 if card is not None:
1344 card.reset()
1345 return card
1346 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001347
1348def card_detect(ctype, scc):
1349 # Detect type if needed
1350 card = None
1351 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1352
1353 if ctype in ("auto", "auto_once"):
1354 for kls in _cards_classes:
1355 card = kls.autodetect(scc)
1356 if card:
1357 print("Autodetected card type: %s" % card.name)
1358 card.reset()
1359 break
1360
1361 if card is None:
1362 print("Autodetection failed")
1363 return None
1364
1365 if ctype == "auto_once":
1366 ctype = card.name
1367
1368 elif ctype in ctypes:
1369 card = ctypes[ctype](scc)
1370
1371 else:
1372 raise ValueError("Unknown card type: %s" % ctype)
1373
1374 return card