blob: 498c34e82b56235e234db6a43b3ea1a682daf475 [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
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030028from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090029from smartcard.util import toBytes
Sylvain Munaut76504e02010-12-07 00:24:32 +010030
31class Card(object):
32
33 def __init__(self, scc):
34 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030035 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010036 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010037
Sylvain Munaut76504e02010-12-07 00:24:32 +010038 def reset(self):
39 self._scc.reset_card()
40
Philipp Maierd58c6322020-05-12 16:47:45 +020041 def erase(self):
42 print("warning: erasing is not supported for specified card type!")
43 return
44
Harald Welteca673942020-06-03 15:19:40 +020045 def file_exists(self, fid):
46 res_arr = self._scc.try_select_file(fid)
47 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020048 if res[1] != '9000':
49 return False
Harald Welteca673942020-06-03 15:19:40 +020050 return True
51
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030052 def verify_adm(self, key):
53 '''
54 Authenticate with ADM key
55 '''
56 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
57 return sw
58
59 def read_iccid(self):
60 (res, sw) = self._scc.read_binary(EF['ICCID'])
61 if sw == '9000':
62 return (dec_iccid(res), sw)
63 else:
64 return (None, sw)
65
66 def read_imsi(self):
67 (res, sw) = self._scc.read_binary(EF['IMSI'])
68 if sw == '9000':
69 return (dec_imsi(res), sw)
70 else:
71 return (None, sw)
72
73 def update_imsi(self, imsi):
74 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
75 return sw
76
77 def update_acc(self, acc):
78 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
79 return sw
80
Supreeth Herlea850a472020-03-19 12:44:11 +010081 def read_hplmn_act(self):
82 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
83 if sw == '9000':
84 return (format_xplmn_w_act(res), sw)
85 else:
86 return (None, sw)
87
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030088 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
89 """
90 Update Home PLMN with access technology bit-field
91
92 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
93 in ETSI TS 151 011 for the details of the access_tech field coding.
94 Some common values:
95 access_tech = '0080' # Only GSM is selected
96 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
97 """
98 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +010099 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700100 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300101 hplmn = enc_plmn(mcc, mnc)
102 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700103 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300104 return sw
105
Supreeth Herle1757b262020-03-19 12:43:11 +0100106 def read_oplmn_act(self):
107 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
108 if sw == '9000':
109 return (format_xplmn_w_act(res), sw)
110 else:
111 return (None, sw)
112
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200113 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
114 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200115 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200116 """
117 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200118 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700119 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200120 hplmn = enc_plmn(mcc, mnc)
121 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700122 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200123 return sw
124
Supreeth Herle14084402020-03-19 12:42:10 +0100125 def read_plmn_act(self):
126 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
127 if sw == '9000':
128 return (format_xplmn_w_act(res), sw)
129 else:
130 return (None, sw)
131
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200132 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
133 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200134 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200135 """
136 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200137 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700138 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200139 hplmn = enc_plmn(mcc, mnc)
140 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700141 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200142 return sw
143
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200144 def update_plmnsel(self, mcc, mnc):
145 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700146 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200147 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200148 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
149 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200150
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300151 def update_smsp(self, smsp):
152 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
153 return sw
154
Philipp Maieree908ae2019-03-21 16:21:12 +0100155 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200156 #See also: 3GPP TS 31.102, chapter 4.2.18
157 mnclen = len(str(mnc))
158 if mnclen == 1:
159 mnclen = 2
160 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100161 raise RuntimeError('unable to calculate proper mnclen')
162
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200163 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
164
165 # Reset contents to EF.AD in case the file is uninintalized
166 if data.lower() == "ffffffff":
167 data = "00000000"
168
169 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100170 data, sw = self._scc.update_binary(EF['AD'], content)
171 return sw
172
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300173 def read_spn(self):
174 (spn, sw) = self._scc.read_binary(EF['SPN'])
175 if sw == '9000':
176 return (dec_spn(spn), sw)
177 else:
178 return (None, sw)
179
180 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
181 content = enc_spn(name, hplmn_disp, oplmn_disp)
182 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
183 return sw
184
Supreeth Herled21349a2020-04-01 08:37:47 +0200185 def read_binary(self, ef, length=None, offset=0):
186 ef_path = ef in EF and EF[ef] or ef
187 return self._scc.read_binary(ef_path, length, offset)
188
Supreeth Herlead10d662020-04-01 08:43:08 +0200189 def read_record(self, ef, rec_no):
190 ef_path = ef in EF and EF[ef] or ef
191 return self._scc.read_record(ef_path, rec_no)
192
Supreeth Herle98a69272020-03-18 12:14:48 +0100193 def read_gid1(self):
194 (res, sw) = self._scc.read_binary(EF['GID1'])
195 if sw == '9000':
196 return (res, sw)
197 else:
198 return (None, sw)
199
Supreeth Herle6d66af62020-03-19 12:49:16 +0100200 def read_msisdn(self):
201 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
202 if sw == '9000':
203 return (dec_msisdn(res), sw)
204 else:
205 return (None, sw)
206
Supreeth Herlee4e98312020-03-18 11:33:14 +0100207 # Fetch all the AIDs present on UICC
208 def read_aids(self):
209 try:
210 # Find out how many records the EF.DIR has
211 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100212 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100213 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100214 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100215 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
216 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
217 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
218 except Exception as e:
219 print("Can't read AIDs from SIM -- %s" % (str(e),))
220
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100221 # Select ADF.U/ISIM in the Card using its full AID
222 def select_adf_by_aid(self, adf="usim"):
223 # Check for valid ADF name
224 if adf not in ["usim", "isim"]:
225 return None
226
227 # First (known) halves of the U/ISIM AID
228 aid_map = {}
229 aid_map["usim"] = "a0000000871002"
230 aid_map["isim"] = "a0000000871004"
231
232 for aid in self._aids:
233 if aid_map[adf] in aid:
234 (res, sw) = self._scc.select_adf(aid)
235 return sw
236
237 return None
238
Philipp Maier5c2cc662020-05-12 16:27:12 +0200239 # Erase the contents of a file
240 def erase_binary(self, ef):
241 len = self._scc.binary_size(ef)
242 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
243
244 # Erase the contents of a single record
245 def erase_record(self, ef, rec_no):
246 len = self._scc.record_size(ef)
247 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
248
Harald Welteca673942020-06-03 15:19:40 +0200249class UsimCard(Card):
250 def __init__(self, ssc):
251 super(UsimCard, self).__init__(ssc)
252
253 def read_ehplmn(self):
254 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
255 if sw == '9000':
256 return (format_xplmn(res), sw)
257 else:
258 return (None, sw)
259
260 def update_ehplmn(self, mcc, mnc):
261 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
262 size = len(data[0]) // 2
263 ehplmn = enc_plmn(mcc, mnc)
264 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
265 return sw
266
herlesupreethf8232db2020-09-29 10:03:06 +0200267 def read_epdgid(self):
268 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
269 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100270 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200271 else:
272 return (None, sw)
273
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200274 def update_epdgid(self, epdgid):
Supreeth Herle3b342c22020-03-24 16:15:02 +0100275 epdgid_tlv = enc_addr_tlv(epdgid)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200276 data, sw = self._scc.update_binary(
277 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
278 return sw
Harald Welteca673942020-06-03 15:19:40 +0200279
Supreeth Herle99d55552020-03-24 13:03:43 +0100280 def read_ePDGSelection(self):
281 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
282 if sw == '9000':
283 return (format_ePDGSelection(res), sw)
284 else:
285 return (None, sw)
286
Supreeth Herlef964df42020-03-24 13:15:37 +0100287 def update_ePDGSelection(self, mcc, mnc):
288 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
289 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
290 # Reset contents
291 # 80 - Tag value
292 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
293 elif sw == '9000':
294 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
295 return sw
296
herlesupreeth4a3580b2020-09-29 10:11:36 +0200297 def read_ust(self):
298 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
299 if sw == '9000':
300 # Print those which are available
301 return ([res, dec_st(res, table="usim")], sw)
302 else:
303 return ([None, None], sw)
304
Supreeth Herleacc222f2020-03-24 13:26:53 +0100305 def update_ust(self, service, bit=1):
306 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
307 if sw == '9000':
308 content = enc_st(res, service, bit)
309 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
310 return sw
311
herlesupreethecbada92020-12-23 09:24:29 +0100312class IsimCard(Card):
313 def __init__(self, ssc):
314 super(IsimCard, self).__init__(ssc)
315
Sylvain Munaut76504e02010-12-07 00:24:32 +0100316
317class _MagicSimBase(Card):
318 """
319 Theses cards uses several record based EFs to store the provider infos,
320 each possible provider uses a specific record number in each EF. The
321 indexes used are ( where N is the number of providers supported ) :
322 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100323 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100324
325 * 3f00/7f4d/8f0c : Operator Name
326
327 bytes 0-15 : provider name, padded with 0xff
328 byte 16 : length of the provider name
329 byte 17 : 01 for valid records, 00 otherwise
330
331 * 3f00/7f4d/8f0d : Programmable Binary EFs
332
333 * 3f00/7f4d/8f0e : Programmable Record EFs
334
335 """
336
337 @classmethod
338 def autodetect(kls, scc):
339 try:
340 for p, l, t in kls._files.values():
341 if not t:
342 continue
343 if scc.record_size(['3f00', '7f4d', p]) != l:
344 return None
345 except:
346 return None
347
348 return kls(scc)
349
350 def _get_count(self):
351 """
352 Selects the file and returns the total number of entries
353 and entry size
354 """
355 f = self._files['name']
356
357 r = self._scc.select_file(['3f00', '7f4d', f[0]])
358 rec_len = int(r[-1][28:30], 16)
359 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200360 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100361
362 if (rec_cnt < 1) or (rec_len != f[1]):
363 raise RuntimeError('Bad card type')
364
365 return rec_cnt
366
367 def program(self, p):
368 # Go to dir
369 self._scc.select_file(['3f00', '7f4d'])
370
371 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400372 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100373
374 # Operator name ( 3f00/7f4d/8f0c )
375 self._scc.update_record(self._files['name'][0], 2,
376 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
377 )
378
379 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
380 v = ''
381
382 # inline Ki
383 if self._ki_file is None:
384 v += p['ki']
385
386 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400387 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100388
389 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400390 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391
392 # Ki
393 if self._ki_file:
394 v += self._ki_file + '10' + p['ki']
395
396 # PLMN_Sel
397 v+= '6f30' + '18' + rpad(hplmn, 36)
398
Alexander Chemeris21885242013-07-02 16:56:55 +0400399 # ACC
400 # This doesn't work with "fake" SuperSIM cards,
401 # but will hopefully work with real SuperSIMs.
402 if p.get('acc') is not None:
403 v+= '6f78' + '02' + lpad(p['acc'], 4)
404
Sylvain Munaut76504e02010-12-07 00:24:32 +0100405 self._scc.update_record(self._files['b_ef'][0], 1,
406 rpad(v, self._files['b_ef'][1]*2)
407 )
408
409 # SMSP ( 3f00/7f4d/8f0e )
410 # FIXME
411
412 # Write PLMN_Sel forcefully as well
413 r = self._scc.select_file(['3f00', '7f20', '6f30'])
414 tl = int(r[-1][4:8], 16)
415
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400416 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100417 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
418
419 def erase(self):
420 # Dummy
421 df = {}
422 for k, v in self._files.iteritems():
423 ofs = 1
424 fv = v[1] * 'ff'
425 if k == 'name':
426 ofs = 2
427 fv = fv[0:-4] + '0000'
428 df[v[0]] = (fv, ofs)
429
430 # Write
431 for n in range(0,self._get_count()):
432 for k, (msg, ofs) in df.iteritems():
433 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
434
435
436class SuperSim(_MagicSimBase):
437
438 name = 'supersim'
439
440 _files = {
441 'name' : ('8f0c', 18, True),
442 'b_ef' : ('8f0d', 74, True),
443 'r_ef' : ('8f0e', 50, True),
444 }
445
446 _ki_file = None
447
448
449class MagicSim(_MagicSimBase):
450
451 name = 'magicsim'
452
453 _files = {
454 'name' : ('8f0c', 18, True),
455 'b_ef' : ('8f0d', 130, True),
456 'r_ef' : ('8f0e', 102, False),
457 }
458
459 _ki_file = '6f1b'
460
461
462class FakeMagicSim(Card):
463 """
464 Theses cards have a record based EF 3f00/000c that contains the provider
465 informations. See the program method for its format. The records go from
466 1 to N.
467 """
468
469 name = 'fakemagicsim'
470
471 @classmethod
472 def autodetect(kls, scc):
473 try:
474 if scc.record_size(['3f00', '000c']) != 0x5a:
475 return None
476 except:
477 return None
478
479 return kls(scc)
480
481 def _get_infos(self):
482 """
483 Selects the file and returns the total number of entries
484 and entry size
485 """
486
487 r = self._scc.select_file(['3f00', '000c'])
488 rec_len = int(r[-1][28:30], 16)
489 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200490 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100491
492 if (rec_cnt < 1) or (rec_len != 0x5a):
493 raise RuntimeError('Bad card type')
494
495 return rec_cnt, rec_len
496
497 def program(self, p):
498 # Home PLMN
499 r = self._scc.select_file(['3f00', '7f20', '6f30'])
500 tl = int(r[-1][4:8], 16)
501
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400502 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100503 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
504
505 # Get total number of entries and entry size
506 rec_cnt, rec_len = self._get_infos()
507
508 # Set first entry
509 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200510 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100511 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200512 enc_iccid(p['iccid']) + # 10b ICCID
513 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
514 p['ki'] + # 16b Ki
515 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100516 )
517 self._scc.update_record('000c', 1, entry)
518
519 def erase(self):
520 # Get total number of entries and entry size
521 rec_cnt, rec_len = self._get_infos()
522
523 # Erase all entries
524 entry = 'ff' * rec_len
525 for i in range(0, rec_cnt):
526 self._scc.update_record('000c', 1+i, entry)
527
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200528
Harald Welte3156d902011-03-22 21:48:19 +0100529class GrcardSim(Card):
530 """
531 Greencard (grcard.cn) HZCOS GSM SIM
532 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
533 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
534 """
535
536 name = 'grcardsim'
537
538 @classmethod
539 def autodetect(kls, scc):
540 return None
541
542 def program(self, p):
543 # We don't really know yet what ADM PIN 4 is about
544 #self._scc.verify_chv(4, h2b("4444444444444444"))
545
546 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100547 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200548 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100549 else:
550 pin = h2b("4444444444444444")
551 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100552
553 # EF.ICCID
554 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400555 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100556
557 # EF.IMSI
558 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400559 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100560
561 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400562 if p.get('acc') is not None:
563 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100564
565 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200566 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200567 r = self._scc.select_file(['3f00', '7f10', '6f42'])
568 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100569
570 # Set the Ki using proprietary command
571 pdu = '80d4020010' + p['ki']
572 data, sw = self._scc._tp.send_apdu(pdu)
573
574 # EF.HPLMN
575 r = self._scc.select_file(['3f00', '7f20', '6f30'])
576 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400577 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100578 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
579
580 # EF.SPN (Service Provider Name)
581 r = self._scc.select_file(['3f00', '7f20', '6f30'])
582 size = int(r[-1][4:8], 16)
583 # FIXME
584
585 # FIXME: EF.MSISDN
586
Sylvain Munaut76504e02010-12-07 00:24:32 +0100587
Harald Weltee10394b2011-12-07 12:34:14 +0100588class SysmoSIMgr1(GrcardSim):
589 """
590 sysmocom sysmoSIM-GR1
591 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
592 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
593 """
594 name = 'sysmosim-gr1'
595
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200596 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200597 def autodetect(kls, scc):
598 try:
599 # Look for ATR
600 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
601 return kls(scc)
602 except:
603 return None
604 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200605
Harald Welteca673942020-06-03 15:19:40 +0200606class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100607 """
608 sysmocom sysmoUSIM-GR1
609 """
610 name = 'sysmoUSIM-GR1'
611
612 @classmethod
613 def autodetect(kls, scc):
614 # TODO: Access the ATR
615 return None
616
617 def program(self, p):
618 # TODO: check if verify_chv could be used or what it needs
619 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
620 # Unlock the card..
621 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
622
623 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100624 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400625 p['opc'] + # 32b OPC
626 enc_iccid(p['iccid']) + # 10b ICCID
627 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100628 )
629 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
630
Sylvain Munaut053c8952013-07-02 15:12:32 +0200631
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100632class SysmoSIMgr2(Card):
633 """
634 sysmocom sysmoSIM-GR2
635 """
636
637 name = 'sysmoSIM-GR2'
638
639 @classmethod
640 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900641 try:
642 # Look for ATR
643 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
644 return kls(scc)
645 except:
646 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100647 return None
648
649 def program(self, p):
650
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200651 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100652 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200653
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100654 # authenticate as SUPER ADM using default key
655 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
656
657 # set ADM pin using proprietary command
658 # INS: D4
659 # P1: 3A for PIN, 3B for PUK
660 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
661 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100662 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200663 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100664 else:
665 pin = h2b("4444444444444444")
666
667 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100668 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200669
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100670 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100671
672 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100673
674 # write EF.ICCID
675 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
676
677 # select DF_GSM
678 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200679
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100680 # write EF.IMSI
681 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
682
683 # write EF.ACC
684 if p.get('acc') is not None:
685 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
686
687 # get size and write EF.HPLMN
688 r = self._scc.select_file(['6f30'])
689 size = int(r[-1][4:8], 16)
690 hplmn = enc_plmn(p['mcc'], p['mnc'])
691 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
692
693 # set COMP128 version 0 in proprietary file
694 data, sw = self._scc.update_binary('0001', '001000')
695
696 # set Ki in proprietary file
697 data, sw = self._scc.update_binary('0001', p['ki'], 3)
698
699 # select DF_TELECOM
700 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200701
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100702 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200703 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200704 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100705
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100706
Harald Welteca673942020-06-03 15:19:40 +0200707class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100708 """
709 sysmocom sysmoUSIM-SJS1
710 """
711
712 name = 'sysmoUSIM-SJS1'
713
714 def __init__(self, ssc):
715 super(SysmoUSIMSJS1, self).__init__(ssc)
716 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100717 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100718
719 @classmethod
720 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900721 try:
722 # Look for ATR
723 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"):
724 return kls(scc)
725 except:
726 return None
Jan Balke3e840672015-01-26 15:36:27 +0100727 return None
728
729 def program(self, p):
730
Philipp Maiere9604882017-03-21 17:24:31 +0100731 # authenticate as ADM using default key (written on the card..)
732 if not p['pin_adm']:
733 raise ValueError("Please provide a PIN-ADM as there is no default one")
734 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100735
736 # select MF
737 r = self._scc.select_file(['3f00'])
738
Philipp Maiere9604882017-03-21 17:24:31 +0100739 # write EF.ICCID
740 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
741
Jan Balke3e840672015-01-26 15:36:27 +0100742 # select DF_GSM
743 r = self._scc.select_file(['7f20'])
744
Jan Balke3e840672015-01-26 15:36:27 +0100745 # set Ki in proprietary file
746 data, sw = self._scc.update_binary('00FF', p['ki'])
747
Philipp Maier1be35bf2018-07-13 11:29:03 +0200748 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200749 if 'opc' in p:
750 content = "01" + p['opc']
751 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100752
Supreeth Herle7947d922019-06-08 07:50:53 +0200753 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100754 if p.get('name') is not None:
755 content = enc_spn(p['name'], True, True)
756 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200757
Supreeth Herlec8796a32019-12-23 12:23:42 +0100758 if p.get('acc') is not None:
759 self.update_acc(p['acc'])
760
Jan Balke3e840672015-01-26 15:36:27 +0100761 # write EF.IMSI
762 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
763
Philipp Maier2d15ea02019-03-20 12:40:36 +0100764 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200765 if p.get('mcc') and p.get('mnc'):
766 sw = self.update_plmnsel(p['mcc'], p['mnc'])
767 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100768 print("Programming PLMNsel failed with code %s"%sw)
769
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200770 # EF.PLMNwAcT
771 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100772 sw = self.update_plmn_act(p['mcc'], p['mnc'])
773 if sw != '9000':
774 print("Programming PLMNwAcT failed with code %s"%sw)
775
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200776 # EF.OPLMNwAcT
777 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100778 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
779 if sw != '9000':
780 print("Programming OPLMNwAcT failed with code %s"%sw)
781
Supreeth Herlef442fb42020-01-21 12:47:32 +0100782 # EF.HPLMNwAcT
783 if p.get('mcc') and p.get('mnc'):
784 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
785 if sw != '9000':
786 print("Programming HPLMNwAcT failed with code %s"%sw)
787
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200788 # EF.AD
789 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100790 sw = self.update_ad(p['mnc'])
791 if sw != '9000':
792 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100793
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200794 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200795 if p.get('smsp'):
796 r = self._scc.select_file(['3f00', '7f10'])
797 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100798
Supreeth Herle5a541012019-12-22 08:59:16 +0100799 # EF.MSISDN
800 # TODO: Alpha Identifier (currently 'ff'O * 20)
801 # TODO: Capability/Configuration1 Record Identifier
802 # TODO: Extension1 Record Identifier
803 if p.get('msisdn') is not None:
804 msisdn = enc_msisdn(p['msisdn'])
805 data = 'ff' * 20 + msisdn + 'ff' * 2
806
807 r = self._scc.select_file(['3f00', '7f10'])
808 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
809
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900810
herlesupreeth4a3580b2020-09-29 10:11:36 +0200811class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900812 """
813 FairwavesSIM
814
815 The SIM card is operating according to the standard.
816 For Ki/OP/OPC programming the following files are additionally open for writing:
817 3F00/7F20/FF01 – OP/OPC:
818 byte 1 = 0x01, bytes 2-17: OPC;
819 byte 1 = 0x00, bytes 2-17: OP;
820 3F00/7F20/FF02: Ki
821 """
822
Philipp Maier5a876312019-11-11 11:01:46 +0100823 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900824 # Propriatary files
825 _EF_num = {
826 'Ki': 'FF02',
827 'OP/OPC': 'FF01',
828 }
829 _EF = {
830 'Ki': DF['GSM']+[_EF_num['Ki']],
831 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
832 }
833
834 def __init__(self, ssc):
835 super(FairwavesSIM, self).__init__(ssc)
836 self._adm_chv_num = 0x11
837 self._adm2_chv_num = 0x12
838
839
840 @classmethod
841 def autodetect(kls, scc):
842 try:
843 # Look for ATR
844 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"):
845 return kls(scc)
846 except:
847 return None
848 return None
849
850
851 def verify_adm2(self, key):
852 '''
853 Authenticate with ADM2 key.
854
855 Fairwaves SIM cards support hierarchical key structure and ADM2 key
856 is a key which has access to proprietary files (Ki and OP/OPC).
857 That said, ADM key inherits permissions of ADM2 key and thus we rarely
858 need ADM2 key per se.
859 '''
860 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
861 return sw
862
863
864 def read_ki(self):
865 """
866 Read Ki in proprietary file.
867
868 Requires ADM1 access level
869 """
870 return self._scc.read_binary(self._EF['Ki'])
871
872
873 def update_ki(self, ki):
874 """
875 Set Ki in proprietary file.
876
877 Requires ADM1 access level
878 """
879 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
880 return sw
881
882
883 def read_op_opc(self):
884 """
885 Read Ki in proprietary file.
886
887 Requires ADM1 access level
888 """
889 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
890 type = 'OP' if ef[0:2] == '00' else 'OPC'
891 return ((type, ef[2:]), sw)
892
893
894 def update_op(self, op):
895 """
896 Set OP in proprietary file.
897
898 Requires ADM1 access level
899 """
900 content = '00' + op
901 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
902 return sw
903
904
905 def update_opc(self, opc):
906 """
907 Set OPC in proprietary file.
908
909 Requires ADM1 access level
910 """
911 content = '01' + opc
912 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
913 return sw
914
915
916 def program(self, p):
917 # authenticate as ADM1
918 if not p['pin_adm']:
919 raise ValueError("Please provide a PIN-ADM as there is no default one")
920 sw = self.verify_adm(h2b(p['pin_adm']))
921 if sw != '9000':
922 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
923
924 # TODO: Set operator name
925 if p.get('smsp') is not None:
926 sw = self.update_smsp(p['smsp'])
927 if sw != '9000':
928 print("Programming SMSP failed with code %s"%sw)
929 # This SIM doesn't support changing ICCID
930 if p.get('mcc') is not None and p.get('mnc') is not None:
931 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
932 if sw != '9000':
933 print("Programming MCC/MNC failed with code %s"%sw)
934 if p.get('imsi') is not None:
935 sw = self.update_imsi(p['imsi'])
936 if sw != '9000':
937 print("Programming IMSI failed with code %s"%sw)
938 if p.get('ki') is not None:
939 sw = self.update_ki(p['ki'])
940 if sw != '9000':
941 print("Programming Ki failed with code %s"%sw)
942 if p.get('opc') is not None:
943 sw = self.update_opc(p['opc'])
944 if sw != '9000':
945 print("Programming OPC failed with code %s"%sw)
946 if p.get('acc') is not None:
947 sw = self.update_acc(p['acc'])
948 if sw != '9000':
949 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100950
Todd Neal9eeadfc2018-04-25 15:36:29 -0500951class OpenCellsSim(Card):
952 """
953 OpenCellsSim
954
955 """
956
Philipp Maier5a876312019-11-11 11:01:46 +0100957 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500958
959 def __init__(self, ssc):
960 super(OpenCellsSim, self).__init__(ssc)
961 self._adm_chv_num = 0x0A
962
963
964 @classmethod
965 def autodetect(kls, scc):
966 try:
967 # Look for ATR
968 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"):
969 return kls(scc)
970 except:
971 return None
972 return None
973
974
975 def program(self, p):
976 if not p['pin_adm']:
977 raise ValueError("Please provide a PIN-ADM as there is no default one")
978 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
979
980 # select MF
981 r = self._scc.select_file(['3f00'])
982
983 # write EF.ICCID
984 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
985
986 r = self._scc.select_file(['7ff0'])
987
988 # set Ki in proprietary file
989 data, sw = self._scc.update_binary('FF02', p['ki'])
990
991 # set OPC in proprietary file
992 data, sw = self._scc.update_binary('FF01', p['opc'])
993
994 # select DF_GSM
995 r = self._scc.select_file(['7f20'])
996
997 # write EF.IMSI
998 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
999
herlesupreeth4a3580b2020-09-29 10:11:36 +02001000class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001001 """
1002 WavemobileSim
1003
1004 """
1005
1006 name = 'Wavemobile-SIM'
1007
1008 def __init__(self, ssc):
1009 super(WavemobileSim, self).__init__(ssc)
1010 self._adm_chv_num = 0x0A
1011 self._scc.cla_byte = "00"
1012 self._scc.sel_ctrl = "0004" #request an FCP
1013
1014 @classmethod
1015 def autodetect(kls, scc):
1016 try:
1017 # Look for ATR
1018 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"):
1019 return kls(scc)
1020 except:
1021 return None
1022 return None
1023
1024 def program(self, p):
1025 if not p['pin_adm']:
1026 raise ValueError("Please provide a PIN-ADM as there is no default one")
1027 sw = self.verify_adm(h2b(p['pin_adm']))
1028 if sw != '9000':
1029 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1030
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001031 # EF.ICCID
1032 # TODO: Add programming of the ICCID
1033 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001034 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1035
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001036 # KI (Presumably a propritary file)
1037 # TODO: Add programming of KI
1038 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001039 print("Warning: Programming of the KI is not implemented for this type of card.")
1040
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001041 # OPc (Presumably a propritary file)
1042 # TODO: Add programming of OPc
1043 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001044 print("Warning: Programming of the OPc is not implemented for this type of card.")
1045
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001046 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001047 if p.get('smsp'):
1048 sw = self.update_smsp(p['smsp'])
1049 if sw != '9000':
1050 print("Programming SMSP failed with code %s"%sw)
1051
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001052 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001053 if p.get('imsi'):
1054 sw = self.update_imsi(p['imsi'])
1055 if sw != '9000':
1056 print("Programming IMSI failed with code %s"%sw)
1057
1058 # EF.ACC
1059 if p.get('acc'):
1060 sw = self.update_acc(p['acc'])
1061 if sw != '9000':
1062 print("Programming ACC failed with code %s"%sw)
1063
1064 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001065 if p.get('mcc') and p.get('mnc'):
1066 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1067 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001068 print("Programming PLMNsel failed with code %s"%sw)
1069
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001070 # EF.PLMNwAcT
1071 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001072 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1073 if sw != '9000':
1074 print("Programming PLMNwAcT failed with code %s"%sw)
1075
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001076 # EF.OPLMNwAcT
1077 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001078 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1079 if sw != '9000':
1080 print("Programming OPLMNwAcT failed with code %s"%sw)
1081
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001082 # EF.AD
1083 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001084 sw = self.update_ad(p['mnc'])
1085 if sw != '9000':
1086 print("Programming AD failed with code %s"%sw)
1087
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001088 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001089
Todd Neal9eeadfc2018-04-25 15:36:29 -05001090
herlesupreethb0c7d122020-12-23 09:25:46 +01001091class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001092 """
1093 sysmocom sysmoISIM-SJA2
1094 """
1095
1096 name = 'sysmoISIM-SJA2'
1097
1098 def __init__(self, ssc):
1099 super(SysmoISIMSJA2, self).__init__(ssc)
1100 self._scc.cla_byte = "00"
1101 self._scc.sel_ctrl = "0004" #request an FCP
1102
1103 @classmethod
1104 def autodetect(kls, scc):
1105 try:
1106 # Try card model #1
1107 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1108 if scc.get_atr() == toBytes(atr):
1109 return kls(scc)
1110
1111 # Try card model #2
1112 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1113 if scc.get_atr() == toBytes(atr):
1114 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001115
1116 # Try card model #3
1117 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1118 if scc.get_atr() == toBytes(atr):
1119 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001120 except:
1121 return None
1122 return None
1123
1124 def program(self, p):
1125 # authenticate as ADM using default key (written on the card..)
1126 if not p['pin_adm']:
1127 raise ValueError("Please provide a PIN-ADM as there is no default one")
1128 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1129
1130 # This type of card does not allow to reprogram the ICCID.
1131 # Reprogramming the ICCID would mess up the card os software
1132 # license management, so the ICCID must be kept at its factory
1133 # setting!
1134 if p.get('iccid'):
1135 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1136
1137 # select DF_GSM
1138 self._scc.select_file(['7f20'])
1139
1140 # write EF.IMSI
1141 if p.get('imsi'):
1142 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1143
1144 # EF.PLMNsel
1145 if p.get('mcc') and p.get('mnc'):
1146 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1147 if sw != '9000':
1148 print("Programming PLMNsel failed with code %s"%sw)
1149
1150 # EF.PLMNwAcT
1151 if p.get('mcc') and p.get('mnc'):
1152 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1153 if sw != '9000':
1154 print("Programming PLMNwAcT failed with code %s"%sw)
1155
1156 # EF.OPLMNwAcT
1157 if p.get('mcc') and p.get('mnc'):
1158 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1159 if sw != '9000':
1160 print("Programming OPLMNwAcT failed with code %s"%sw)
1161
Harald Welte32f0d412020-05-05 17:35:57 +02001162 # EF.HPLMNwAcT
1163 if p.get('mcc') and p.get('mnc'):
1164 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1165 if sw != '9000':
1166 print("Programming HPLMNwAcT failed with code %s"%sw)
1167
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001168 # EF.AD
1169 if p.get('mcc') and p.get('mnc'):
1170 sw = self.update_ad(p['mnc'])
1171 if sw != '9000':
1172 print("Programming AD failed with code %s"%sw)
1173
1174 # EF.SMSP
1175 if p.get('smsp'):
1176 r = self._scc.select_file(['3f00', '7f10'])
1177 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1178
Supreeth Herle80164052020-03-23 12:06:29 +01001179 # Populate AIDs
1180 self.read_aids()
1181
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001182 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1183 # hard linked to EF-USIM_AUTH_KEY)
1184 self._scc.select_file(['3f00'])
1185 self._scc.select_file(['a515'])
1186 if p.get('ki'):
1187 self._scc.update_binary('6f20', p['ki'], 1)
1188 if p.get('opc'):
1189 self._scc.update_binary('6f20', p['opc'], 17)
1190
1191 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001192 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001193 if p.get('ki'):
1194 self._scc.update_binary('af20', p['ki'], 1)
1195 if p.get('opc'):
1196 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001197
herlesupreeth1a13c442020-09-11 21:16:51 +02001198 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001199 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001200 if p.get('ki'):
1201 self._scc.update_binary('af20', p['ki'], 1)
1202 if p.get('opc'):
1203 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001204
Harald Welteca673942020-06-03 15:19:40 +02001205 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001206 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001207 if p.get('mcc') and p.get('mnc'):
1208 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1209 if sw != '9000':
1210 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001211
1212 # update EF.ePDGId in ADF.USIM
1213 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1214 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001215 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001216 if sw != '9000':
1217 print("Programming ePDGId failed with code %s"%sw)
1218
Supreeth Herlef964df42020-03-24 13:15:37 +01001219 # update EF.ePDGSelection in ADF.USIM
1220 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1221 if p.get('epdgSelection'):
1222 epdg_plmn = p['epdgSelection']
1223 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1224 else:
1225 sw = self.update_ePDGSelection("", "")
1226 if sw != '9000':
1227 print("Programming ePDGSelection failed with code %s"%sw)
1228
1229
Supreeth Herleacc222f2020-03-24 13:26:53 +01001230 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1231 # Set service 106 and 107 as available in EF.UST
1232 if self.file_exists(EF_USIM_ADF_map['UST']):
1233 if p.get('epdgSelection') and p.get('epdgid'):
1234 sw = self.update_ust(106, 1)
1235 if sw != '9000':
1236 print("Programming UST failed with code %s"%sw)
1237 sw = self.update_ust(107, 1)
1238 if sw != '9000':
1239 print("Programming UST failed with code %s"%sw)
1240
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001241 return
1242
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001243
Todd Neal9eeadfc2018-04-25 15:36:29 -05001244# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001245_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001246 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001247 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001248
1249def card_autodetect(scc):
1250 for kls in _cards_classes:
1251 card = kls.autodetect(scc)
1252 if card is not None:
1253 card.reset()
1254 return card
1255 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001256
1257def card_detect(ctype, scc):
1258 # Detect type if needed
1259 card = None
1260 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1261
1262 if ctype in ("auto", "auto_once"):
1263 for kls in _cards_classes:
1264 card = kls.autodetect(scc)
1265 if card:
1266 print("Autodetected card type: %s" % card.name)
1267 card.reset()
1268 break
1269
1270 if card is None:
1271 print("Autodetection failed")
1272 return None
1273
1274 if ctype == "auto_once":
1275 ctype = card.name
1276
1277 elif ctype in ctypes:
1278 card = ctypes[ctype](scc)
1279
1280 else:
1281 raise ValueError("Unknown card type: %s" % ctype)
1282
1283 return card