blob: 7d3b7b4eaa03a58f00723a0ce9e97cd06b378043 [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
99 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
100 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200101 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200102 """
103 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200104 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700105 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200106 hplmn = enc_plmn(mcc, mnc)
107 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700108 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200109 return sw
110
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200111 def update_plmnsel(self, mcc, mnc):
112 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700113 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200114 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200115 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
116 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200117
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300118 def update_smsp(self, smsp):
119 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
120 return sw
121
Philipp Maieree908ae2019-03-21 16:21:12 +0100122 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200123 #See also: 3GPP TS 31.102, chapter 4.2.18
124 mnclen = len(str(mnc))
125 if mnclen == 1:
126 mnclen = 2
127 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100128 raise RuntimeError('unable to calculate proper mnclen')
129
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200130 data = self._scc.read_binary(EF['AD'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700131 size = len(data[0]) // 2
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200132 content = data[0][0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100133 data, sw = self._scc.update_binary(EF['AD'], content)
134 return sw
135
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300136 def read_spn(self):
137 (spn, sw) = self._scc.read_binary(EF['SPN'])
138 if sw == '9000':
139 return (dec_spn(spn), sw)
140 else:
141 return (None, sw)
142
143 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
144 content = enc_spn(name, hplmn_disp, oplmn_disp)
145 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
146 return sw
147
Supreeth Herled21349a2020-04-01 08:37:47 +0200148 def read_binary(self, ef, length=None, offset=0):
149 ef_path = ef in EF and EF[ef] or ef
150 return self._scc.read_binary(ef_path, length, offset)
151
Supreeth Herle98a69272020-03-18 12:14:48 +0100152 def read_gid1(self):
153 (res, sw) = self._scc.read_binary(EF['GID1'])
154 if sw == '9000':
155 return (res, sw)
156 else:
157 return (None, sw)
158
Supreeth Herlec7f2f742020-03-19 12:06:20 +0100159 def read_gid2(self):
160 (res, sw) = self._scc.read_binary(EF['GID2'])
161 if sw == '9000':
162 return (res, sw)
163 else:
164 return (None, sw)
165
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100166 # Read the (full) AID for either ISIM or USIM application
167 def read_aid(self, isim = False):
168
169 # First (known) halves of the AID
170 aid_usim = "a0000000871002"
171 aid_isim = "a0000000871004"
172
173 # Select which one to look for
174 if isim:
175 aid = aid_isim
176 else:
177 aid = aid_usim
178
179 # Find out how many records the EF.DIR has, then go through
180 # all records and try to find the AID we are looking for
181 aid_record_count = self._scc.record_count(['2F00'])
182 for i in range(0, aid_record_count):
183 record = self._scc.read_record(['2F00'], i + 1)
184 if aid in record[0]:
185 aid_len = int(record[0][6:8], 16)
186 return record[0][8:8 + aid_len * 2]
187
188 return None
189
Supreeth Herlee4e98312020-03-18 11:33:14 +0100190 # Fetch all the AIDs present on UICC
191 def read_aids(self):
192 try:
193 # Find out how many records the EF.DIR has
194 # and store all the AIDs in the UICC
195 rec_cnt = self._scc.record_count(['3f00', '2f00'])
196 for i in range(0, rec_cnt):
197 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
198 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
199 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
200 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
201 except Exception as e:
202 print("Can't read AIDs from SIM -- %s" % (str(e),))
203
Sylvain Munaut76504e02010-12-07 00:24:32 +0100204
205class _MagicSimBase(Card):
206 """
207 Theses cards uses several record based EFs to store the provider infos,
208 each possible provider uses a specific record number in each EF. The
209 indexes used are ( where N is the number of providers supported ) :
210 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100211 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100212
213 * 3f00/7f4d/8f0c : Operator Name
214
215 bytes 0-15 : provider name, padded with 0xff
216 byte 16 : length of the provider name
217 byte 17 : 01 for valid records, 00 otherwise
218
219 * 3f00/7f4d/8f0d : Programmable Binary EFs
220
221 * 3f00/7f4d/8f0e : Programmable Record EFs
222
223 """
224
225 @classmethod
226 def autodetect(kls, scc):
227 try:
228 for p, l, t in kls._files.values():
229 if not t:
230 continue
231 if scc.record_size(['3f00', '7f4d', p]) != l:
232 return None
233 except:
234 return None
235
236 return kls(scc)
237
238 def _get_count(self):
239 """
240 Selects the file and returns the total number of entries
241 and entry size
242 """
243 f = self._files['name']
244
245 r = self._scc.select_file(['3f00', '7f4d', f[0]])
246 rec_len = int(r[-1][28:30], 16)
247 tlen = int(r[-1][4:8],16)
248 rec_cnt = (tlen / rec_len) - 1;
249
250 if (rec_cnt < 1) or (rec_len != f[1]):
251 raise RuntimeError('Bad card type')
252
253 return rec_cnt
254
255 def program(self, p):
256 # Go to dir
257 self._scc.select_file(['3f00', '7f4d'])
258
259 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400260 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100261
262 # Operator name ( 3f00/7f4d/8f0c )
263 self._scc.update_record(self._files['name'][0], 2,
264 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
265 )
266
267 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
268 v = ''
269
270 # inline Ki
271 if self._ki_file is None:
272 v += p['ki']
273
274 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400275 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100276
277 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400278 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100279
280 # Ki
281 if self._ki_file:
282 v += self._ki_file + '10' + p['ki']
283
284 # PLMN_Sel
285 v+= '6f30' + '18' + rpad(hplmn, 36)
286
Alexander Chemeris21885242013-07-02 16:56:55 +0400287 # ACC
288 # This doesn't work with "fake" SuperSIM cards,
289 # but will hopefully work with real SuperSIMs.
290 if p.get('acc') is not None:
291 v+= '6f78' + '02' + lpad(p['acc'], 4)
292
Sylvain Munaut76504e02010-12-07 00:24:32 +0100293 self._scc.update_record(self._files['b_ef'][0], 1,
294 rpad(v, self._files['b_ef'][1]*2)
295 )
296
297 # SMSP ( 3f00/7f4d/8f0e )
298 # FIXME
299
300 # Write PLMN_Sel forcefully as well
301 r = self._scc.select_file(['3f00', '7f20', '6f30'])
302 tl = int(r[-1][4:8], 16)
303
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400304 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100305 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
306
307 def erase(self):
308 # Dummy
309 df = {}
310 for k, v in self._files.iteritems():
311 ofs = 1
312 fv = v[1] * 'ff'
313 if k == 'name':
314 ofs = 2
315 fv = fv[0:-4] + '0000'
316 df[v[0]] = (fv, ofs)
317
318 # Write
319 for n in range(0,self._get_count()):
320 for k, (msg, ofs) in df.iteritems():
321 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
322
323
324class SuperSim(_MagicSimBase):
325
326 name = 'supersim'
327
328 _files = {
329 'name' : ('8f0c', 18, True),
330 'b_ef' : ('8f0d', 74, True),
331 'r_ef' : ('8f0e', 50, True),
332 }
333
334 _ki_file = None
335
336
337class MagicSim(_MagicSimBase):
338
339 name = 'magicsim'
340
341 _files = {
342 'name' : ('8f0c', 18, True),
343 'b_ef' : ('8f0d', 130, True),
344 'r_ef' : ('8f0e', 102, False),
345 }
346
347 _ki_file = '6f1b'
348
349
350class FakeMagicSim(Card):
351 """
352 Theses cards have a record based EF 3f00/000c that contains the provider
353 informations. See the program method for its format. The records go from
354 1 to N.
355 """
356
357 name = 'fakemagicsim'
358
359 @classmethod
360 def autodetect(kls, scc):
361 try:
362 if scc.record_size(['3f00', '000c']) != 0x5a:
363 return None
364 except:
365 return None
366
367 return kls(scc)
368
369 def _get_infos(self):
370 """
371 Selects the file and returns the total number of entries
372 and entry size
373 """
374
375 r = self._scc.select_file(['3f00', '000c'])
376 rec_len = int(r[-1][28:30], 16)
377 tlen = int(r[-1][4:8],16)
378 rec_cnt = (tlen / rec_len) - 1;
379
380 if (rec_cnt < 1) or (rec_len != 0x5a):
381 raise RuntimeError('Bad card type')
382
383 return rec_cnt, rec_len
384
385 def program(self, p):
386 # Home PLMN
387 r = self._scc.select_file(['3f00', '7f20', '6f30'])
388 tl = int(r[-1][4:8], 16)
389
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400390 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
392
393 # Get total number of entries and entry size
394 rec_cnt, rec_len = self._get_infos()
395
396 # Set first entry
397 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200398 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100399 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200400 enc_iccid(p['iccid']) + # 10b ICCID
401 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
402 p['ki'] + # 16b Ki
403 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100404 )
405 self._scc.update_record('000c', 1, entry)
406
407 def erase(self):
408 # Get total number of entries and entry size
409 rec_cnt, rec_len = self._get_infos()
410
411 # Erase all entries
412 entry = 'ff' * rec_len
413 for i in range(0, rec_cnt):
414 self._scc.update_record('000c', 1+i, entry)
415
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200416
Harald Welte3156d902011-03-22 21:48:19 +0100417class GrcardSim(Card):
418 """
419 Greencard (grcard.cn) HZCOS GSM SIM
420 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
421 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
422 """
423
424 name = 'grcardsim'
425
426 @classmethod
427 def autodetect(kls, scc):
428 return None
429
430 def program(self, p):
431 # We don't really know yet what ADM PIN 4 is about
432 #self._scc.verify_chv(4, h2b("4444444444444444"))
433
434 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100435 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200436 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100437 else:
438 pin = h2b("4444444444444444")
439 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100440
441 # EF.ICCID
442 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400443 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100444
445 # EF.IMSI
446 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400447 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100448
449 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400450 if p.get('acc') is not None:
451 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100452
453 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200454 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200455 r = self._scc.select_file(['3f00', '7f10', '6f42'])
456 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100457
458 # Set the Ki using proprietary command
459 pdu = '80d4020010' + p['ki']
460 data, sw = self._scc._tp.send_apdu(pdu)
461
462 # EF.HPLMN
463 r = self._scc.select_file(['3f00', '7f20', '6f30'])
464 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400465 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100466 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
467
468 # EF.SPN (Service Provider Name)
469 r = self._scc.select_file(['3f00', '7f20', '6f30'])
470 size = int(r[-1][4:8], 16)
471 # FIXME
472
473 # FIXME: EF.MSISDN
474
475 def erase(self):
476 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100477
Harald Weltee10394b2011-12-07 12:34:14 +0100478class SysmoSIMgr1(GrcardSim):
479 """
480 sysmocom sysmoSIM-GR1
481 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
482 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
483 """
484 name = 'sysmosim-gr1'
485
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200486 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200487 def autodetect(kls, scc):
488 try:
489 # Look for ATR
490 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
491 return kls(scc)
492 except:
493 return None
494 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200495
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100496class SysmoUSIMgr1(Card):
497 """
498 sysmocom sysmoUSIM-GR1
499 """
500 name = 'sysmoUSIM-GR1'
501
502 @classmethod
503 def autodetect(kls, scc):
504 # TODO: Access the ATR
505 return None
506
507 def program(self, p):
508 # TODO: check if verify_chv could be used or what it needs
509 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
510 # Unlock the card..
511 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
512
513 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100514 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400515 p['opc'] + # 32b OPC
516 enc_iccid(p['iccid']) + # 10b ICCID
517 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100518 )
519 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
520
521 def erase(self):
522 return
523
Sylvain Munaut053c8952013-07-02 15:12:32 +0200524
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100525class SysmoSIMgr2(Card):
526 """
527 sysmocom sysmoSIM-GR2
528 """
529
530 name = 'sysmoSIM-GR2'
531
532 @classmethod
533 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900534 try:
535 # Look for ATR
536 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
537 return kls(scc)
538 except:
539 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100540 return None
541
542 def program(self, p):
543
544 # select MF
545 r = self._scc.select_file(['3f00'])
546
547 # authenticate as SUPER ADM using default key
548 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
549
550 # set ADM pin using proprietary command
551 # INS: D4
552 # P1: 3A for PIN, 3B for PUK
553 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
554 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100555 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200556 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100557 else:
558 pin = h2b("4444444444444444")
559
560 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100561 data, sw = self._scc._tp.send_apdu(pdu)
562
563 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100564
565 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100566
567 # write EF.ICCID
568 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
569
570 # select DF_GSM
571 r = self._scc.select_file(['7f20'])
572
573 # write EF.IMSI
574 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
575
576 # write EF.ACC
577 if p.get('acc') is not None:
578 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
579
580 # get size and write EF.HPLMN
581 r = self._scc.select_file(['6f30'])
582 size = int(r[-1][4:8], 16)
583 hplmn = enc_plmn(p['mcc'], p['mnc'])
584 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
585
586 # set COMP128 version 0 in proprietary file
587 data, sw = self._scc.update_binary('0001', '001000')
588
589 # set Ki in proprietary file
590 data, sw = self._scc.update_binary('0001', p['ki'], 3)
591
592 # select DF_TELECOM
593 r = self._scc.select_file(['3f00', '7f10'])
594
595 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200596 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200597 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100598
599 def erase(self):
600 return
601
Jan Balke3e840672015-01-26 15:36:27 +0100602class SysmoUSIMSJS1(Card):
603 """
604 sysmocom sysmoUSIM-SJS1
605 """
606
607 name = 'sysmoUSIM-SJS1'
608
609 def __init__(self, ssc):
610 super(SysmoUSIMSJS1, self).__init__(ssc)
611 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100612 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100613
614 @classmethod
615 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900616 try:
617 # Look for ATR
618 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"):
619 return kls(scc)
620 except:
621 return None
Jan Balke3e840672015-01-26 15:36:27 +0100622 return None
623
624 def program(self, p):
625
Philipp Maiere9604882017-03-21 17:24:31 +0100626 # authenticate as ADM using default key (written on the card..)
627 if not p['pin_adm']:
628 raise ValueError("Please provide a PIN-ADM as there is no default one")
629 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100630
631 # select MF
632 r = self._scc.select_file(['3f00'])
633
Philipp Maiere9604882017-03-21 17:24:31 +0100634 # write EF.ICCID
635 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
636
Jan Balke3e840672015-01-26 15:36:27 +0100637 # select DF_GSM
638 r = self._scc.select_file(['7f20'])
639
Jan Balke3e840672015-01-26 15:36:27 +0100640 # set Ki in proprietary file
641 data, sw = self._scc.update_binary('00FF', p['ki'])
642
Philipp Maier1be35bf2018-07-13 11:29:03 +0200643 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200644 if 'opc' in p:
645 content = "01" + p['opc']
646 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100647
Supreeth Herle7947d922019-06-08 07:50:53 +0200648 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100649 if p.get('name') is not None:
650 content = enc_spn(p['name'], True, True)
651 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200652
Supreeth Herlec8796a32019-12-23 12:23:42 +0100653 if p.get('acc') is not None:
654 self.update_acc(p['acc'])
655
Jan Balke3e840672015-01-26 15:36:27 +0100656 # write EF.IMSI
657 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
658
Philipp Maier2d15ea02019-03-20 12:40:36 +0100659 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200660 if p.get('mcc') and p.get('mnc'):
661 sw = self.update_plmnsel(p['mcc'], p['mnc'])
662 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100663 print("Programming PLMNsel failed with code %s"%sw)
664
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200665 # EF.PLMNwAcT
666 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100667 sw = self.update_plmn_act(p['mcc'], p['mnc'])
668 if sw != '9000':
669 print("Programming PLMNwAcT failed with code %s"%sw)
670
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200671 # EF.OPLMNwAcT
672 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100673 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
674 if sw != '9000':
675 print("Programming OPLMNwAcT failed with code %s"%sw)
676
Supreeth Herlef442fb42020-01-21 12:47:32 +0100677 # EF.HPLMNwAcT
678 if p.get('mcc') and p.get('mnc'):
679 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
680 if sw != '9000':
681 print("Programming HPLMNwAcT failed with code %s"%sw)
682
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200683 # EF.AD
684 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100685 sw = self.update_ad(p['mnc'])
686 if sw != '9000':
687 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100688
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200689 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200690 if p.get('smsp'):
691 r = self._scc.select_file(['3f00', '7f10'])
692 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100693
Supreeth Herle5a541012019-12-22 08:59:16 +0100694 # EF.MSISDN
695 # TODO: Alpha Identifier (currently 'ff'O * 20)
696 # TODO: Capability/Configuration1 Record Identifier
697 # TODO: Extension1 Record Identifier
698 if p.get('msisdn') is not None:
699 msisdn = enc_msisdn(p['msisdn'])
700 data = 'ff' * 20 + msisdn + 'ff' * 2
701
702 r = self._scc.select_file(['3f00', '7f10'])
703 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
704
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900705 def erase(self):
706 return
707
708
709class FairwavesSIM(Card):
710 """
711 FairwavesSIM
712
713 The SIM card is operating according to the standard.
714 For Ki/OP/OPC programming the following files are additionally open for writing:
715 3F00/7F20/FF01 – OP/OPC:
716 byte 1 = 0x01, bytes 2-17: OPC;
717 byte 1 = 0x00, bytes 2-17: OP;
718 3F00/7F20/FF02: Ki
719 """
720
Philipp Maier5a876312019-11-11 11:01:46 +0100721 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900722 # Propriatary files
723 _EF_num = {
724 'Ki': 'FF02',
725 'OP/OPC': 'FF01',
726 }
727 _EF = {
728 'Ki': DF['GSM']+[_EF_num['Ki']],
729 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
730 }
731
732 def __init__(self, ssc):
733 super(FairwavesSIM, self).__init__(ssc)
734 self._adm_chv_num = 0x11
735 self._adm2_chv_num = 0x12
736
737
738 @classmethod
739 def autodetect(kls, scc):
740 try:
741 # Look for ATR
742 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"):
743 return kls(scc)
744 except:
745 return None
746 return None
747
748
749 def verify_adm2(self, key):
750 '''
751 Authenticate with ADM2 key.
752
753 Fairwaves SIM cards support hierarchical key structure and ADM2 key
754 is a key which has access to proprietary files (Ki and OP/OPC).
755 That said, ADM key inherits permissions of ADM2 key and thus we rarely
756 need ADM2 key per se.
757 '''
758 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
759 return sw
760
761
762 def read_ki(self):
763 """
764 Read Ki in proprietary file.
765
766 Requires ADM1 access level
767 """
768 return self._scc.read_binary(self._EF['Ki'])
769
770
771 def update_ki(self, ki):
772 """
773 Set Ki in proprietary file.
774
775 Requires ADM1 access level
776 """
777 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
778 return sw
779
780
781 def read_op_opc(self):
782 """
783 Read Ki in proprietary file.
784
785 Requires ADM1 access level
786 """
787 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
788 type = 'OP' if ef[0:2] == '00' else 'OPC'
789 return ((type, ef[2:]), sw)
790
791
792 def update_op(self, op):
793 """
794 Set OP in proprietary file.
795
796 Requires ADM1 access level
797 """
798 content = '00' + op
799 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
800 return sw
801
802
803 def update_opc(self, opc):
804 """
805 Set OPC in proprietary file.
806
807 Requires ADM1 access level
808 """
809 content = '01' + opc
810 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
811 return sw
812
813
814 def program(self, p):
815 # authenticate as ADM1
816 if not p['pin_adm']:
817 raise ValueError("Please provide a PIN-ADM as there is no default one")
818 sw = self.verify_adm(h2b(p['pin_adm']))
819 if sw != '9000':
820 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
821
822 # TODO: Set operator name
823 if p.get('smsp') is not None:
824 sw = self.update_smsp(p['smsp'])
825 if sw != '9000':
826 print("Programming SMSP failed with code %s"%sw)
827 # This SIM doesn't support changing ICCID
828 if p.get('mcc') is not None and p.get('mnc') is not None:
829 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
830 if sw != '9000':
831 print("Programming MCC/MNC failed with code %s"%sw)
832 if p.get('imsi') is not None:
833 sw = self.update_imsi(p['imsi'])
834 if sw != '9000':
835 print("Programming IMSI failed with code %s"%sw)
836 if p.get('ki') is not None:
837 sw = self.update_ki(p['ki'])
838 if sw != '9000':
839 print("Programming Ki failed with code %s"%sw)
840 if p.get('opc') is not None:
841 sw = self.update_opc(p['opc'])
842 if sw != '9000':
843 print("Programming OPC failed with code %s"%sw)
844 if p.get('acc') is not None:
845 sw = self.update_acc(p['acc'])
846 if sw != '9000':
847 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100848
849 def erase(self):
850 return
851
852
Todd Neal9eeadfc2018-04-25 15:36:29 -0500853class OpenCellsSim(Card):
854 """
855 OpenCellsSim
856
857 """
858
Philipp Maier5a876312019-11-11 11:01:46 +0100859 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500860
861 def __init__(self, ssc):
862 super(OpenCellsSim, self).__init__(ssc)
863 self._adm_chv_num = 0x0A
864
865
866 @classmethod
867 def autodetect(kls, scc):
868 try:
869 # Look for ATR
870 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"):
871 return kls(scc)
872 except:
873 return None
874 return None
875
876
877 def program(self, p):
878 if not p['pin_adm']:
879 raise ValueError("Please provide a PIN-ADM as there is no default one")
880 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
881
882 # select MF
883 r = self._scc.select_file(['3f00'])
884
885 # write EF.ICCID
886 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
887
888 r = self._scc.select_file(['7ff0'])
889
890 # set Ki in proprietary file
891 data, sw = self._scc.update_binary('FF02', p['ki'])
892
893 # set OPC in proprietary file
894 data, sw = self._scc.update_binary('FF01', p['opc'])
895
896 # select DF_GSM
897 r = self._scc.select_file(['7f20'])
898
899 # write EF.IMSI
900 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
901
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200902class WavemobileSim(Card):
903 """
904 WavemobileSim
905
906 """
907
908 name = 'Wavemobile-SIM'
909
910 def __init__(self, ssc):
911 super(WavemobileSim, self).__init__(ssc)
912 self._adm_chv_num = 0x0A
913 self._scc.cla_byte = "00"
914 self._scc.sel_ctrl = "0004" #request an FCP
915
916 @classmethod
917 def autodetect(kls, scc):
918 try:
919 # Look for ATR
920 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"):
921 return kls(scc)
922 except:
923 return None
924 return None
925
926 def program(self, p):
927 if not p['pin_adm']:
928 raise ValueError("Please provide a PIN-ADM as there is no default one")
929 sw = self.verify_adm(h2b(p['pin_adm']))
930 if sw != '9000':
931 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
932
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200933 # EF.ICCID
934 # TODO: Add programming of the ICCID
935 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200936 print("Warning: Programming of the ICCID is not implemented for this type of card.")
937
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200938 # KI (Presumably a propritary file)
939 # TODO: Add programming of KI
940 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200941 print("Warning: Programming of the KI is not implemented for this type of card.")
942
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200943 # OPc (Presumably a propritary file)
944 # TODO: Add programming of OPc
945 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200946 print("Warning: Programming of the OPc is not implemented for this type of card.")
947
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200948 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200949 if p.get('smsp'):
950 sw = self.update_smsp(p['smsp'])
951 if sw != '9000':
952 print("Programming SMSP failed with code %s"%sw)
953
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200954 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200955 if p.get('imsi'):
956 sw = self.update_imsi(p['imsi'])
957 if sw != '9000':
958 print("Programming IMSI failed with code %s"%sw)
959
960 # EF.ACC
961 if p.get('acc'):
962 sw = self.update_acc(p['acc'])
963 if sw != '9000':
964 print("Programming ACC failed with code %s"%sw)
965
966 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200967 if p.get('mcc') and p.get('mnc'):
968 sw = self.update_plmnsel(p['mcc'], p['mnc'])
969 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200970 print("Programming PLMNsel failed with code %s"%sw)
971
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200972 # EF.PLMNwAcT
973 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200974 sw = self.update_plmn_act(p['mcc'], p['mnc'])
975 if sw != '9000':
976 print("Programming PLMNwAcT failed with code %s"%sw)
977
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200978 # EF.OPLMNwAcT
979 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200980 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
981 if sw != '9000':
982 print("Programming OPLMNwAcT failed with code %s"%sw)
983
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200984 # EF.AD
985 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +0200986 sw = self.update_ad(p['mnc'])
987 if sw != '9000':
988 print("Programming AD failed with code %s"%sw)
989
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200990 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200991
992 def erase(self):
993 return
994
Todd Neal9eeadfc2018-04-25 15:36:29 -0500995
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100996class SysmoISIMSJA2(Card):
997 """
998 sysmocom sysmoISIM-SJA2
999 """
1000
1001 name = 'sysmoISIM-SJA2'
1002
1003 def __init__(self, ssc):
1004 super(SysmoISIMSJA2, self).__init__(ssc)
1005 self._scc.cla_byte = "00"
1006 self._scc.sel_ctrl = "0004" #request an FCP
1007
1008 @classmethod
1009 def autodetect(kls, scc):
1010 try:
1011 # Try card model #1
1012 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1013 if scc.get_atr() == toBytes(atr):
1014 return kls(scc)
1015
1016 # Try card model #2
1017 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1018 if scc.get_atr() == toBytes(atr):
1019 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001020
1021 # Try card model #3
1022 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1023 if scc.get_atr() == toBytes(atr):
1024 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001025 except:
1026 return None
1027 return None
1028
1029 def program(self, p):
1030 # authenticate as ADM using default key (written on the card..)
1031 if not p['pin_adm']:
1032 raise ValueError("Please provide a PIN-ADM as there is no default one")
1033 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1034
1035 # This type of card does not allow to reprogram the ICCID.
1036 # Reprogramming the ICCID would mess up the card os software
1037 # license management, so the ICCID must be kept at its factory
1038 # setting!
1039 if p.get('iccid'):
1040 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1041
1042 # select DF_GSM
1043 self._scc.select_file(['7f20'])
1044
1045 # write EF.IMSI
1046 if p.get('imsi'):
1047 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1048
1049 # EF.PLMNsel
1050 if p.get('mcc') and p.get('mnc'):
1051 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1052 if sw != '9000':
1053 print("Programming PLMNsel failed with code %s"%sw)
1054
1055 # EF.PLMNwAcT
1056 if p.get('mcc') and p.get('mnc'):
1057 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1058 if sw != '9000':
1059 print("Programming PLMNwAcT failed with code %s"%sw)
1060
1061 # EF.OPLMNwAcT
1062 if p.get('mcc') and p.get('mnc'):
1063 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1064 if sw != '9000':
1065 print("Programming OPLMNwAcT failed with code %s"%sw)
1066
1067 # EF.AD
1068 if p.get('mcc') and p.get('mnc'):
1069 sw = self.update_ad(p['mnc'])
1070 if sw != '9000':
1071 print("Programming AD failed with code %s"%sw)
1072
1073 # EF.SMSP
1074 if p.get('smsp'):
1075 r = self._scc.select_file(['3f00', '7f10'])
1076 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1077
1078 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1079 # hard linked to EF-USIM_AUTH_KEY)
1080 self._scc.select_file(['3f00'])
1081 self._scc.select_file(['a515'])
1082 if p.get('ki'):
1083 self._scc.update_binary('6f20', p['ki'], 1)
1084 if p.get('opc'):
1085 self._scc.update_binary('6f20', p['opc'], 17)
1086
1087 # update EF-USIM_AUTH_KEY in ADF.ISIM
1088 self._scc.select_file(['3f00'])
1089 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001090 if (aid):
1091 self._scc.select_adf(aid)
1092 if p.get('ki'):
1093 self._scc.update_binary('af20', p['ki'], 1)
1094 if p.get('opc'):
1095 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001096
1097 # update EF-USIM_AUTH_KEY in ADF.USIM
1098 self._scc.select_file(['3f00'])
1099 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001100 if (aid):
1101 self._scc.select_adf(aid)
1102 if p.get('ki'):
1103 self._scc.update_binary('af20', p['ki'], 1)
1104 if p.get('opc'):
1105 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001106
1107 return
1108
1109 def erase(self):
1110 return
1111
1112
Todd Neal9eeadfc2018-04-25 15:36:29 -05001113# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001114_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001115 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001116 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001117
1118def card_autodetect(scc):
1119 for kls in _cards_classes:
1120 card = kls.autodetect(scc)
1121 if card is not None:
1122 card.reset()
1123 return card
1124 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001125
1126def card_detect(ctype, scc):
1127 # Detect type if needed
1128 card = None
1129 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1130
1131 if ctype in ("auto", "auto_once"):
1132 for kls in _cards_classes:
1133 card = kls.autodetect(scc)
1134 if card:
1135 print("Autodetected card type: %s" % card.name)
1136 card.reset()
1137 break
1138
1139 if card is None:
1140 print("Autodetection failed")
1141 return None
1142
1143 if ctype == "auto_once":
1144 ctype = card.name
1145
1146 elif ctype in ctypes:
1147 card = ctypes[ctype](scc)
1148
1149 else:
1150 raise ValueError("Unknown card type: %s" % ctype)
1151
1152 return card