blob: d27092d8fdf0d8c0bd2ad691a568d58cc54cfaa1 [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
Supreeth Herle6d66af62020-03-19 12:49:16 +0100184 def read_msisdn(self):
185 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
186 if sw == '9000':
187 return (dec_msisdn(res), sw)
188 else:
189 return (None, sw)
190
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100191 # Read the (full) AID for either ISIM or USIM application
192 def read_aid(self, isim = False):
193
194 # First (known) halves of the AID
195 aid_usim = "a0000000871002"
196 aid_isim = "a0000000871004"
197
198 # Select which one to look for
199 if isim:
200 aid = aid_isim
201 else:
202 aid = aid_usim
203
204 # Find out how many records the EF.DIR has, then go through
205 # all records and try to find the AID we are looking for
206 aid_record_count = self._scc.record_count(['2F00'])
207 for i in range(0, aid_record_count):
208 record = self._scc.read_record(['2F00'], i + 1)
209 if aid in record[0]:
210 aid_len = int(record[0][6:8], 16)
211 return record[0][8:8 + aid_len * 2]
212
213 return None
214
Supreeth Herlee4e98312020-03-18 11:33:14 +0100215 # Fetch all the AIDs present on UICC
216 def read_aids(self):
217 try:
218 # Find out how many records the EF.DIR has
219 # and store all the AIDs in the UICC
220 rec_cnt = self._scc.record_count(['3f00', '2f00'])
221 for i in range(0, rec_cnt):
222 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
223 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
224 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
225 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
226 except Exception as e:
227 print("Can't read AIDs from SIM -- %s" % (str(e),))
228
Sylvain Munaut76504e02010-12-07 00:24:32 +0100229
230class _MagicSimBase(Card):
231 """
232 Theses cards uses several record based EFs to store the provider infos,
233 each possible provider uses a specific record number in each EF. The
234 indexes used are ( where N is the number of providers supported ) :
235 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100236 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100237
238 * 3f00/7f4d/8f0c : Operator Name
239
240 bytes 0-15 : provider name, padded with 0xff
241 byte 16 : length of the provider name
242 byte 17 : 01 for valid records, 00 otherwise
243
244 * 3f00/7f4d/8f0d : Programmable Binary EFs
245
246 * 3f00/7f4d/8f0e : Programmable Record EFs
247
248 """
249
250 @classmethod
251 def autodetect(kls, scc):
252 try:
253 for p, l, t in kls._files.values():
254 if not t:
255 continue
256 if scc.record_size(['3f00', '7f4d', p]) != l:
257 return None
258 except:
259 return None
260
261 return kls(scc)
262
263 def _get_count(self):
264 """
265 Selects the file and returns the total number of entries
266 and entry size
267 """
268 f = self._files['name']
269
270 r = self._scc.select_file(['3f00', '7f4d', f[0]])
271 rec_len = int(r[-1][28:30], 16)
272 tlen = int(r[-1][4:8],16)
273 rec_cnt = (tlen / rec_len) - 1;
274
275 if (rec_cnt < 1) or (rec_len != f[1]):
276 raise RuntimeError('Bad card type')
277
278 return rec_cnt
279
280 def program(self, p):
281 # Go to dir
282 self._scc.select_file(['3f00', '7f4d'])
283
284 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400285 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100286
287 # Operator name ( 3f00/7f4d/8f0c )
288 self._scc.update_record(self._files['name'][0], 2,
289 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
290 )
291
292 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
293 v = ''
294
295 # inline Ki
296 if self._ki_file is None:
297 v += p['ki']
298
299 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400300 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100301
302 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400303 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304
305 # Ki
306 if self._ki_file:
307 v += self._ki_file + '10' + p['ki']
308
309 # PLMN_Sel
310 v+= '6f30' + '18' + rpad(hplmn, 36)
311
Alexander Chemeris21885242013-07-02 16:56:55 +0400312 # ACC
313 # This doesn't work with "fake" SuperSIM cards,
314 # but will hopefully work with real SuperSIMs.
315 if p.get('acc') is not None:
316 v+= '6f78' + '02' + lpad(p['acc'], 4)
317
Sylvain Munaut76504e02010-12-07 00:24:32 +0100318 self._scc.update_record(self._files['b_ef'][0], 1,
319 rpad(v, self._files['b_ef'][1]*2)
320 )
321
322 # SMSP ( 3f00/7f4d/8f0e )
323 # FIXME
324
325 # Write PLMN_Sel forcefully as well
326 r = self._scc.select_file(['3f00', '7f20', '6f30'])
327 tl = int(r[-1][4:8], 16)
328
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400329 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100330 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
331
332 def erase(self):
333 # Dummy
334 df = {}
335 for k, v in self._files.iteritems():
336 ofs = 1
337 fv = v[1] * 'ff'
338 if k == 'name':
339 ofs = 2
340 fv = fv[0:-4] + '0000'
341 df[v[0]] = (fv, ofs)
342
343 # Write
344 for n in range(0,self._get_count()):
345 for k, (msg, ofs) in df.iteritems():
346 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
347
348
349class SuperSim(_MagicSimBase):
350
351 name = 'supersim'
352
353 _files = {
354 'name' : ('8f0c', 18, True),
355 'b_ef' : ('8f0d', 74, True),
356 'r_ef' : ('8f0e', 50, True),
357 }
358
359 _ki_file = None
360
361
362class MagicSim(_MagicSimBase):
363
364 name = 'magicsim'
365
366 _files = {
367 'name' : ('8f0c', 18, True),
368 'b_ef' : ('8f0d', 130, True),
369 'r_ef' : ('8f0e', 102, False),
370 }
371
372 _ki_file = '6f1b'
373
374
375class FakeMagicSim(Card):
376 """
377 Theses cards have a record based EF 3f00/000c that contains the provider
378 informations. See the program method for its format. The records go from
379 1 to N.
380 """
381
382 name = 'fakemagicsim'
383
384 @classmethod
385 def autodetect(kls, scc):
386 try:
387 if scc.record_size(['3f00', '000c']) != 0x5a:
388 return None
389 except:
390 return None
391
392 return kls(scc)
393
394 def _get_infos(self):
395 """
396 Selects the file and returns the total number of entries
397 and entry size
398 """
399
400 r = self._scc.select_file(['3f00', '000c'])
401 rec_len = int(r[-1][28:30], 16)
402 tlen = int(r[-1][4:8],16)
403 rec_cnt = (tlen / rec_len) - 1;
404
405 if (rec_cnt < 1) or (rec_len != 0x5a):
406 raise RuntimeError('Bad card type')
407
408 return rec_cnt, rec_len
409
410 def program(self, p):
411 # Home PLMN
412 r = self._scc.select_file(['3f00', '7f20', '6f30'])
413 tl = int(r[-1][4:8], 16)
414
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400415 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100416 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
417
418 # Get total number of entries and entry size
419 rec_cnt, rec_len = self._get_infos()
420
421 # Set first entry
422 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200423 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200425 enc_iccid(p['iccid']) + # 10b ICCID
426 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
427 p['ki'] + # 16b Ki
428 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100429 )
430 self._scc.update_record('000c', 1, entry)
431
432 def erase(self):
433 # Get total number of entries and entry size
434 rec_cnt, rec_len = self._get_infos()
435
436 # Erase all entries
437 entry = 'ff' * rec_len
438 for i in range(0, rec_cnt):
439 self._scc.update_record('000c', 1+i, entry)
440
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200441
Harald Welte3156d902011-03-22 21:48:19 +0100442class GrcardSim(Card):
443 """
444 Greencard (grcard.cn) HZCOS GSM SIM
445 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
446 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
447 """
448
449 name = 'grcardsim'
450
451 @classmethod
452 def autodetect(kls, scc):
453 return None
454
455 def program(self, p):
456 # We don't really know yet what ADM PIN 4 is about
457 #self._scc.verify_chv(4, h2b("4444444444444444"))
458
459 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100460 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200461 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100462 else:
463 pin = h2b("4444444444444444")
464 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100465
466 # EF.ICCID
467 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400468 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100469
470 # EF.IMSI
471 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400472 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100473
474 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400475 if p.get('acc') is not None:
476 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100477
478 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200479 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200480 r = self._scc.select_file(['3f00', '7f10', '6f42'])
481 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100482
483 # Set the Ki using proprietary command
484 pdu = '80d4020010' + p['ki']
485 data, sw = self._scc._tp.send_apdu(pdu)
486
487 # EF.HPLMN
488 r = self._scc.select_file(['3f00', '7f20', '6f30'])
489 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400490 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100491 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
492
493 # EF.SPN (Service Provider Name)
494 r = self._scc.select_file(['3f00', '7f20', '6f30'])
495 size = int(r[-1][4:8], 16)
496 # FIXME
497
498 # FIXME: EF.MSISDN
499
500 def erase(self):
501 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100502
Harald Weltee10394b2011-12-07 12:34:14 +0100503class SysmoSIMgr1(GrcardSim):
504 """
505 sysmocom sysmoSIM-GR1
506 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
507 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
508 """
509 name = 'sysmosim-gr1'
510
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200511 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200512 def autodetect(kls, scc):
513 try:
514 # Look for ATR
515 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
516 return kls(scc)
517 except:
518 return None
519 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200520
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100521class SysmoUSIMgr1(Card):
522 """
523 sysmocom sysmoUSIM-GR1
524 """
525 name = 'sysmoUSIM-GR1'
526
527 @classmethod
528 def autodetect(kls, scc):
529 # TODO: Access the ATR
530 return None
531
532 def program(self, p):
533 # TODO: check if verify_chv could be used or what it needs
534 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
535 # Unlock the card..
536 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
537
538 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100539 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400540 p['opc'] + # 32b OPC
541 enc_iccid(p['iccid']) + # 10b ICCID
542 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100543 )
544 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
545
546 def erase(self):
547 return
548
Sylvain Munaut053c8952013-07-02 15:12:32 +0200549
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100550class SysmoSIMgr2(Card):
551 """
552 sysmocom sysmoSIM-GR2
553 """
554
555 name = 'sysmoSIM-GR2'
556
557 @classmethod
558 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900559 try:
560 # Look for ATR
561 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
562 return kls(scc)
563 except:
564 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100565 return None
566
567 def program(self, p):
568
569 # select MF
570 r = self._scc.select_file(['3f00'])
571
572 # authenticate as SUPER ADM using default key
573 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
574
575 # set ADM pin using proprietary command
576 # INS: D4
577 # P1: 3A for PIN, 3B for PUK
578 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
579 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100580 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200581 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100582 else:
583 pin = h2b("4444444444444444")
584
585 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100586 data, sw = self._scc._tp.send_apdu(pdu)
587
588 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100589
590 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100591
592 # write EF.ICCID
593 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
594
595 # select DF_GSM
596 r = self._scc.select_file(['7f20'])
597
598 # write EF.IMSI
599 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
600
601 # write EF.ACC
602 if p.get('acc') is not None:
603 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
604
605 # get size and write EF.HPLMN
606 r = self._scc.select_file(['6f30'])
607 size = int(r[-1][4:8], 16)
608 hplmn = enc_plmn(p['mcc'], p['mnc'])
609 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
610
611 # set COMP128 version 0 in proprietary file
612 data, sw = self._scc.update_binary('0001', '001000')
613
614 # set Ki in proprietary file
615 data, sw = self._scc.update_binary('0001', p['ki'], 3)
616
617 # select DF_TELECOM
618 r = self._scc.select_file(['3f00', '7f10'])
619
620 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200621 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200622 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100623
624 def erase(self):
625 return
626
Jan Balke3e840672015-01-26 15:36:27 +0100627class SysmoUSIMSJS1(Card):
628 """
629 sysmocom sysmoUSIM-SJS1
630 """
631
632 name = 'sysmoUSIM-SJS1'
633
634 def __init__(self, ssc):
635 super(SysmoUSIMSJS1, self).__init__(ssc)
636 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100637 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100638
639 @classmethod
640 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900641 try:
642 # Look for ATR
643 if scc.get_atr() == toBytes("3B 9F 96 80 1F C7 80 31 A0 73 BE 21 13 67 43 20 07 18 00 00 01 A5"):
644 return kls(scc)
645 except:
646 return None
Jan Balke3e840672015-01-26 15:36:27 +0100647 return None
648
649 def program(self, p):
650
Philipp Maiere9604882017-03-21 17:24:31 +0100651 # authenticate as ADM using default key (written on the card..)
652 if not p['pin_adm']:
653 raise ValueError("Please provide a PIN-ADM as there is no default one")
654 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100655
656 # select MF
657 r = self._scc.select_file(['3f00'])
658
Philipp Maiere9604882017-03-21 17:24:31 +0100659 # write EF.ICCID
660 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
661
Jan Balke3e840672015-01-26 15:36:27 +0100662 # select DF_GSM
663 r = self._scc.select_file(['7f20'])
664
Jan Balke3e840672015-01-26 15:36:27 +0100665 # set Ki in proprietary file
666 data, sw = self._scc.update_binary('00FF', p['ki'])
667
Philipp Maier1be35bf2018-07-13 11:29:03 +0200668 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200669 if 'opc' in p:
670 content = "01" + p['opc']
671 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100672
Supreeth Herle7947d922019-06-08 07:50:53 +0200673 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100674 if p.get('name') is not None:
675 content = enc_spn(p['name'], True, True)
676 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200677
Supreeth Herlec8796a32019-12-23 12:23:42 +0100678 if p.get('acc') is not None:
679 self.update_acc(p['acc'])
680
Jan Balke3e840672015-01-26 15:36:27 +0100681 # write EF.IMSI
682 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
683
Philipp Maier2d15ea02019-03-20 12:40:36 +0100684 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200685 if p.get('mcc') and p.get('mnc'):
686 sw = self.update_plmnsel(p['mcc'], p['mnc'])
687 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100688 print("Programming PLMNsel failed with code %s"%sw)
689
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200690 # EF.PLMNwAcT
691 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100692 sw = self.update_plmn_act(p['mcc'], p['mnc'])
693 if sw != '9000':
694 print("Programming PLMNwAcT failed with code %s"%sw)
695
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200696 # EF.OPLMNwAcT
697 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100698 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
699 if sw != '9000':
700 print("Programming OPLMNwAcT failed with code %s"%sw)
701
Supreeth Herlef442fb42020-01-21 12:47:32 +0100702 # EF.HPLMNwAcT
703 if p.get('mcc') and p.get('mnc'):
704 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
705 if sw != '9000':
706 print("Programming HPLMNwAcT failed with code %s"%sw)
707
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200708 # EF.AD
709 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100710 sw = self.update_ad(p['mnc'])
711 if sw != '9000':
712 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100713
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200714 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200715 if p.get('smsp'):
716 r = self._scc.select_file(['3f00', '7f10'])
717 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100718
Supreeth Herle5a541012019-12-22 08:59:16 +0100719 # EF.MSISDN
720 # TODO: Alpha Identifier (currently 'ff'O * 20)
721 # TODO: Capability/Configuration1 Record Identifier
722 # TODO: Extension1 Record Identifier
723 if p.get('msisdn') is not None:
724 msisdn = enc_msisdn(p['msisdn'])
725 data = 'ff' * 20 + msisdn + 'ff' * 2
726
727 r = self._scc.select_file(['3f00', '7f10'])
728 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
729
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900730 def erase(self):
731 return
732
733
734class FairwavesSIM(Card):
735 """
736 FairwavesSIM
737
738 The SIM card is operating according to the standard.
739 For Ki/OP/OPC programming the following files are additionally open for writing:
740 3F00/7F20/FF01 – OP/OPC:
741 byte 1 = 0x01, bytes 2-17: OPC;
742 byte 1 = 0x00, bytes 2-17: OP;
743 3F00/7F20/FF02: Ki
744 """
745
Philipp Maier5a876312019-11-11 11:01:46 +0100746 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900747 # Propriatary files
748 _EF_num = {
749 'Ki': 'FF02',
750 'OP/OPC': 'FF01',
751 }
752 _EF = {
753 'Ki': DF['GSM']+[_EF_num['Ki']],
754 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
755 }
756
757 def __init__(self, ssc):
758 super(FairwavesSIM, self).__init__(ssc)
759 self._adm_chv_num = 0x11
760 self._adm2_chv_num = 0x12
761
762
763 @classmethod
764 def autodetect(kls, scc):
765 try:
766 # Look for ATR
767 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"):
768 return kls(scc)
769 except:
770 return None
771 return None
772
773
774 def verify_adm2(self, key):
775 '''
776 Authenticate with ADM2 key.
777
778 Fairwaves SIM cards support hierarchical key structure and ADM2 key
779 is a key which has access to proprietary files (Ki and OP/OPC).
780 That said, ADM key inherits permissions of ADM2 key and thus we rarely
781 need ADM2 key per se.
782 '''
783 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
784 return sw
785
786
787 def read_ki(self):
788 """
789 Read Ki in proprietary file.
790
791 Requires ADM1 access level
792 """
793 return self._scc.read_binary(self._EF['Ki'])
794
795
796 def update_ki(self, ki):
797 """
798 Set Ki in proprietary file.
799
800 Requires ADM1 access level
801 """
802 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
803 return sw
804
805
806 def read_op_opc(self):
807 """
808 Read Ki in proprietary file.
809
810 Requires ADM1 access level
811 """
812 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
813 type = 'OP' if ef[0:2] == '00' else 'OPC'
814 return ((type, ef[2:]), sw)
815
816
817 def update_op(self, op):
818 """
819 Set OP in proprietary file.
820
821 Requires ADM1 access level
822 """
823 content = '00' + op
824 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
825 return sw
826
827
828 def update_opc(self, opc):
829 """
830 Set OPC in proprietary file.
831
832 Requires ADM1 access level
833 """
834 content = '01' + opc
835 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
836 return sw
837
838
839 def program(self, p):
840 # authenticate as ADM1
841 if not p['pin_adm']:
842 raise ValueError("Please provide a PIN-ADM as there is no default one")
843 sw = self.verify_adm(h2b(p['pin_adm']))
844 if sw != '9000':
845 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
846
847 # TODO: Set operator name
848 if p.get('smsp') is not None:
849 sw = self.update_smsp(p['smsp'])
850 if sw != '9000':
851 print("Programming SMSP failed with code %s"%sw)
852 # This SIM doesn't support changing ICCID
853 if p.get('mcc') is not None and p.get('mnc') is not None:
854 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
855 if sw != '9000':
856 print("Programming MCC/MNC failed with code %s"%sw)
857 if p.get('imsi') is not None:
858 sw = self.update_imsi(p['imsi'])
859 if sw != '9000':
860 print("Programming IMSI failed with code %s"%sw)
861 if p.get('ki') is not None:
862 sw = self.update_ki(p['ki'])
863 if sw != '9000':
864 print("Programming Ki failed with code %s"%sw)
865 if p.get('opc') is not None:
866 sw = self.update_opc(p['opc'])
867 if sw != '9000':
868 print("Programming OPC failed with code %s"%sw)
869 if p.get('acc') is not None:
870 sw = self.update_acc(p['acc'])
871 if sw != '9000':
872 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100873
874 def erase(self):
875 return
876
877
Todd Neal9eeadfc2018-04-25 15:36:29 -0500878class OpenCellsSim(Card):
879 """
880 OpenCellsSim
881
882 """
883
Philipp Maier5a876312019-11-11 11:01:46 +0100884 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500885
886 def __init__(self, ssc):
887 super(OpenCellsSim, self).__init__(ssc)
888 self._adm_chv_num = 0x0A
889
890
891 @classmethod
892 def autodetect(kls, scc):
893 try:
894 # Look for ATR
895 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"):
896 return kls(scc)
897 except:
898 return None
899 return None
900
901
902 def program(self, p):
903 if not p['pin_adm']:
904 raise ValueError("Please provide a PIN-ADM as there is no default one")
905 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
906
907 # select MF
908 r = self._scc.select_file(['3f00'])
909
910 # write EF.ICCID
911 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
912
913 r = self._scc.select_file(['7ff0'])
914
915 # set Ki in proprietary file
916 data, sw = self._scc.update_binary('FF02', p['ki'])
917
918 # set OPC in proprietary file
919 data, sw = self._scc.update_binary('FF01', p['opc'])
920
921 # select DF_GSM
922 r = self._scc.select_file(['7f20'])
923
924 # write EF.IMSI
925 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
926
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200927class WavemobileSim(Card):
928 """
929 WavemobileSim
930
931 """
932
933 name = 'Wavemobile-SIM'
934
935 def __init__(self, ssc):
936 super(WavemobileSim, self).__init__(ssc)
937 self._adm_chv_num = 0x0A
938 self._scc.cla_byte = "00"
939 self._scc.sel_ctrl = "0004" #request an FCP
940
941 @classmethod
942 def autodetect(kls, scc):
943 try:
944 # Look for ATR
945 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"):
946 return kls(scc)
947 except:
948 return None
949 return None
950
951 def program(self, p):
952 if not p['pin_adm']:
953 raise ValueError("Please provide a PIN-ADM as there is no default one")
954 sw = self.verify_adm(h2b(p['pin_adm']))
955 if sw != '9000':
956 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
957
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200958 # EF.ICCID
959 # TODO: Add programming of the ICCID
960 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200961 print("Warning: Programming of the ICCID is not implemented for this type of card.")
962
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200963 # KI (Presumably a propritary file)
964 # TODO: Add programming of KI
965 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200966 print("Warning: Programming of the KI is not implemented for this type of card.")
967
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200968 # OPc (Presumably a propritary file)
969 # TODO: Add programming of OPc
970 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200971 print("Warning: Programming of the OPc is not implemented for this type of card.")
972
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200973 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200974 if p.get('smsp'):
975 sw = self.update_smsp(p['smsp'])
976 if sw != '9000':
977 print("Programming SMSP failed with code %s"%sw)
978
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200979 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200980 if p.get('imsi'):
981 sw = self.update_imsi(p['imsi'])
982 if sw != '9000':
983 print("Programming IMSI failed with code %s"%sw)
984
985 # EF.ACC
986 if p.get('acc'):
987 sw = self.update_acc(p['acc'])
988 if sw != '9000':
989 print("Programming ACC failed with code %s"%sw)
990
991 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200992 if p.get('mcc') and p.get('mnc'):
993 sw = self.update_plmnsel(p['mcc'], p['mnc'])
994 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200995 print("Programming PLMNsel failed with code %s"%sw)
996
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200997 # EF.PLMNwAcT
998 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200999 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1000 if sw != '9000':
1001 print("Programming PLMNwAcT failed with code %s"%sw)
1002
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001003 # EF.OPLMNwAcT
1004 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001005 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1006 if sw != '9000':
1007 print("Programming OPLMNwAcT failed with code %s"%sw)
1008
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001009 # EF.AD
1010 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001011 sw = self.update_ad(p['mnc'])
1012 if sw != '9000':
1013 print("Programming AD failed with code %s"%sw)
1014
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001015 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001016
1017 def erase(self):
1018 return
1019
Todd Neal9eeadfc2018-04-25 15:36:29 -05001020
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001021class SysmoISIMSJA2(Card):
1022 """
1023 sysmocom sysmoISIM-SJA2
1024 """
1025
1026 name = 'sysmoISIM-SJA2'
1027
1028 def __init__(self, ssc):
1029 super(SysmoISIMSJA2, self).__init__(ssc)
1030 self._scc.cla_byte = "00"
1031 self._scc.sel_ctrl = "0004" #request an FCP
1032
1033 @classmethod
1034 def autodetect(kls, scc):
1035 try:
1036 # Try card model #1
1037 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1038 if scc.get_atr() == toBytes(atr):
1039 return kls(scc)
1040
1041 # Try card model #2
1042 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1043 if scc.get_atr() == toBytes(atr):
1044 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001045
1046 # Try card model #3
1047 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1048 if scc.get_atr() == toBytes(atr):
1049 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001050 except:
1051 return None
1052 return None
1053
1054 def program(self, p):
1055 # authenticate as ADM using default key (written on the card..)
1056 if not p['pin_adm']:
1057 raise ValueError("Please provide a PIN-ADM as there is no default one")
1058 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1059
1060 # This type of card does not allow to reprogram the ICCID.
1061 # Reprogramming the ICCID would mess up the card os software
1062 # license management, so the ICCID must be kept at its factory
1063 # setting!
1064 if p.get('iccid'):
1065 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1066
1067 # select DF_GSM
1068 self._scc.select_file(['7f20'])
1069
1070 # write EF.IMSI
1071 if p.get('imsi'):
1072 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1073
1074 # EF.PLMNsel
1075 if p.get('mcc') and p.get('mnc'):
1076 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1077 if sw != '9000':
1078 print("Programming PLMNsel failed with code %s"%sw)
1079
1080 # EF.PLMNwAcT
1081 if p.get('mcc') and p.get('mnc'):
1082 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1083 if sw != '9000':
1084 print("Programming PLMNwAcT failed with code %s"%sw)
1085
1086 # EF.OPLMNwAcT
1087 if p.get('mcc') and p.get('mnc'):
1088 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1089 if sw != '9000':
1090 print("Programming OPLMNwAcT failed with code %s"%sw)
1091
1092 # EF.AD
1093 if p.get('mcc') and p.get('mnc'):
1094 sw = self.update_ad(p['mnc'])
1095 if sw != '9000':
1096 print("Programming AD failed with code %s"%sw)
1097
1098 # EF.SMSP
1099 if p.get('smsp'):
1100 r = self._scc.select_file(['3f00', '7f10'])
1101 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1102
1103 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1104 # hard linked to EF-USIM_AUTH_KEY)
1105 self._scc.select_file(['3f00'])
1106 self._scc.select_file(['a515'])
1107 if p.get('ki'):
1108 self._scc.update_binary('6f20', p['ki'], 1)
1109 if p.get('opc'):
1110 self._scc.update_binary('6f20', p['opc'], 17)
1111
1112 # update EF-USIM_AUTH_KEY in ADF.ISIM
1113 self._scc.select_file(['3f00'])
1114 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001115 if (aid):
1116 self._scc.select_adf(aid)
1117 if p.get('ki'):
1118 self._scc.update_binary('af20', p['ki'], 1)
1119 if p.get('opc'):
1120 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001121
1122 # update EF-USIM_AUTH_KEY in ADF.USIM
1123 self._scc.select_file(['3f00'])
1124 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001125 if (aid):
1126 self._scc.select_adf(aid)
1127 if p.get('ki'):
1128 self._scc.update_binary('af20', p['ki'], 1)
1129 if p.get('opc'):
1130 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001131
1132 return
1133
1134 def erase(self):
1135 return
1136
1137
Todd Neal9eeadfc2018-04-25 15:36:29 -05001138# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001139_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001140 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001141 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001142
1143def card_autodetect(scc):
1144 for kls in _cards_classes:
1145 card = kls.autodetect(scc)
1146 if card is not None:
1147 card.reset()
1148 return card
1149 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001150
1151def card_detect(ctype, scc):
1152 # Detect type if needed
1153 card = None
1154 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1155
1156 if ctype in ("auto", "auto_once"):
1157 for kls in _cards_classes:
1158 card = kls.autodetect(scc)
1159 if card:
1160 print("Autodetected card type: %s" % card.name)
1161 card.reset()
1162 break
1163
1164 if card is None:
1165 print("Autodetection failed")
1166 return None
1167
1168 if ctype == "auto_once":
1169 ctype = card.name
1170
1171 elif ctype in ctypes:
1172 card = ctypes[ctype](scc)
1173
1174 else:
1175 raise ValueError("Unknown card type: %s" % ctype)
1176
1177 return card