blob: 8081f87b0f87ffbcdcae02732970c70a48c2e3ee [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
Supreeth Herlea850a472020-03-19 12:44:11 +010069 def read_hplmn_act(self):
70 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
71 if sw == '9000':
72 return (format_xplmn_w_act(res), sw)
73 else:
74 return (None, sw)
75
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030076 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
77 """
78 Update Home PLMN with access technology bit-field
79
80 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
81 in ETSI TS 151 011 for the details of the access_tech field coding.
82 Some common values:
83 access_tech = '0080' # Only GSM is selected
84 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
85 """
86 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +010087 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +070088 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030089 hplmn = enc_plmn(mcc, mnc)
90 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +070091 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030092 return sw
93
Supreeth Herle1757b262020-03-19 12:43:11 +010094 def read_oplmn_act(self):
95 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
96 if sw == '9000':
97 return (format_xplmn_w_act(res), sw)
98 else:
99 return (None, sw)
100
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200101 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
102 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200103 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200104 """
105 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200106 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700107 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200108 hplmn = enc_plmn(mcc, mnc)
109 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700110 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200111 return sw
112
Supreeth Herle14084402020-03-19 12:42:10 +0100113 def read_plmn_act(self):
114 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
115 if sw == '9000':
116 return (format_xplmn_w_act(res), sw)
117 else:
118 return (None, sw)
119
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200120 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
121 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200122 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200123 """
124 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200125 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700126 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200127 hplmn = enc_plmn(mcc, mnc)
128 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700129 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200130 return sw
131
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200132 def update_plmnsel(self, mcc, mnc):
133 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700134 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200135 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200136 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
137 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200138
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300139 def update_smsp(self, smsp):
140 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
141 return sw
142
Philipp Maieree908ae2019-03-21 16:21:12 +0100143 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200144 #See also: 3GPP TS 31.102, chapter 4.2.18
145 mnclen = len(str(mnc))
146 if mnclen == 1:
147 mnclen = 2
148 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100149 raise RuntimeError('unable to calculate proper mnclen')
150
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200151 data = self._scc.read_binary(EF['AD'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700152 size = len(data[0]) // 2
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200153 content = data[0][0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100154 data, sw = self._scc.update_binary(EF['AD'], content)
155 return sw
156
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300157 def read_spn(self):
158 (spn, sw) = self._scc.read_binary(EF['SPN'])
159 if sw == '9000':
160 return (dec_spn(spn), sw)
161 else:
162 return (None, sw)
163
164 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
165 content = enc_spn(name, hplmn_disp, oplmn_disp)
166 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
167 return sw
168
Supreeth Herled21349a2020-04-01 08:37:47 +0200169 def read_binary(self, ef, length=None, offset=0):
170 ef_path = ef in EF and EF[ef] or ef
171 return self._scc.read_binary(ef_path, length, offset)
172
Supreeth Herlead10d662020-04-01 08:43:08 +0200173 def read_record(self, ef, rec_no):
174 ef_path = ef in EF and EF[ef] or ef
175 return self._scc.read_record(ef_path, rec_no)
176
Supreeth Herle98a69272020-03-18 12:14:48 +0100177 def read_gid1(self):
178 (res, sw) = self._scc.read_binary(EF['GID1'])
179 if sw == '9000':
180 return (res, sw)
181 else:
182 return (None, sw)
183
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100184 # Read the (full) AID for either ISIM or USIM application
185 def read_aid(self, isim = False):
186
187 # First (known) halves of the AID
188 aid_usim = "a0000000871002"
189 aid_isim = "a0000000871004"
190
191 # Select which one to look for
192 if isim:
193 aid = aid_isim
194 else:
195 aid = aid_usim
196
197 # Find out how many records the EF.DIR has, then go through
198 # all records and try to find the AID we are looking for
199 aid_record_count = self._scc.record_count(['2F00'])
200 for i in range(0, aid_record_count):
201 record = self._scc.read_record(['2F00'], i + 1)
202 if aid in record[0]:
203 aid_len = int(record[0][6:8], 16)
204 return record[0][8:8 + aid_len * 2]
205
206 return None
207
Supreeth Herlee4e98312020-03-18 11:33:14 +0100208 # Fetch all the AIDs present on UICC
209 def read_aids(self):
210 try:
211 # Find out how many records the EF.DIR has
212 # and store all the AIDs in the UICC
213 rec_cnt = self._scc.record_count(['3f00', '2f00'])
214 for i in range(0, rec_cnt):
215 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
216 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
217 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
218 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
219 except Exception as e:
220 print("Can't read AIDs from SIM -- %s" % (str(e),))
221
Sylvain Munaut76504e02010-12-07 00:24:32 +0100222
223class _MagicSimBase(Card):
224 """
225 Theses cards uses several record based EFs to store the provider infos,
226 each possible provider uses a specific record number in each EF. The
227 indexes used are ( where N is the number of providers supported ) :
228 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100229 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100230
231 * 3f00/7f4d/8f0c : Operator Name
232
233 bytes 0-15 : provider name, padded with 0xff
234 byte 16 : length of the provider name
235 byte 17 : 01 for valid records, 00 otherwise
236
237 * 3f00/7f4d/8f0d : Programmable Binary EFs
238
239 * 3f00/7f4d/8f0e : Programmable Record EFs
240
241 """
242
243 @classmethod
244 def autodetect(kls, scc):
245 try:
246 for p, l, t in kls._files.values():
247 if not t:
248 continue
249 if scc.record_size(['3f00', '7f4d', p]) != l:
250 return None
251 except:
252 return None
253
254 return kls(scc)
255
256 def _get_count(self):
257 """
258 Selects the file and returns the total number of entries
259 and entry size
260 """
261 f = self._files['name']
262
263 r = self._scc.select_file(['3f00', '7f4d', f[0]])
264 rec_len = int(r[-1][28:30], 16)
265 tlen = int(r[-1][4:8],16)
266 rec_cnt = (tlen / rec_len) - 1;
267
268 if (rec_cnt < 1) or (rec_len != f[1]):
269 raise RuntimeError('Bad card type')
270
271 return rec_cnt
272
273 def program(self, p):
274 # Go to dir
275 self._scc.select_file(['3f00', '7f4d'])
276
277 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400278 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100279
280 # Operator name ( 3f00/7f4d/8f0c )
281 self._scc.update_record(self._files['name'][0], 2,
282 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
283 )
284
285 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
286 v = ''
287
288 # inline Ki
289 if self._ki_file is None:
290 v += p['ki']
291
292 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400293 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100294
295 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400296 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100297
298 # Ki
299 if self._ki_file:
300 v += self._ki_file + '10' + p['ki']
301
302 # PLMN_Sel
303 v+= '6f30' + '18' + rpad(hplmn, 36)
304
Alexander Chemeris21885242013-07-02 16:56:55 +0400305 # ACC
306 # This doesn't work with "fake" SuperSIM cards,
307 # but will hopefully work with real SuperSIMs.
308 if p.get('acc') is not None:
309 v+= '6f78' + '02' + lpad(p['acc'], 4)
310
Sylvain Munaut76504e02010-12-07 00:24:32 +0100311 self._scc.update_record(self._files['b_ef'][0], 1,
312 rpad(v, self._files['b_ef'][1]*2)
313 )
314
315 # SMSP ( 3f00/7f4d/8f0e )
316 # FIXME
317
318 # Write PLMN_Sel forcefully as well
319 r = self._scc.select_file(['3f00', '7f20', '6f30'])
320 tl = int(r[-1][4:8], 16)
321
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400322 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100323 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
324
325 def erase(self):
326 # Dummy
327 df = {}
328 for k, v in self._files.iteritems():
329 ofs = 1
330 fv = v[1] * 'ff'
331 if k == 'name':
332 ofs = 2
333 fv = fv[0:-4] + '0000'
334 df[v[0]] = (fv, ofs)
335
336 # Write
337 for n in range(0,self._get_count()):
338 for k, (msg, ofs) in df.iteritems():
339 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
340
341
342class SuperSim(_MagicSimBase):
343
344 name = 'supersim'
345
346 _files = {
347 'name' : ('8f0c', 18, True),
348 'b_ef' : ('8f0d', 74, True),
349 'r_ef' : ('8f0e', 50, True),
350 }
351
352 _ki_file = None
353
354
355class MagicSim(_MagicSimBase):
356
357 name = 'magicsim'
358
359 _files = {
360 'name' : ('8f0c', 18, True),
361 'b_ef' : ('8f0d', 130, True),
362 'r_ef' : ('8f0e', 102, False),
363 }
364
365 _ki_file = '6f1b'
366
367
368class FakeMagicSim(Card):
369 """
370 Theses cards have a record based EF 3f00/000c that contains the provider
371 informations. See the program method for its format. The records go from
372 1 to N.
373 """
374
375 name = 'fakemagicsim'
376
377 @classmethod
378 def autodetect(kls, scc):
379 try:
380 if scc.record_size(['3f00', '000c']) != 0x5a:
381 return None
382 except:
383 return None
384
385 return kls(scc)
386
387 def _get_infos(self):
388 """
389 Selects the file and returns the total number of entries
390 and entry size
391 """
392
393 r = self._scc.select_file(['3f00', '000c'])
394 rec_len = int(r[-1][28:30], 16)
395 tlen = int(r[-1][4:8],16)
396 rec_cnt = (tlen / rec_len) - 1;
397
398 if (rec_cnt < 1) or (rec_len != 0x5a):
399 raise RuntimeError('Bad card type')
400
401 return rec_cnt, rec_len
402
403 def program(self, p):
404 # Home PLMN
405 r = self._scc.select_file(['3f00', '7f20', '6f30'])
406 tl = int(r[-1][4:8], 16)
407
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400408 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100409 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
410
411 # Get total number of entries and entry size
412 rec_cnt, rec_len = self._get_infos()
413
414 # Set first entry
415 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200416 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100417 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200418 enc_iccid(p['iccid']) + # 10b ICCID
419 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
420 p['ki'] + # 16b Ki
421 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100422 )
423 self._scc.update_record('000c', 1, entry)
424
425 def erase(self):
426 # Get total number of entries and entry size
427 rec_cnt, rec_len = self._get_infos()
428
429 # Erase all entries
430 entry = 'ff' * rec_len
431 for i in range(0, rec_cnt):
432 self._scc.update_record('000c', 1+i, entry)
433
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200434
Harald Welte3156d902011-03-22 21:48:19 +0100435class GrcardSim(Card):
436 """
437 Greencard (grcard.cn) HZCOS GSM SIM
438 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
439 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
440 """
441
442 name = 'grcardsim'
443
444 @classmethod
445 def autodetect(kls, scc):
446 return None
447
448 def program(self, p):
449 # We don't really know yet what ADM PIN 4 is about
450 #self._scc.verify_chv(4, h2b("4444444444444444"))
451
452 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100453 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200454 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100455 else:
456 pin = h2b("4444444444444444")
457 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100458
459 # EF.ICCID
460 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400461 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100462
463 # EF.IMSI
464 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400465 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100466
467 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400468 if p.get('acc') is not None:
469 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100470
471 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200472 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200473 r = self._scc.select_file(['3f00', '7f10', '6f42'])
474 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100475
476 # Set the Ki using proprietary command
477 pdu = '80d4020010' + p['ki']
478 data, sw = self._scc._tp.send_apdu(pdu)
479
480 # EF.HPLMN
481 r = self._scc.select_file(['3f00', '7f20', '6f30'])
482 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400483 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100484 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
485
486 # EF.SPN (Service Provider Name)
487 r = self._scc.select_file(['3f00', '7f20', '6f30'])
488 size = int(r[-1][4:8], 16)
489 # FIXME
490
491 # FIXME: EF.MSISDN
492
493 def erase(self):
494 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100495
Harald Weltee10394b2011-12-07 12:34:14 +0100496class SysmoSIMgr1(GrcardSim):
497 """
498 sysmocom sysmoSIM-GR1
499 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
500 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
501 """
502 name = 'sysmosim-gr1'
503
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200504 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200505 def autodetect(kls, scc):
506 try:
507 # Look for ATR
508 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
509 return kls(scc)
510 except:
511 return None
512 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200513
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100514class SysmoUSIMgr1(Card):
515 """
516 sysmocom sysmoUSIM-GR1
517 """
518 name = 'sysmoUSIM-GR1'
519
520 @classmethod
521 def autodetect(kls, scc):
522 # TODO: Access the ATR
523 return None
524
525 def program(self, p):
526 # TODO: check if verify_chv could be used or what it needs
527 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
528 # Unlock the card..
529 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
530
531 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100532 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400533 p['opc'] + # 32b OPC
534 enc_iccid(p['iccid']) + # 10b ICCID
535 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100536 )
537 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
538
539 def erase(self):
540 return
541
Sylvain Munaut053c8952013-07-02 15:12:32 +0200542
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100543class SysmoSIMgr2(Card):
544 """
545 sysmocom sysmoSIM-GR2
546 """
547
548 name = 'sysmoSIM-GR2'
549
550 @classmethod
551 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900552 try:
553 # Look for ATR
554 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
555 return kls(scc)
556 except:
557 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100558 return None
559
560 def program(self, p):
561
562 # select MF
563 r = self._scc.select_file(['3f00'])
564
565 # authenticate as SUPER ADM using default key
566 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
567
568 # set ADM pin using proprietary command
569 # INS: D4
570 # P1: 3A for PIN, 3B for PUK
571 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
572 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100573 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200574 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100575 else:
576 pin = h2b("4444444444444444")
577
578 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100579 data, sw = self._scc._tp.send_apdu(pdu)
580
581 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100582
583 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100584
585 # write EF.ICCID
586 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
587
588 # select DF_GSM
589 r = self._scc.select_file(['7f20'])
590
591 # write EF.IMSI
592 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
593
594 # write EF.ACC
595 if p.get('acc') is not None:
596 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
597
598 # get size and write EF.HPLMN
599 r = self._scc.select_file(['6f30'])
600 size = int(r[-1][4:8], 16)
601 hplmn = enc_plmn(p['mcc'], p['mnc'])
602 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
603
604 # set COMP128 version 0 in proprietary file
605 data, sw = self._scc.update_binary('0001', '001000')
606
607 # set Ki in proprietary file
608 data, sw = self._scc.update_binary('0001', p['ki'], 3)
609
610 # select DF_TELECOM
611 r = self._scc.select_file(['3f00', '7f10'])
612
613 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200614 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200615 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100616
617 def erase(self):
618 return
619
Jan Balke3e840672015-01-26 15:36:27 +0100620class SysmoUSIMSJS1(Card):
621 """
622 sysmocom sysmoUSIM-SJS1
623 """
624
625 name = 'sysmoUSIM-SJS1'
626
627 def __init__(self, ssc):
628 super(SysmoUSIMSJS1, self).__init__(ssc)
629 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100630 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100631
632 @classmethod
633 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900634 try:
635 # Look for ATR
636 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"):
637 return kls(scc)
638 except:
639 return None
Jan Balke3e840672015-01-26 15:36:27 +0100640 return None
641
642 def program(self, p):
643
Philipp Maiere9604882017-03-21 17:24:31 +0100644 # authenticate as ADM using default key (written on the card..)
645 if not p['pin_adm']:
646 raise ValueError("Please provide a PIN-ADM as there is no default one")
647 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100648
649 # select MF
650 r = self._scc.select_file(['3f00'])
651
Philipp Maiere9604882017-03-21 17:24:31 +0100652 # write EF.ICCID
653 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
654
Jan Balke3e840672015-01-26 15:36:27 +0100655 # select DF_GSM
656 r = self._scc.select_file(['7f20'])
657
Jan Balke3e840672015-01-26 15:36:27 +0100658 # set Ki in proprietary file
659 data, sw = self._scc.update_binary('00FF', p['ki'])
660
Philipp Maier1be35bf2018-07-13 11:29:03 +0200661 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200662 if 'opc' in p:
663 content = "01" + p['opc']
664 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100665
Supreeth Herle7947d922019-06-08 07:50:53 +0200666 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100667 if p.get('name') is not None:
668 content = enc_spn(p['name'], True, True)
669 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200670
Supreeth Herlec8796a32019-12-23 12:23:42 +0100671 if p.get('acc') is not None:
672 self.update_acc(p['acc'])
673
Jan Balke3e840672015-01-26 15:36:27 +0100674 # write EF.IMSI
675 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
676
Philipp Maier2d15ea02019-03-20 12:40:36 +0100677 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200678 if p.get('mcc') and p.get('mnc'):
679 sw = self.update_plmnsel(p['mcc'], p['mnc'])
680 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100681 print("Programming PLMNsel failed with code %s"%sw)
682
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200683 # EF.PLMNwAcT
684 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100685 sw = self.update_plmn_act(p['mcc'], p['mnc'])
686 if sw != '9000':
687 print("Programming PLMNwAcT failed with code %s"%sw)
688
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200689 # EF.OPLMNwAcT
690 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100691 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
692 if sw != '9000':
693 print("Programming OPLMNwAcT failed with code %s"%sw)
694
Supreeth Herlef442fb42020-01-21 12:47:32 +0100695 # EF.HPLMNwAcT
696 if p.get('mcc') and p.get('mnc'):
697 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
698 if sw != '9000':
699 print("Programming HPLMNwAcT failed with code %s"%sw)
700
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200701 # EF.AD
702 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100703 sw = self.update_ad(p['mnc'])
704 if sw != '9000':
705 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100706
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200707 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200708 if p.get('smsp'):
709 r = self._scc.select_file(['3f00', '7f10'])
710 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100711
Supreeth Herle5a541012019-12-22 08:59:16 +0100712 # EF.MSISDN
713 # TODO: Alpha Identifier (currently 'ff'O * 20)
714 # TODO: Capability/Configuration1 Record Identifier
715 # TODO: Extension1 Record Identifier
716 if p.get('msisdn') is not None:
717 msisdn = enc_msisdn(p['msisdn'])
718 data = 'ff' * 20 + msisdn + 'ff' * 2
719
720 r = self._scc.select_file(['3f00', '7f10'])
721 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
722
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900723 def erase(self):
724 return
725
726
727class FairwavesSIM(Card):
728 """
729 FairwavesSIM
730
731 The SIM card is operating according to the standard.
732 For Ki/OP/OPC programming the following files are additionally open for writing:
733 3F00/7F20/FF01 – OP/OPC:
734 byte 1 = 0x01, bytes 2-17: OPC;
735 byte 1 = 0x00, bytes 2-17: OP;
736 3F00/7F20/FF02: Ki
737 """
738
Philipp Maier5a876312019-11-11 11:01:46 +0100739 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900740 # Propriatary files
741 _EF_num = {
742 'Ki': 'FF02',
743 'OP/OPC': 'FF01',
744 }
745 _EF = {
746 'Ki': DF['GSM']+[_EF_num['Ki']],
747 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
748 }
749
750 def __init__(self, ssc):
751 super(FairwavesSIM, self).__init__(ssc)
752 self._adm_chv_num = 0x11
753 self._adm2_chv_num = 0x12
754
755
756 @classmethod
757 def autodetect(kls, scc):
758 try:
759 # Look for ATR
760 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"):
761 return kls(scc)
762 except:
763 return None
764 return None
765
766
767 def verify_adm2(self, key):
768 '''
769 Authenticate with ADM2 key.
770
771 Fairwaves SIM cards support hierarchical key structure and ADM2 key
772 is a key which has access to proprietary files (Ki and OP/OPC).
773 That said, ADM key inherits permissions of ADM2 key and thus we rarely
774 need ADM2 key per se.
775 '''
776 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
777 return sw
778
779
780 def read_ki(self):
781 """
782 Read Ki in proprietary file.
783
784 Requires ADM1 access level
785 """
786 return self._scc.read_binary(self._EF['Ki'])
787
788
789 def update_ki(self, ki):
790 """
791 Set Ki in proprietary file.
792
793 Requires ADM1 access level
794 """
795 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
796 return sw
797
798
799 def read_op_opc(self):
800 """
801 Read Ki in proprietary file.
802
803 Requires ADM1 access level
804 """
805 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
806 type = 'OP' if ef[0:2] == '00' else 'OPC'
807 return ((type, ef[2:]), sw)
808
809
810 def update_op(self, op):
811 """
812 Set OP in proprietary file.
813
814 Requires ADM1 access level
815 """
816 content = '00' + op
817 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
818 return sw
819
820
821 def update_opc(self, opc):
822 """
823 Set OPC in proprietary file.
824
825 Requires ADM1 access level
826 """
827 content = '01' + opc
828 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
829 return sw
830
831
832 def program(self, p):
833 # authenticate as ADM1
834 if not p['pin_adm']:
835 raise ValueError("Please provide a PIN-ADM as there is no default one")
836 sw = self.verify_adm(h2b(p['pin_adm']))
837 if sw != '9000':
838 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
839
840 # TODO: Set operator name
841 if p.get('smsp') is not None:
842 sw = self.update_smsp(p['smsp'])
843 if sw != '9000':
844 print("Programming SMSP failed with code %s"%sw)
845 # This SIM doesn't support changing ICCID
846 if p.get('mcc') is not None and p.get('mnc') is not None:
847 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
848 if sw != '9000':
849 print("Programming MCC/MNC failed with code %s"%sw)
850 if p.get('imsi') is not None:
851 sw = self.update_imsi(p['imsi'])
852 if sw != '9000':
853 print("Programming IMSI failed with code %s"%sw)
854 if p.get('ki') is not None:
855 sw = self.update_ki(p['ki'])
856 if sw != '9000':
857 print("Programming Ki failed with code %s"%sw)
858 if p.get('opc') is not None:
859 sw = self.update_opc(p['opc'])
860 if sw != '9000':
861 print("Programming OPC failed with code %s"%sw)
862 if p.get('acc') is not None:
863 sw = self.update_acc(p['acc'])
864 if sw != '9000':
865 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100866
867 def erase(self):
868 return
869
870
Todd Neal9eeadfc2018-04-25 15:36:29 -0500871class OpenCellsSim(Card):
872 """
873 OpenCellsSim
874
875 """
876
Philipp Maier5a876312019-11-11 11:01:46 +0100877 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500878
879 def __init__(self, ssc):
880 super(OpenCellsSim, self).__init__(ssc)
881 self._adm_chv_num = 0x0A
882
883
884 @classmethod
885 def autodetect(kls, scc):
886 try:
887 # Look for ATR
888 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"):
889 return kls(scc)
890 except:
891 return None
892 return None
893
894
895 def program(self, p):
896 if not p['pin_adm']:
897 raise ValueError("Please provide a PIN-ADM as there is no default one")
898 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
899
900 # select MF
901 r = self._scc.select_file(['3f00'])
902
903 # write EF.ICCID
904 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
905
906 r = self._scc.select_file(['7ff0'])
907
908 # set Ki in proprietary file
909 data, sw = self._scc.update_binary('FF02', p['ki'])
910
911 # set OPC in proprietary file
912 data, sw = self._scc.update_binary('FF01', p['opc'])
913
914 # select DF_GSM
915 r = self._scc.select_file(['7f20'])
916
917 # write EF.IMSI
918 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
919
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200920class WavemobileSim(Card):
921 """
922 WavemobileSim
923
924 """
925
926 name = 'Wavemobile-SIM'
927
928 def __init__(self, ssc):
929 super(WavemobileSim, self).__init__(ssc)
930 self._adm_chv_num = 0x0A
931 self._scc.cla_byte = "00"
932 self._scc.sel_ctrl = "0004" #request an FCP
933
934 @classmethod
935 def autodetect(kls, scc):
936 try:
937 # Look for ATR
938 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"):
939 return kls(scc)
940 except:
941 return None
942 return None
943
944 def program(self, p):
945 if not p['pin_adm']:
946 raise ValueError("Please provide a PIN-ADM as there is no default one")
947 sw = self.verify_adm(h2b(p['pin_adm']))
948 if sw != '9000':
949 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
950
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200951 # EF.ICCID
952 # TODO: Add programming of the ICCID
953 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200954 print("Warning: Programming of the ICCID is not implemented for this type of card.")
955
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200956 # KI (Presumably a propritary file)
957 # TODO: Add programming of KI
958 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200959 print("Warning: Programming of the KI is not implemented for this type of card.")
960
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200961 # OPc (Presumably a propritary file)
962 # TODO: Add programming of OPc
963 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200964 print("Warning: Programming of the OPc is not implemented for this type of card.")
965
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200966 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200967 if p.get('smsp'):
968 sw = self.update_smsp(p['smsp'])
969 if sw != '9000':
970 print("Programming SMSP failed with code %s"%sw)
971
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200972 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200973 if p.get('imsi'):
974 sw = self.update_imsi(p['imsi'])
975 if sw != '9000':
976 print("Programming IMSI failed with code %s"%sw)
977
978 # EF.ACC
979 if p.get('acc'):
980 sw = self.update_acc(p['acc'])
981 if sw != '9000':
982 print("Programming ACC failed with code %s"%sw)
983
984 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200985 if p.get('mcc') and p.get('mnc'):
986 sw = self.update_plmnsel(p['mcc'], p['mnc'])
987 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200988 print("Programming PLMNsel failed with code %s"%sw)
989
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200990 # EF.PLMNwAcT
991 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200992 sw = self.update_plmn_act(p['mcc'], p['mnc'])
993 if sw != '9000':
994 print("Programming PLMNwAcT failed with code %s"%sw)
995
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200996 # EF.OPLMNwAcT
997 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200998 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
999 if sw != '9000':
1000 print("Programming OPLMNwAcT failed with code %s"%sw)
1001
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001002 # EF.AD
1003 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001004 sw = self.update_ad(p['mnc'])
1005 if sw != '9000':
1006 print("Programming AD failed with code %s"%sw)
1007
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001008 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001009
1010 def erase(self):
1011 return
1012
Todd Neal9eeadfc2018-04-25 15:36:29 -05001013
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001014class SysmoISIMSJA2(Card):
1015 """
1016 sysmocom sysmoISIM-SJA2
1017 """
1018
1019 name = 'sysmoISIM-SJA2'
1020
1021 def __init__(self, ssc):
1022 super(SysmoISIMSJA2, self).__init__(ssc)
1023 self._scc.cla_byte = "00"
1024 self._scc.sel_ctrl = "0004" #request an FCP
1025
1026 @classmethod
1027 def autodetect(kls, scc):
1028 try:
1029 # Try card model #1
1030 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1031 if scc.get_atr() == toBytes(atr):
1032 return kls(scc)
1033
1034 # Try card model #2
1035 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1036 if scc.get_atr() == toBytes(atr):
1037 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001038
1039 # Try card model #3
1040 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1041 if scc.get_atr() == toBytes(atr):
1042 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001043 except:
1044 return None
1045 return None
1046
1047 def program(self, p):
1048 # authenticate as ADM using default key (written on the card..)
1049 if not p['pin_adm']:
1050 raise ValueError("Please provide a PIN-ADM as there is no default one")
1051 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1052
1053 # This type of card does not allow to reprogram the ICCID.
1054 # Reprogramming the ICCID would mess up the card os software
1055 # license management, so the ICCID must be kept at its factory
1056 # setting!
1057 if p.get('iccid'):
1058 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1059
1060 # select DF_GSM
1061 self._scc.select_file(['7f20'])
1062
1063 # write EF.IMSI
1064 if p.get('imsi'):
1065 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1066
1067 # EF.PLMNsel
1068 if p.get('mcc') and p.get('mnc'):
1069 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1070 if sw != '9000':
1071 print("Programming PLMNsel failed with code %s"%sw)
1072
1073 # EF.PLMNwAcT
1074 if p.get('mcc') and p.get('mnc'):
1075 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1076 if sw != '9000':
1077 print("Programming PLMNwAcT failed with code %s"%sw)
1078
1079 # EF.OPLMNwAcT
1080 if p.get('mcc') and p.get('mnc'):
1081 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1082 if sw != '9000':
1083 print("Programming OPLMNwAcT failed with code %s"%sw)
1084
1085 # EF.AD
1086 if p.get('mcc') and p.get('mnc'):
1087 sw = self.update_ad(p['mnc'])
1088 if sw != '9000':
1089 print("Programming AD failed with code %s"%sw)
1090
1091 # EF.SMSP
1092 if p.get('smsp'):
1093 r = self._scc.select_file(['3f00', '7f10'])
1094 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1095
1096 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1097 # hard linked to EF-USIM_AUTH_KEY)
1098 self._scc.select_file(['3f00'])
1099 self._scc.select_file(['a515'])
1100 if p.get('ki'):
1101 self._scc.update_binary('6f20', p['ki'], 1)
1102 if p.get('opc'):
1103 self._scc.update_binary('6f20', p['opc'], 17)
1104
1105 # update EF-USIM_AUTH_KEY in ADF.ISIM
1106 self._scc.select_file(['3f00'])
1107 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001108 if (aid):
1109 self._scc.select_adf(aid)
1110 if p.get('ki'):
1111 self._scc.update_binary('af20', p['ki'], 1)
1112 if p.get('opc'):
1113 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001114
1115 # update EF-USIM_AUTH_KEY in ADF.USIM
1116 self._scc.select_file(['3f00'])
1117 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001118 if (aid):
1119 self._scc.select_adf(aid)
1120 if p.get('ki'):
1121 self._scc.update_binary('af20', p['ki'], 1)
1122 if p.get('opc'):
1123 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001124
1125 return
1126
1127 def erase(self):
1128 return
1129
1130
Todd Neal9eeadfc2018-04-25 15:36:29 -05001131# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001132_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001133 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001134 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001135
1136def card_autodetect(scc):
1137 for kls in _cards_classes:
1138 card = kls.autodetect(scc)
1139 if card is not None:
1140 card.reset()
1141 return card
1142 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001143
1144def card_detect(ctype, scc):
1145 # Detect type if needed
1146 card = None
1147 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1148
1149 if ctype in ("auto", "auto_once"):
1150 for kls in _cards_classes:
1151 card = kls.autodetect(scc)
1152 if card:
1153 print("Autodetected card type: %s" % card.name)
1154 card.reset()
1155 break
1156
1157 if card is None:
1158 print("Autodetection failed")
1159 return None
1160
1161 if ctype == "auto_once":
1162 ctype = card.name
1163
1164 elif ctype in ctypes:
1165 card = ctypes[ctype](scc)
1166
1167 else:
1168 raise ValueError("Unknown card type: %s" % ctype)
1169
1170 return card