blob: 16f6881c9b40c65f6593d6b3e19706403b57e8d1 [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
27from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090028from smartcard.util import toBytes
Sylvain Munaut76504e02010-12-07 00:24:32 +010029
30class Card(object):
31
32 def __init__(self, scc):
33 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030034 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010035 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010036
Sylvain Munaut76504e02010-12-07 00:24:32 +010037 def reset(self):
38 self._scc.reset_card()
39
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030040 def verify_adm(self, key):
41 '''
42 Authenticate with ADM key
43 '''
44 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
45 return sw
46
47 def read_iccid(self):
48 (res, sw) = self._scc.read_binary(EF['ICCID'])
49 if sw == '9000':
50 return (dec_iccid(res), sw)
51 else:
52 return (None, sw)
53
54 def read_imsi(self):
55 (res, sw) = self._scc.read_binary(EF['IMSI'])
56 if sw == '9000':
57 return (dec_imsi(res), sw)
58 else:
59 return (None, sw)
60
61 def update_imsi(self, imsi):
62 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
63 return sw
64
65 def update_acc(self, acc):
66 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
67 return sw
68
69 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
70 """
71 Update Home PLMN with access technology bit-field
72
73 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
74 in ETSI TS 151 011 for the details of the access_tech field coding.
75 Some common values:
76 access_tech = '0080' # Only GSM is selected
77 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
78 """
79 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +010080 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +070081 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030082 hplmn = enc_plmn(mcc, mnc)
83 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +070084 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030085 return sw
86
Philipp Maierc8ce82a2018-07-04 17:57:20 +020087 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
88 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020089 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +020090 """
91 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020092 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070093 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +020094 hplmn = enc_plmn(mcc, mnc)
95 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +070096 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +020097 return sw
98
Supreeth Herle14084402020-03-19 12:42:10 +010099 def read_plmn_act(self):
100 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
101 if sw == '9000':
102 return (format_xplmn_w_act(res), sw)
103 else:
104 return (None, sw)
105
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200106 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
107 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200108 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200109 """
110 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200111 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700112 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200113 hplmn = enc_plmn(mcc, mnc)
114 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700115 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200116 return sw
117
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200118 def update_plmnsel(self, mcc, mnc):
119 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700120 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200121 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200122 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
123 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200124
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300125 def update_smsp(self, smsp):
126 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
127 return sw
128
Philipp Maieree908ae2019-03-21 16:21:12 +0100129 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200130 #See also: 3GPP TS 31.102, chapter 4.2.18
131 mnclen = len(str(mnc))
132 if mnclen == 1:
133 mnclen = 2
134 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100135 raise RuntimeError('unable to calculate proper mnclen')
136
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200137 data = self._scc.read_binary(EF['AD'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700138 size = len(data[0]) // 2
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200139 content = data[0][0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100140 data, sw = self._scc.update_binary(EF['AD'], content)
141 return sw
142
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300143 def read_spn(self):
144 (spn, sw) = self._scc.read_binary(EF['SPN'])
145 if sw == '9000':
146 return (dec_spn(spn), sw)
147 else:
148 return (None, sw)
149
150 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
151 content = enc_spn(name, hplmn_disp, oplmn_disp)
152 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
153 return sw
154
Supreeth Herled21349a2020-04-01 08:37:47 +0200155 def read_binary(self, ef, length=None, offset=0):
156 ef_path = ef in EF and EF[ef] or ef
157 return self._scc.read_binary(ef_path, length, offset)
158
Supreeth Herlead10d662020-04-01 08:43:08 +0200159 def read_record(self, ef, rec_no):
160 ef_path = ef in EF and EF[ef] or ef
161 return self._scc.read_record(ef_path, rec_no)
162
Supreeth Herle98a69272020-03-18 12:14:48 +0100163 def read_gid1(self):
164 (res, sw) = self._scc.read_binary(EF['GID1'])
165 if sw == '9000':
166 return (res, sw)
167 else:
168 return (None, sw)
169
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100170 # Read the (full) AID for either ISIM or USIM application
171 def read_aid(self, isim = False):
172
173 # First (known) halves of the AID
174 aid_usim = "a0000000871002"
175 aid_isim = "a0000000871004"
176
177 # Select which one to look for
178 if isim:
179 aid = aid_isim
180 else:
181 aid = aid_usim
182
183 # Find out how many records the EF.DIR has, then go through
184 # all records and try to find the AID we are looking for
185 aid_record_count = self._scc.record_count(['2F00'])
186 for i in range(0, aid_record_count):
187 record = self._scc.read_record(['2F00'], i + 1)
188 if aid in record[0]:
189 aid_len = int(record[0][6:8], 16)
190 return record[0][8:8 + aid_len * 2]
191
192 return None
193
Supreeth Herlee4e98312020-03-18 11:33:14 +0100194 # Fetch all the AIDs present on UICC
195 def read_aids(self):
196 try:
197 # Find out how many records the EF.DIR has
198 # and store all the AIDs in the UICC
199 rec_cnt = self._scc.record_count(['3f00', '2f00'])
200 for i in range(0, rec_cnt):
201 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
202 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
203 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
204 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
205 except Exception as e:
206 print("Can't read AIDs from SIM -- %s" % (str(e),))
207
Sylvain Munaut76504e02010-12-07 00:24:32 +0100208
209class _MagicSimBase(Card):
210 """
211 Theses cards uses several record based EFs to store the provider infos,
212 each possible provider uses a specific record number in each EF. The
213 indexes used are ( where N is the number of providers supported ) :
214 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100215 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100216
217 * 3f00/7f4d/8f0c : Operator Name
218
219 bytes 0-15 : provider name, padded with 0xff
220 byte 16 : length of the provider name
221 byte 17 : 01 for valid records, 00 otherwise
222
223 * 3f00/7f4d/8f0d : Programmable Binary EFs
224
225 * 3f00/7f4d/8f0e : Programmable Record EFs
226
227 """
228
229 @classmethod
230 def autodetect(kls, scc):
231 try:
232 for p, l, t in kls._files.values():
233 if not t:
234 continue
235 if scc.record_size(['3f00', '7f4d', p]) != l:
236 return None
237 except:
238 return None
239
240 return kls(scc)
241
242 def _get_count(self):
243 """
244 Selects the file and returns the total number of entries
245 and entry size
246 """
247 f = self._files['name']
248
249 r = self._scc.select_file(['3f00', '7f4d', f[0]])
250 rec_len = int(r[-1][28:30], 16)
251 tlen = int(r[-1][4:8],16)
252 rec_cnt = (tlen / rec_len) - 1;
253
254 if (rec_cnt < 1) or (rec_len != f[1]):
255 raise RuntimeError('Bad card type')
256
257 return rec_cnt
258
259 def program(self, p):
260 # Go to dir
261 self._scc.select_file(['3f00', '7f4d'])
262
263 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400264 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100265
266 # Operator name ( 3f00/7f4d/8f0c )
267 self._scc.update_record(self._files['name'][0], 2,
268 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
269 )
270
271 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
272 v = ''
273
274 # inline Ki
275 if self._ki_file is None:
276 v += p['ki']
277
278 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400279 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100280
281 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400282 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100283
284 # Ki
285 if self._ki_file:
286 v += self._ki_file + '10' + p['ki']
287
288 # PLMN_Sel
289 v+= '6f30' + '18' + rpad(hplmn, 36)
290
Alexander Chemeris21885242013-07-02 16:56:55 +0400291 # ACC
292 # This doesn't work with "fake" SuperSIM cards,
293 # but will hopefully work with real SuperSIMs.
294 if p.get('acc') is not None:
295 v+= '6f78' + '02' + lpad(p['acc'], 4)
296
Sylvain Munaut76504e02010-12-07 00:24:32 +0100297 self._scc.update_record(self._files['b_ef'][0], 1,
298 rpad(v, self._files['b_ef'][1]*2)
299 )
300
301 # SMSP ( 3f00/7f4d/8f0e )
302 # FIXME
303
304 # Write PLMN_Sel forcefully as well
305 r = self._scc.select_file(['3f00', '7f20', '6f30'])
306 tl = int(r[-1][4:8], 16)
307
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400308 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100309 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
310
311 def erase(self):
312 # Dummy
313 df = {}
314 for k, v in self._files.iteritems():
315 ofs = 1
316 fv = v[1] * 'ff'
317 if k == 'name':
318 ofs = 2
319 fv = fv[0:-4] + '0000'
320 df[v[0]] = (fv, ofs)
321
322 # Write
323 for n in range(0,self._get_count()):
324 for k, (msg, ofs) in df.iteritems():
325 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
326
327
328class SuperSim(_MagicSimBase):
329
330 name = 'supersim'
331
332 _files = {
333 'name' : ('8f0c', 18, True),
334 'b_ef' : ('8f0d', 74, True),
335 'r_ef' : ('8f0e', 50, True),
336 }
337
338 _ki_file = None
339
340
341class MagicSim(_MagicSimBase):
342
343 name = 'magicsim'
344
345 _files = {
346 'name' : ('8f0c', 18, True),
347 'b_ef' : ('8f0d', 130, True),
348 'r_ef' : ('8f0e', 102, False),
349 }
350
351 _ki_file = '6f1b'
352
353
354class FakeMagicSim(Card):
355 """
356 Theses cards have a record based EF 3f00/000c that contains the provider
357 informations. See the program method for its format. The records go from
358 1 to N.
359 """
360
361 name = 'fakemagicsim'
362
363 @classmethod
364 def autodetect(kls, scc):
365 try:
366 if scc.record_size(['3f00', '000c']) != 0x5a:
367 return None
368 except:
369 return None
370
371 return kls(scc)
372
373 def _get_infos(self):
374 """
375 Selects the file and returns the total number of entries
376 and entry size
377 """
378
379 r = self._scc.select_file(['3f00', '000c'])
380 rec_len = int(r[-1][28:30], 16)
381 tlen = int(r[-1][4:8],16)
382 rec_cnt = (tlen / rec_len) - 1;
383
384 if (rec_cnt < 1) or (rec_len != 0x5a):
385 raise RuntimeError('Bad card type')
386
387 return rec_cnt, rec_len
388
389 def program(self, p):
390 # Home PLMN
391 r = self._scc.select_file(['3f00', '7f20', '6f30'])
392 tl = int(r[-1][4:8], 16)
393
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400394 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100395 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
396
397 # Get total number of entries and entry size
398 rec_cnt, rec_len = self._get_infos()
399
400 # Set first entry
401 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200402 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100403 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200404 enc_iccid(p['iccid']) + # 10b ICCID
405 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
406 p['ki'] + # 16b Ki
407 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100408 )
409 self._scc.update_record('000c', 1, entry)
410
411 def erase(self):
412 # Get total number of entries and entry size
413 rec_cnt, rec_len = self._get_infos()
414
415 # Erase all entries
416 entry = 'ff' * rec_len
417 for i in range(0, rec_cnt):
418 self._scc.update_record('000c', 1+i, entry)
419
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200420
Harald Welte3156d902011-03-22 21:48:19 +0100421class GrcardSim(Card):
422 """
423 Greencard (grcard.cn) HZCOS GSM SIM
424 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
425 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
426 """
427
428 name = 'grcardsim'
429
430 @classmethod
431 def autodetect(kls, scc):
432 return None
433
434 def program(self, p):
435 # We don't really know yet what ADM PIN 4 is about
436 #self._scc.verify_chv(4, h2b("4444444444444444"))
437
438 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100439 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200440 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100441 else:
442 pin = h2b("4444444444444444")
443 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100444
445 # EF.ICCID
446 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400447 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100448
449 # EF.IMSI
450 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400451 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100452
453 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400454 if p.get('acc') is not None:
455 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100456
457 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200458 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200459 r = self._scc.select_file(['3f00', '7f10', '6f42'])
460 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100461
462 # Set the Ki using proprietary command
463 pdu = '80d4020010' + p['ki']
464 data, sw = self._scc._tp.send_apdu(pdu)
465
466 # EF.HPLMN
467 r = self._scc.select_file(['3f00', '7f20', '6f30'])
468 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400469 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100470 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
471
472 # EF.SPN (Service Provider Name)
473 r = self._scc.select_file(['3f00', '7f20', '6f30'])
474 size = int(r[-1][4:8], 16)
475 # FIXME
476
477 # FIXME: EF.MSISDN
478
479 def erase(self):
480 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100481
Harald Weltee10394b2011-12-07 12:34:14 +0100482class SysmoSIMgr1(GrcardSim):
483 """
484 sysmocom sysmoSIM-GR1
485 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
486 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
487 """
488 name = 'sysmosim-gr1'
489
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200490 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200491 def autodetect(kls, scc):
492 try:
493 # Look for ATR
494 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
495 return kls(scc)
496 except:
497 return None
498 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200499
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100500class SysmoUSIMgr1(Card):
501 """
502 sysmocom sysmoUSIM-GR1
503 """
504 name = 'sysmoUSIM-GR1'
505
506 @classmethod
507 def autodetect(kls, scc):
508 # TODO: Access the ATR
509 return None
510
511 def program(self, p):
512 # TODO: check if verify_chv could be used or what it needs
513 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
514 # Unlock the card..
515 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
516
517 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100518 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400519 p['opc'] + # 32b OPC
520 enc_iccid(p['iccid']) + # 10b ICCID
521 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100522 )
523 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
524
525 def erase(self):
526 return
527
Sylvain Munaut053c8952013-07-02 15:12:32 +0200528
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100529class SysmoSIMgr2(Card):
530 """
531 sysmocom sysmoSIM-GR2
532 """
533
534 name = 'sysmoSIM-GR2'
535
536 @classmethod
537 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900538 try:
539 # Look for ATR
540 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
541 return kls(scc)
542 except:
543 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100544 return None
545
546 def program(self, p):
547
548 # select MF
549 r = self._scc.select_file(['3f00'])
550
551 # authenticate as SUPER ADM using default key
552 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
553
554 # set ADM pin using proprietary command
555 # INS: D4
556 # P1: 3A for PIN, 3B for PUK
557 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
558 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100559 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200560 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100561 else:
562 pin = h2b("4444444444444444")
563
564 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100565 data, sw = self._scc._tp.send_apdu(pdu)
566
567 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100568
569 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100570
571 # write EF.ICCID
572 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
573
574 # select DF_GSM
575 r = self._scc.select_file(['7f20'])
576
577 # write EF.IMSI
578 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
579
580 # write EF.ACC
581 if p.get('acc') is not None:
582 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
583
584 # get size and write EF.HPLMN
585 r = self._scc.select_file(['6f30'])
586 size = int(r[-1][4:8], 16)
587 hplmn = enc_plmn(p['mcc'], p['mnc'])
588 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
589
590 # set COMP128 version 0 in proprietary file
591 data, sw = self._scc.update_binary('0001', '001000')
592
593 # set Ki in proprietary file
594 data, sw = self._scc.update_binary('0001', p['ki'], 3)
595
596 # select DF_TELECOM
597 r = self._scc.select_file(['3f00', '7f10'])
598
599 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200600 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200601 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100602
603 def erase(self):
604 return
605
Jan Balke3e840672015-01-26 15:36:27 +0100606class SysmoUSIMSJS1(Card):
607 """
608 sysmocom sysmoUSIM-SJS1
609 """
610
611 name = 'sysmoUSIM-SJS1'
612
613 def __init__(self, ssc):
614 super(SysmoUSIMSJS1, self).__init__(ssc)
615 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100616 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100617
618 @classmethod
619 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900620 try:
621 # Look for ATR
622 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"):
623 return kls(scc)
624 except:
625 return None
Jan Balke3e840672015-01-26 15:36:27 +0100626 return None
627
628 def program(self, p):
629
Philipp Maiere9604882017-03-21 17:24:31 +0100630 # authenticate as ADM using default key (written on the card..)
631 if not p['pin_adm']:
632 raise ValueError("Please provide a PIN-ADM as there is no default one")
633 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100634
635 # select MF
636 r = self._scc.select_file(['3f00'])
637
Philipp Maiere9604882017-03-21 17:24:31 +0100638 # write EF.ICCID
639 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
640
Jan Balke3e840672015-01-26 15:36:27 +0100641 # select DF_GSM
642 r = self._scc.select_file(['7f20'])
643
Jan Balke3e840672015-01-26 15:36:27 +0100644 # set Ki in proprietary file
645 data, sw = self._scc.update_binary('00FF', p['ki'])
646
Philipp Maier1be35bf2018-07-13 11:29:03 +0200647 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200648 if 'opc' in p:
649 content = "01" + p['opc']
650 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100651
Supreeth Herle7947d922019-06-08 07:50:53 +0200652 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100653 if p.get('name') is not None:
654 content = enc_spn(p['name'], True, True)
655 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200656
Supreeth Herlec8796a32019-12-23 12:23:42 +0100657 if p.get('acc') is not None:
658 self.update_acc(p['acc'])
659
Jan Balke3e840672015-01-26 15:36:27 +0100660 # write EF.IMSI
661 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
662
Philipp Maier2d15ea02019-03-20 12:40:36 +0100663 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200664 if p.get('mcc') and p.get('mnc'):
665 sw = self.update_plmnsel(p['mcc'], p['mnc'])
666 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100667 print("Programming PLMNsel failed with code %s"%sw)
668
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200669 # EF.PLMNwAcT
670 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100671 sw = self.update_plmn_act(p['mcc'], p['mnc'])
672 if sw != '9000':
673 print("Programming PLMNwAcT failed with code %s"%sw)
674
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200675 # EF.OPLMNwAcT
676 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100677 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
678 if sw != '9000':
679 print("Programming OPLMNwAcT failed with code %s"%sw)
680
Supreeth Herlef442fb42020-01-21 12:47:32 +0100681 # EF.HPLMNwAcT
682 if p.get('mcc') and p.get('mnc'):
683 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
684 if sw != '9000':
685 print("Programming HPLMNwAcT failed with code %s"%sw)
686
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200687 # EF.AD
688 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100689 sw = self.update_ad(p['mnc'])
690 if sw != '9000':
691 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100692
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200693 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200694 if p.get('smsp'):
695 r = self._scc.select_file(['3f00', '7f10'])
696 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100697
Supreeth Herle5a541012019-12-22 08:59:16 +0100698 # EF.MSISDN
699 # TODO: Alpha Identifier (currently 'ff'O * 20)
700 # TODO: Capability/Configuration1 Record Identifier
701 # TODO: Extension1 Record Identifier
702 if p.get('msisdn') is not None:
703 msisdn = enc_msisdn(p['msisdn'])
704 data = 'ff' * 20 + msisdn + 'ff' * 2
705
706 r = self._scc.select_file(['3f00', '7f10'])
707 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
708
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900709 def erase(self):
710 return
711
712
713class FairwavesSIM(Card):
714 """
715 FairwavesSIM
716
717 The SIM card is operating according to the standard.
718 For Ki/OP/OPC programming the following files are additionally open for writing:
719 3F00/7F20/FF01 – OP/OPC:
720 byte 1 = 0x01, bytes 2-17: OPC;
721 byte 1 = 0x00, bytes 2-17: OP;
722 3F00/7F20/FF02: Ki
723 """
724
Philipp Maier5a876312019-11-11 11:01:46 +0100725 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900726 # Propriatary files
727 _EF_num = {
728 'Ki': 'FF02',
729 'OP/OPC': 'FF01',
730 }
731 _EF = {
732 'Ki': DF['GSM']+[_EF_num['Ki']],
733 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
734 }
735
736 def __init__(self, ssc):
737 super(FairwavesSIM, self).__init__(ssc)
738 self._adm_chv_num = 0x11
739 self._adm2_chv_num = 0x12
740
741
742 @classmethod
743 def autodetect(kls, scc):
744 try:
745 # Look for ATR
746 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"):
747 return kls(scc)
748 except:
749 return None
750 return None
751
752
753 def verify_adm2(self, key):
754 '''
755 Authenticate with ADM2 key.
756
757 Fairwaves SIM cards support hierarchical key structure and ADM2 key
758 is a key which has access to proprietary files (Ki and OP/OPC).
759 That said, ADM key inherits permissions of ADM2 key and thus we rarely
760 need ADM2 key per se.
761 '''
762 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
763 return sw
764
765
766 def read_ki(self):
767 """
768 Read Ki in proprietary file.
769
770 Requires ADM1 access level
771 """
772 return self._scc.read_binary(self._EF['Ki'])
773
774
775 def update_ki(self, ki):
776 """
777 Set Ki in proprietary file.
778
779 Requires ADM1 access level
780 """
781 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
782 return sw
783
784
785 def read_op_opc(self):
786 """
787 Read Ki in proprietary file.
788
789 Requires ADM1 access level
790 """
791 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
792 type = 'OP' if ef[0:2] == '00' else 'OPC'
793 return ((type, ef[2:]), sw)
794
795
796 def update_op(self, op):
797 """
798 Set OP in proprietary file.
799
800 Requires ADM1 access level
801 """
802 content = '00' + op
803 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
804 return sw
805
806
807 def update_opc(self, opc):
808 """
809 Set OPC in proprietary file.
810
811 Requires ADM1 access level
812 """
813 content = '01' + opc
814 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
815 return sw
816
817
818 def program(self, p):
819 # authenticate as ADM1
820 if not p['pin_adm']:
821 raise ValueError("Please provide a PIN-ADM as there is no default one")
822 sw = self.verify_adm(h2b(p['pin_adm']))
823 if sw != '9000':
824 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
825
826 # TODO: Set operator name
827 if p.get('smsp') is not None:
828 sw = self.update_smsp(p['smsp'])
829 if sw != '9000':
830 print("Programming SMSP failed with code %s"%sw)
831 # This SIM doesn't support changing ICCID
832 if p.get('mcc') is not None and p.get('mnc') is not None:
833 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
834 if sw != '9000':
835 print("Programming MCC/MNC failed with code %s"%sw)
836 if p.get('imsi') is not None:
837 sw = self.update_imsi(p['imsi'])
838 if sw != '9000':
839 print("Programming IMSI failed with code %s"%sw)
840 if p.get('ki') is not None:
841 sw = self.update_ki(p['ki'])
842 if sw != '9000':
843 print("Programming Ki failed with code %s"%sw)
844 if p.get('opc') is not None:
845 sw = self.update_opc(p['opc'])
846 if sw != '9000':
847 print("Programming OPC failed with code %s"%sw)
848 if p.get('acc') is not None:
849 sw = self.update_acc(p['acc'])
850 if sw != '9000':
851 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100852
853 def erase(self):
854 return
855
856
Todd Neal9eeadfc2018-04-25 15:36:29 -0500857class OpenCellsSim(Card):
858 """
859 OpenCellsSim
860
861 """
862
Philipp Maier5a876312019-11-11 11:01:46 +0100863 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500864
865 def __init__(self, ssc):
866 super(OpenCellsSim, self).__init__(ssc)
867 self._adm_chv_num = 0x0A
868
869
870 @classmethod
871 def autodetect(kls, scc):
872 try:
873 # Look for ATR
874 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"):
875 return kls(scc)
876 except:
877 return None
878 return None
879
880
881 def program(self, p):
882 if not p['pin_adm']:
883 raise ValueError("Please provide a PIN-ADM as there is no default one")
884 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
885
886 # select MF
887 r = self._scc.select_file(['3f00'])
888
889 # write EF.ICCID
890 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
891
892 r = self._scc.select_file(['7ff0'])
893
894 # set Ki in proprietary file
895 data, sw = self._scc.update_binary('FF02', p['ki'])
896
897 # set OPC in proprietary file
898 data, sw = self._scc.update_binary('FF01', p['opc'])
899
900 # select DF_GSM
901 r = self._scc.select_file(['7f20'])
902
903 # write EF.IMSI
904 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
905
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200906class WavemobileSim(Card):
907 """
908 WavemobileSim
909
910 """
911
912 name = 'Wavemobile-SIM'
913
914 def __init__(self, ssc):
915 super(WavemobileSim, self).__init__(ssc)
916 self._adm_chv_num = 0x0A
917 self._scc.cla_byte = "00"
918 self._scc.sel_ctrl = "0004" #request an FCP
919
920 @classmethod
921 def autodetect(kls, scc):
922 try:
923 # Look for ATR
924 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"):
925 return kls(scc)
926 except:
927 return None
928 return None
929
930 def program(self, p):
931 if not p['pin_adm']:
932 raise ValueError("Please provide a PIN-ADM as there is no default one")
933 sw = self.verify_adm(h2b(p['pin_adm']))
934 if sw != '9000':
935 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
936
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200937 # EF.ICCID
938 # TODO: Add programming of the ICCID
939 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200940 print("Warning: Programming of the ICCID is not implemented for this type of card.")
941
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200942 # KI (Presumably a propritary file)
943 # TODO: Add programming of KI
944 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200945 print("Warning: Programming of the KI is not implemented for this type of card.")
946
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200947 # OPc (Presumably a propritary file)
948 # TODO: Add programming of OPc
949 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200950 print("Warning: Programming of the OPc is not implemented for this type of card.")
951
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200952 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200953 if p.get('smsp'):
954 sw = self.update_smsp(p['smsp'])
955 if sw != '9000':
956 print("Programming SMSP failed with code %s"%sw)
957
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200958 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200959 if p.get('imsi'):
960 sw = self.update_imsi(p['imsi'])
961 if sw != '9000':
962 print("Programming IMSI failed with code %s"%sw)
963
964 # EF.ACC
965 if p.get('acc'):
966 sw = self.update_acc(p['acc'])
967 if sw != '9000':
968 print("Programming ACC failed with code %s"%sw)
969
970 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200971 if p.get('mcc') and p.get('mnc'):
972 sw = self.update_plmnsel(p['mcc'], p['mnc'])
973 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200974 print("Programming PLMNsel failed with code %s"%sw)
975
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200976 # EF.PLMNwAcT
977 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200978 sw = self.update_plmn_act(p['mcc'], p['mnc'])
979 if sw != '9000':
980 print("Programming PLMNwAcT failed with code %s"%sw)
981
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200982 # EF.OPLMNwAcT
983 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200984 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
985 if sw != '9000':
986 print("Programming OPLMNwAcT failed with code %s"%sw)
987
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200988 # EF.AD
989 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +0200990 sw = self.update_ad(p['mnc'])
991 if sw != '9000':
992 print("Programming AD failed with code %s"%sw)
993
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200994 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200995
996 def erase(self):
997 return
998
Todd Neal9eeadfc2018-04-25 15:36:29 -0500999
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001000class SysmoISIMSJA2(Card):
1001 """
1002 sysmocom sysmoISIM-SJA2
1003 """
1004
1005 name = 'sysmoISIM-SJA2'
1006
1007 def __init__(self, ssc):
1008 super(SysmoISIMSJA2, self).__init__(ssc)
1009 self._scc.cla_byte = "00"
1010 self._scc.sel_ctrl = "0004" #request an FCP
1011
1012 @classmethod
1013 def autodetect(kls, scc):
1014 try:
1015 # Try card model #1
1016 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1017 if scc.get_atr() == toBytes(atr):
1018 return kls(scc)
1019
1020 # Try card model #2
1021 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1022 if scc.get_atr() == toBytes(atr):
1023 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001024
1025 # Try card model #3
1026 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1027 if scc.get_atr() == toBytes(atr):
1028 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001029 except:
1030 return None
1031 return None
1032
1033 def program(self, p):
1034 # authenticate as ADM using default key (written on the card..)
1035 if not p['pin_adm']:
1036 raise ValueError("Please provide a PIN-ADM as there is no default one")
1037 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1038
1039 # This type of card does not allow to reprogram the ICCID.
1040 # Reprogramming the ICCID would mess up the card os software
1041 # license management, so the ICCID must be kept at its factory
1042 # setting!
1043 if p.get('iccid'):
1044 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1045
1046 # select DF_GSM
1047 self._scc.select_file(['7f20'])
1048
1049 # write EF.IMSI
1050 if p.get('imsi'):
1051 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1052
1053 # EF.PLMNsel
1054 if p.get('mcc') and p.get('mnc'):
1055 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1056 if sw != '9000':
1057 print("Programming PLMNsel failed with code %s"%sw)
1058
1059 # EF.PLMNwAcT
1060 if p.get('mcc') and p.get('mnc'):
1061 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1062 if sw != '9000':
1063 print("Programming PLMNwAcT failed with code %s"%sw)
1064
1065 # EF.OPLMNwAcT
1066 if p.get('mcc') and p.get('mnc'):
1067 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1068 if sw != '9000':
1069 print("Programming OPLMNwAcT failed with code %s"%sw)
1070
1071 # EF.AD
1072 if p.get('mcc') and p.get('mnc'):
1073 sw = self.update_ad(p['mnc'])
1074 if sw != '9000':
1075 print("Programming AD failed with code %s"%sw)
1076
1077 # EF.SMSP
1078 if p.get('smsp'):
1079 r = self._scc.select_file(['3f00', '7f10'])
1080 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1081
1082 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1083 # hard linked to EF-USIM_AUTH_KEY)
1084 self._scc.select_file(['3f00'])
1085 self._scc.select_file(['a515'])
1086 if p.get('ki'):
1087 self._scc.update_binary('6f20', p['ki'], 1)
1088 if p.get('opc'):
1089 self._scc.update_binary('6f20', p['opc'], 17)
1090
1091 # update EF-USIM_AUTH_KEY in ADF.ISIM
1092 self._scc.select_file(['3f00'])
1093 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001094 if (aid):
1095 self._scc.select_adf(aid)
1096 if p.get('ki'):
1097 self._scc.update_binary('af20', p['ki'], 1)
1098 if p.get('opc'):
1099 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001100
1101 # update EF-USIM_AUTH_KEY in ADF.USIM
1102 self._scc.select_file(['3f00'])
1103 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001104 if (aid):
1105 self._scc.select_adf(aid)
1106 if p.get('ki'):
1107 self._scc.update_binary('af20', p['ki'], 1)
1108 if p.get('opc'):
1109 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001110
1111 return
1112
1113 def erase(self):
1114 return
1115
1116
Todd Neal9eeadfc2018-04-25 15:36:29 -05001117# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001118_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001119 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001120 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001121
1122def card_autodetect(scc):
1123 for kls in _cards_classes:
1124 card = kls.autodetect(scc)
1125 if card is not None:
1126 card.reset()
1127 return card
1128 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001129
1130def card_detect(ctype, scc):
1131 # Detect type if needed
1132 card = None
1133 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1134
1135 if ctype in ("auto", "auto_once"):
1136 for kls in _cards_classes:
1137 card = kls.autodetect(scc)
1138 if card:
1139 print("Autodetected card type: %s" % card.name)
1140 card.reset()
1141 break
1142
1143 if card is None:
1144 print("Autodetection failed")
1145 return None
1146
1147 if ctype == "auto_once":
1148 ctype = card.name
1149
1150 elif ctype in ctypes:
1151 card = ctypes[ctype](scc)
1152
1153 else:
1154 raise ValueError("Unknown card type: %s" % ctype)
1155
1156 return card