blob: f2a3d2a992b88ca7ba4947a33fd3596aa5a793d4 [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
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200267 def update_epdgid(self, epdgid):
268 epdgid_tlv = enc_epdgid(epdgid)
269 data, sw = self._scc.update_binary(
270 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
271 return sw
Harald Welteca673942020-06-03 15:19:40 +0200272
Sylvain Munaut76504e02010-12-07 00:24:32 +0100273
274class _MagicSimBase(Card):
275 """
276 Theses cards uses several record based EFs to store the provider infos,
277 each possible provider uses a specific record number in each EF. The
278 indexes used are ( where N is the number of providers supported ) :
279 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100280 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100281
282 * 3f00/7f4d/8f0c : Operator Name
283
284 bytes 0-15 : provider name, padded with 0xff
285 byte 16 : length of the provider name
286 byte 17 : 01 for valid records, 00 otherwise
287
288 * 3f00/7f4d/8f0d : Programmable Binary EFs
289
290 * 3f00/7f4d/8f0e : Programmable Record EFs
291
292 """
293
294 @classmethod
295 def autodetect(kls, scc):
296 try:
297 for p, l, t in kls._files.values():
298 if not t:
299 continue
300 if scc.record_size(['3f00', '7f4d', p]) != l:
301 return None
302 except:
303 return None
304
305 return kls(scc)
306
307 def _get_count(self):
308 """
309 Selects the file and returns the total number of entries
310 and entry size
311 """
312 f = self._files['name']
313
314 r = self._scc.select_file(['3f00', '7f4d', f[0]])
315 rec_len = int(r[-1][28:30], 16)
316 tlen = int(r[-1][4:8],16)
317 rec_cnt = (tlen / rec_len) - 1;
318
319 if (rec_cnt < 1) or (rec_len != f[1]):
320 raise RuntimeError('Bad card type')
321
322 return rec_cnt
323
324 def program(self, p):
325 # Go to dir
326 self._scc.select_file(['3f00', '7f4d'])
327
328 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400329 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100330
331 # Operator name ( 3f00/7f4d/8f0c )
332 self._scc.update_record(self._files['name'][0], 2,
333 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
334 )
335
336 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
337 v = ''
338
339 # inline Ki
340 if self._ki_file is None:
341 v += p['ki']
342
343 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400344 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100345
346 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400347 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100348
349 # Ki
350 if self._ki_file:
351 v += self._ki_file + '10' + p['ki']
352
353 # PLMN_Sel
354 v+= '6f30' + '18' + rpad(hplmn, 36)
355
Alexander Chemeris21885242013-07-02 16:56:55 +0400356 # ACC
357 # This doesn't work with "fake" SuperSIM cards,
358 # but will hopefully work with real SuperSIMs.
359 if p.get('acc') is not None:
360 v+= '6f78' + '02' + lpad(p['acc'], 4)
361
Sylvain Munaut76504e02010-12-07 00:24:32 +0100362 self._scc.update_record(self._files['b_ef'][0], 1,
363 rpad(v, self._files['b_ef'][1]*2)
364 )
365
366 # SMSP ( 3f00/7f4d/8f0e )
367 # FIXME
368
369 # Write PLMN_Sel forcefully as well
370 r = self._scc.select_file(['3f00', '7f20', '6f30'])
371 tl = int(r[-1][4:8], 16)
372
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400373 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100374 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
375
376 def erase(self):
377 # Dummy
378 df = {}
379 for k, v in self._files.iteritems():
380 ofs = 1
381 fv = v[1] * 'ff'
382 if k == 'name':
383 ofs = 2
384 fv = fv[0:-4] + '0000'
385 df[v[0]] = (fv, ofs)
386
387 # Write
388 for n in range(0,self._get_count()):
389 for k, (msg, ofs) in df.iteritems():
390 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
391
392
393class SuperSim(_MagicSimBase):
394
395 name = 'supersim'
396
397 _files = {
398 'name' : ('8f0c', 18, True),
399 'b_ef' : ('8f0d', 74, True),
400 'r_ef' : ('8f0e', 50, True),
401 }
402
403 _ki_file = None
404
405
406class MagicSim(_MagicSimBase):
407
408 name = 'magicsim'
409
410 _files = {
411 'name' : ('8f0c', 18, True),
412 'b_ef' : ('8f0d', 130, True),
413 'r_ef' : ('8f0e', 102, False),
414 }
415
416 _ki_file = '6f1b'
417
418
419class FakeMagicSim(Card):
420 """
421 Theses cards have a record based EF 3f00/000c that contains the provider
422 informations. See the program method for its format. The records go from
423 1 to N.
424 """
425
426 name = 'fakemagicsim'
427
428 @classmethod
429 def autodetect(kls, scc):
430 try:
431 if scc.record_size(['3f00', '000c']) != 0x5a:
432 return None
433 except:
434 return None
435
436 return kls(scc)
437
438 def _get_infos(self):
439 """
440 Selects the file and returns the total number of entries
441 and entry size
442 """
443
444 r = self._scc.select_file(['3f00', '000c'])
445 rec_len = int(r[-1][28:30], 16)
446 tlen = int(r[-1][4:8],16)
447 rec_cnt = (tlen / rec_len) - 1;
448
449 if (rec_cnt < 1) or (rec_len != 0x5a):
450 raise RuntimeError('Bad card type')
451
452 return rec_cnt, rec_len
453
454 def program(self, p):
455 # Home PLMN
456 r = self._scc.select_file(['3f00', '7f20', '6f30'])
457 tl = int(r[-1][4:8], 16)
458
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400459 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100460 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
461
462 # Get total number of entries and entry size
463 rec_cnt, rec_len = self._get_infos()
464
465 # Set first entry
466 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200467 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100468 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200469 enc_iccid(p['iccid']) + # 10b ICCID
470 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
471 p['ki'] + # 16b Ki
472 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100473 )
474 self._scc.update_record('000c', 1, entry)
475
476 def erase(self):
477 # Get total number of entries and entry size
478 rec_cnt, rec_len = self._get_infos()
479
480 # Erase all entries
481 entry = 'ff' * rec_len
482 for i in range(0, rec_cnt):
483 self._scc.update_record('000c', 1+i, entry)
484
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200485
Harald Welte3156d902011-03-22 21:48:19 +0100486class GrcardSim(Card):
487 """
488 Greencard (grcard.cn) HZCOS GSM SIM
489 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
490 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
491 """
492
493 name = 'grcardsim'
494
495 @classmethod
496 def autodetect(kls, scc):
497 return None
498
499 def program(self, p):
500 # We don't really know yet what ADM PIN 4 is about
501 #self._scc.verify_chv(4, h2b("4444444444444444"))
502
503 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100504 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200505 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100506 else:
507 pin = h2b("4444444444444444")
508 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100509
510 # EF.ICCID
511 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400512 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100513
514 # EF.IMSI
515 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400516 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100517
518 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400519 if p.get('acc') is not None:
520 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100521
522 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200523 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200524 r = self._scc.select_file(['3f00', '7f10', '6f42'])
525 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100526
527 # Set the Ki using proprietary command
528 pdu = '80d4020010' + p['ki']
529 data, sw = self._scc._tp.send_apdu(pdu)
530
531 # EF.HPLMN
532 r = self._scc.select_file(['3f00', '7f20', '6f30'])
533 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400534 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100535 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
536
537 # EF.SPN (Service Provider Name)
538 r = self._scc.select_file(['3f00', '7f20', '6f30'])
539 size = int(r[-1][4:8], 16)
540 # FIXME
541
542 # FIXME: EF.MSISDN
543
Sylvain Munaut76504e02010-12-07 00:24:32 +0100544
Harald Weltee10394b2011-12-07 12:34:14 +0100545class SysmoSIMgr1(GrcardSim):
546 """
547 sysmocom sysmoSIM-GR1
548 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
549 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
550 """
551 name = 'sysmosim-gr1'
552
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200553 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200554 def autodetect(kls, scc):
555 try:
556 # Look for ATR
557 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
558 return kls(scc)
559 except:
560 return None
561 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200562
Harald Welteca673942020-06-03 15:19:40 +0200563class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100564 """
565 sysmocom sysmoUSIM-GR1
566 """
567 name = 'sysmoUSIM-GR1'
568
569 @classmethod
570 def autodetect(kls, scc):
571 # TODO: Access the ATR
572 return None
573
574 def program(self, p):
575 # TODO: check if verify_chv could be used or what it needs
576 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
577 # Unlock the card..
578 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
579
580 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100581 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400582 p['opc'] + # 32b OPC
583 enc_iccid(p['iccid']) + # 10b ICCID
584 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100585 )
586 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
587
Sylvain Munaut053c8952013-07-02 15:12:32 +0200588
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100589class SysmoSIMgr2(Card):
590 """
591 sysmocom sysmoSIM-GR2
592 """
593
594 name = 'sysmoSIM-GR2'
595
596 @classmethod
597 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900598 try:
599 # Look for ATR
600 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
601 return kls(scc)
602 except:
603 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100604 return None
605
606 def program(self, p):
607
608 # select MF
609 r = self._scc.select_file(['3f00'])
610
611 # authenticate as SUPER ADM using default key
612 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
613
614 # set ADM pin using proprietary command
615 # INS: D4
616 # P1: 3A for PIN, 3B for PUK
617 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
618 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100619 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200620 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100621 else:
622 pin = h2b("4444444444444444")
623
624 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100625 data, sw = self._scc._tp.send_apdu(pdu)
626
627 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100628
629 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100630
631 # write EF.ICCID
632 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
633
634 # select DF_GSM
635 r = self._scc.select_file(['7f20'])
636
637 # write EF.IMSI
638 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
639
640 # write EF.ACC
641 if p.get('acc') is not None:
642 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
643
644 # get size and write EF.HPLMN
645 r = self._scc.select_file(['6f30'])
646 size = int(r[-1][4:8], 16)
647 hplmn = enc_plmn(p['mcc'], p['mnc'])
648 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
649
650 # set COMP128 version 0 in proprietary file
651 data, sw = self._scc.update_binary('0001', '001000')
652
653 # set Ki in proprietary file
654 data, sw = self._scc.update_binary('0001', p['ki'], 3)
655
656 # select DF_TELECOM
657 r = self._scc.select_file(['3f00', '7f10'])
658
659 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200660 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200661 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100662
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100663
Harald Welteca673942020-06-03 15:19:40 +0200664class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100665 """
666 sysmocom sysmoUSIM-SJS1
667 """
668
669 name = 'sysmoUSIM-SJS1'
670
671 def __init__(self, ssc):
672 super(SysmoUSIMSJS1, self).__init__(ssc)
673 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100674 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100675
676 @classmethod
677 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900678 try:
679 # Look for ATR
680 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"):
681 return kls(scc)
682 except:
683 return None
Jan Balke3e840672015-01-26 15:36:27 +0100684 return None
685
686 def program(self, p):
687
Philipp Maiere9604882017-03-21 17:24:31 +0100688 # authenticate as ADM using default key (written on the card..)
689 if not p['pin_adm']:
690 raise ValueError("Please provide a PIN-ADM as there is no default one")
691 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100692
693 # select MF
694 r = self._scc.select_file(['3f00'])
695
Philipp Maiere9604882017-03-21 17:24:31 +0100696 # write EF.ICCID
697 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
698
Jan Balke3e840672015-01-26 15:36:27 +0100699 # select DF_GSM
700 r = self._scc.select_file(['7f20'])
701
Jan Balke3e840672015-01-26 15:36:27 +0100702 # set Ki in proprietary file
703 data, sw = self._scc.update_binary('00FF', p['ki'])
704
Philipp Maier1be35bf2018-07-13 11:29:03 +0200705 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200706 if 'opc' in p:
707 content = "01" + p['opc']
708 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100709
Supreeth Herle7947d922019-06-08 07:50:53 +0200710 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100711 if p.get('name') is not None:
712 content = enc_spn(p['name'], True, True)
713 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200714
Supreeth Herlec8796a32019-12-23 12:23:42 +0100715 if p.get('acc') is not None:
716 self.update_acc(p['acc'])
717
Jan Balke3e840672015-01-26 15:36:27 +0100718 # write EF.IMSI
719 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
720
Philipp Maier2d15ea02019-03-20 12:40:36 +0100721 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200722 if p.get('mcc') and p.get('mnc'):
723 sw = self.update_plmnsel(p['mcc'], p['mnc'])
724 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100725 print("Programming PLMNsel failed with code %s"%sw)
726
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200727 # EF.PLMNwAcT
728 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100729 sw = self.update_plmn_act(p['mcc'], p['mnc'])
730 if sw != '9000':
731 print("Programming PLMNwAcT failed with code %s"%sw)
732
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200733 # EF.OPLMNwAcT
734 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100735 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
736 if sw != '9000':
737 print("Programming OPLMNwAcT failed with code %s"%sw)
738
Supreeth Herlef442fb42020-01-21 12:47:32 +0100739 # EF.HPLMNwAcT
740 if p.get('mcc') and p.get('mnc'):
741 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
742 if sw != '9000':
743 print("Programming HPLMNwAcT failed with code %s"%sw)
744
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200745 # EF.AD
746 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100747 sw = self.update_ad(p['mnc'])
748 if sw != '9000':
749 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100750
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200751 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200752 if p.get('smsp'):
753 r = self._scc.select_file(['3f00', '7f10'])
754 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100755
Supreeth Herle5a541012019-12-22 08:59:16 +0100756 # EF.MSISDN
757 # TODO: Alpha Identifier (currently 'ff'O * 20)
758 # TODO: Capability/Configuration1 Record Identifier
759 # TODO: Extension1 Record Identifier
760 if p.get('msisdn') is not None:
761 msisdn = enc_msisdn(p['msisdn'])
762 data = 'ff' * 20 + msisdn + 'ff' * 2
763
764 r = self._scc.select_file(['3f00', '7f10'])
765 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
766
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900767
768class FairwavesSIM(Card):
769 """
770 FairwavesSIM
771
772 The SIM card is operating according to the standard.
773 For Ki/OP/OPC programming the following files are additionally open for writing:
774 3F00/7F20/FF01 – OP/OPC:
775 byte 1 = 0x01, bytes 2-17: OPC;
776 byte 1 = 0x00, bytes 2-17: OP;
777 3F00/7F20/FF02: Ki
778 """
779
Philipp Maier5a876312019-11-11 11:01:46 +0100780 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900781 # Propriatary files
782 _EF_num = {
783 'Ki': 'FF02',
784 'OP/OPC': 'FF01',
785 }
786 _EF = {
787 'Ki': DF['GSM']+[_EF_num['Ki']],
788 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
789 }
790
791 def __init__(self, ssc):
792 super(FairwavesSIM, self).__init__(ssc)
793 self._adm_chv_num = 0x11
794 self._adm2_chv_num = 0x12
795
796
797 @classmethod
798 def autodetect(kls, scc):
799 try:
800 # Look for ATR
801 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"):
802 return kls(scc)
803 except:
804 return None
805 return None
806
807
808 def verify_adm2(self, key):
809 '''
810 Authenticate with ADM2 key.
811
812 Fairwaves SIM cards support hierarchical key structure and ADM2 key
813 is a key which has access to proprietary files (Ki and OP/OPC).
814 That said, ADM key inherits permissions of ADM2 key and thus we rarely
815 need ADM2 key per se.
816 '''
817 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
818 return sw
819
820
821 def read_ki(self):
822 """
823 Read Ki in proprietary file.
824
825 Requires ADM1 access level
826 """
827 return self._scc.read_binary(self._EF['Ki'])
828
829
830 def update_ki(self, ki):
831 """
832 Set Ki in proprietary file.
833
834 Requires ADM1 access level
835 """
836 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
837 return sw
838
839
840 def read_op_opc(self):
841 """
842 Read Ki in proprietary file.
843
844 Requires ADM1 access level
845 """
846 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
847 type = 'OP' if ef[0:2] == '00' else 'OPC'
848 return ((type, ef[2:]), sw)
849
850
851 def update_op(self, op):
852 """
853 Set OP in proprietary file.
854
855 Requires ADM1 access level
856 """
857 content = '00' + op
858 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
859 return sw
860
861
862 def update_opc(self, opc):
863 """
864 Set OPC in proprietary file.
865
866 Requires ADM1 access level
867 """
868 content = '01' + opc
869 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
870 return sw
871
872
873 def program(self, p):
874 # authenticate as ADM1
875 if not p['pin_adm']:
876 raise ValueError("Please provide a PIN-ADM as there is no default one")
877 sw = self.verify_adm(h2b(p['pin_adm']))
878 if sw != '9000':
879 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
880
881 # TODO: Set operator name
882 if p.get('smsp') is not None:
883 sw = self.update_smsp(p['smsp'])
884 if sw != '9000':
885 print("Programming SMSP failed with code %s"%sw)
886 # This SIM doesn't support changing ICCID
887 if p.get('mcc') is not None and p.get('mnc') is not None:
888 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
889 if sw != '9000':
890 print("Programming MCC/MNC failed with code %s"%sw)
891 if p.get('imsi') is not None:
892 sw = self.update_imsi(p['imsi'])
893 if sw != '9000':
894 print("Programming IMSI failed with code %s"%sw)
895 if p.get('ki') is not None:
896 sw = self.update_ki(p['ki'])
897 if sw != '9000':
898 print("Programming Ki failed with code %s"%sw)
899 if p.get('opc') is not None:
900 sw = self.update_opc(p['opc'])
901 if sw != '9000':
902 print("Programming OPC failed with code %s"%sw)
903 if p.get('acc') is not None:
904 sw = self.update_acc(p['acc'])
905 if sw != '9000':
906 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100907
Todd Neal9eeadfc2018-04-25 15:36:29 -0500908class OpenCellsSim(Card):
909 """
910 OpenCellsSim
911
912 """
913
Philipp Maier5a876312019-11-11 11:01:46 +0100914 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500915
916 def __init__(self, ssc):
917 super(OpenCellsSim, self).__init__(ssc)
918 self._adm_chv_num = 0x0A
919
920
921 @classmethod
922 def autodetect(kls, scc):
923 try:
924 # Look for ATR
925 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"):
926 return kls(scc)
927 except:
928 return None
929 return None
930
931
932 def program(self, p):
933 if not p['pin_adm']:
934 raise ValueError("Please provide a PIN-ADM as there is no default one")
935 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
936
937 # select MF
938 r = self._scc.select_file(['3f00'])
939
940 # write EF.ICCID
941 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
942
943 r = self._scc.select_file(['7ff0'])
944
945 # set Ki in proprietary file
946 data, sw = self._scc.update_binary('FF02', p['ki'])
947
948 # set OPC in proprietary file
949 data, sw = self._scc.update_binary('FF01', p['opc'])
950
951 # select DF_GSM
952 r = self._scc.select_file(['7f20'])
953
954 # write EF.IMSI
955 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
956
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200957class WavemobileSim(Card):
958 """
959 WavemobileSim
960
961 """
962
963 name = 'Wavemobile-SIM'
964
965 def __init__(self, ssc):
966 super(WavemobileSim, self).__init__(ssc)
967 self._adm_chv_num = 0x0A
968 self._scc.cla_byte = "00"
969 self._scc.sel_ctrl = "0004" #request an FCP
970
971 @classmethod
972 def autodetect(kls, scc):
973 try:
974 # Look for ATR
975 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"):
976 return kls(scc)
977 except:
978 return None
979 return None
980
981 def program(self, p):
982 if not p['pin_adm']:
983 raise ValueError("Please provide a PIN-ADM as there is no default one")
984 sw = self.verify_adm(h2b(p['pin_adm']))
985 if sw != '9000':
986 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
987
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200988 # EF.ICCID
989 # TODO: Add programming of the ICCID
990 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200991 print("Warning: Programming of the ICCID is not implemented for this type of card.")
992
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200993 # KI (Presumably a propritary file)
994 # TODO: Add programming of KI
995 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200996 print("Warning: Programming of the KI is not implemented for this type of card.")
997
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200998 # OPc (Presumably a propritary file)
999 # TODO: Add programming of OPc
1000 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001001 print("Warning: Programming of the OPc is not implemented for this type of card.")
1002
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001003 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001004 if p.get('smsp'):
1005 sw = self.update_smsp(p['smsp'])
1006 if sw != '9000':
1007 print("Programming SMSP failed with code %s"%sw)
1008
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001009 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001010 if p.get('imsi'):
1011 sw = self.update_imsi(p['imsi'])
1012 if sw != '9000':
1013 print("Programming IMSI failed with code %s"%sw)
1014
1015 # EF.ACC
1016 if p.get('acc'):
1017 sw = self.update_acc(p['acc'])
1018 if sw != '9000':
1019 print("Programming ACC failed with code %s"%sw)
1020
1021 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001022 if p.get('mcc') and p.get('mnc'):
1023 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1024 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001025 print("Programming PLMNsel failed with code %s"%sw)
1026
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001027 # EF.PLMNwAcT
1028 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001029 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1030 if sw != '9000':
1031 print("Programming PLMNwAcT failed with code %s"%sw)
1032
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001033 # EF.OPLMNwAcT
1034 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001035 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1036 if sw != '9000':
1037 print("Programming OPLMNwAcT failed with code %s"%sw)
1038
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001039 # EF.AD
1040 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001041 sw = self.update_ad(p['mnc'])
1042 if sw != '9000':
1043 print("Programming AD failed with code %s"%sw)
1044
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001045 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001046
Todd Neal9eeadfc2018-04-25 15:36:29 -05001047
Harald Welteca673942020-06-03 15:19:40 +02001048class SysmoISIMSJA2(UsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001049 """
1050 sysmocom sysmoISIM-SJA2
1051 """
1052
1053 name = 'sysmoISIM-SJA2'
1054
1055 def __init__(self, ssc):
1056 super(SysmoISIMSJA2, self).__init__(ssc)
1057 self._scc.cla_byte = "00"
1058 self._scc.sel_ctrl = "0004" #request an FCP
1059
1060 @classmethod
1061 def autodetect(kls, scc):
1062 try:
1063 # Try card model #1
1064 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1065 if scc.get_atr() == toBytes(atr):
1066 return kls(scc)
1067
1068 # Try card model #2
1069 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1070 if scc.get_atr() == toBytes(atr):
1071 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001072
1073 # Try card model #3
1074 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1075 if scc.get_atr() == toBytes(atr):
1076 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001077 except:
1078 return None
1079 return None
1080
1081 def program(self, p):
1082 # authenticate as ADM using default key (written on the card..)
1083 if not p['pin_adm']:
1084 raise ValueError("Please provide a PIN-ADM as there is no default one")
1085 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1086
1087 # This type of card does not allow to reprogram the ICCID.
1088 # Reprogramming the ICCID would mess up the card os software
1089 # license management, so the ICCID must be kept at its factory
1090 # setting!
1091 if p.get('iccid'):
1092 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1093
1094 # select DF_GSM
1095 self._scc.select_file(['7f20'])
1096
1097 # write EF.IMSI
1098 if p.get('imsi'):
1099 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1100
1101 # EF.PLMNsel
1102 if p.get('mcc') and p.get('mnc'):
1103 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1104 if sw != '9000':
1105 print("Programming PLMNsel failed with code %s"%sw)
1106
1107 # EF.PLMNwAcT
1108 if p.get('mcc') and p.get('mnc'):
1109 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1110 if sw != '9000':
1111 print("Programming PLMNwAcT failed with code %s"%sw)
1112
1113 # EF.OPLMNwAcT
1114 if p.get('mcc') and p.get('mnc'):
1115 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1116 if sw != '9000':
1117 print("Programming OPLMNwAcT failed with code %s"%sw)
1118
Harald Welte32f0d412020-05-05 17:35:57 +02001119 # EF.HPLMNwAcT
1120 if p.get('mcc') and p.get('mnc'):
1121 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1122 if sw != '9000':
1123 print("Programming HPLMNwAcT failed with code %s"%sw)
1124
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001125 # EF.AD
1126 if p.get('mcc') and p.get('mnc'):
1127 sw = self.update_ad(p['mnc'])
1128 if sw != '9000':
1129 print("Programming AD failed with code %s"%sw)
1130
1131 # EF.SMSP
1132 if p.get('smsp'):
1133 r = self._scc.select_file(['3f00', '7f10'])
1134 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1135
Supreeth Herle80164052020-03-23 12:06:29 +01001136 # Populate AIDs
1137 self.read_aids()
1138
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001139 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1140 # hard linked to EF-USIM_AUTH_KEY)
1141 self._scc.select_file(['3f00'])
1142 self._scc.select_file(['a515'])
1143 if p.get('ki'):
1144 self._scc.update_binary('6f20', p['ki'], 1)
1145 if p.get('opc'):
1146 self._scc.update_binary('6f20', p['opc'], 17)
1147
1148 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001149 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001150 if p.get('ki'):
1151 self._scc.update_binary('af20', p['ki'], 1)
1152 if p.get('opc'):
1153 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001154
herlesupreeth1a13c442020-09-11 21:16:51 +02001155 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001156 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001157 if p.get('ki'):
1158 self._scc.update_binary('af20', p['ki'], 1)
1159 if p.get('opc'):
1160 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001161
Harald Welteca673942020-06-03 15:19:40 +02001162 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001163 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001164 if p.get('mcc') and p.get('mnc'):
1165 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1166 if sw != '9000':
1167 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001168
1169 # update EF.ePDGId in ADF.USIM
1170 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1171 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001172 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001173 if sw != '9000':
1174 print("Programming ePDGId failed with code %s"%sw)
1175
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001176 return
1177
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001178
Todd Neal9eeadfc2018-04-25 15:36:29 -05001179# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001180_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001181 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001182 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001183
1184def card_autodetect(scc):
1185 for kls in _cards_classes:
1186 card = kls.autodetect(scc)
1187 if card is not None:
1188 card.reset()
1189 return card
1190 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001191
1192def card_detect(ctype, scc):
1193 # Detect type if needed
1194 card = None
1195 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1196
1197 if ctype in ("auto", "auto_once"):
1198 for kls in _cards_classes:
1199 card = kls.autodetect(scc)
1200 if card:
1201 print("Autodetected card type: %s" % card.name)
1202 card.reset()
1203 break
1204
1205 if card is None:
1206 print("Autodetection failed")
1207 return None
1208
1209 if ctype == "auto_once":
1210 ctype = card.name
1211
1212 elif ctype in ctypes:
1213 card = ctypes[ctype](scc)
1214
1215 else:
1216 raise ValueError("Unknown card type: %s" % ctype)
1217
1218 return card