blob: a12b1111388b0b25bb724161c312f097a3b0c7b5 [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
Supreeth Herlee26331e2020-03-20 18:50:39 +0100191 # Read SIM Service table
192 def read_sst(self):
193 (res, sw) = self._scc.read_binary(EF['SST'])
194 if sw == '9000':
195 return ((res, parse_st(res)), sw)
196 else:
197 return (None, sw)
198
199 # Read the (full) AID for either ISIM or USIM or ISIM application
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100200 def read_aid(self, isim = False):
201
202 # First (known) halves of the AID
203 aid_usim = "a0000000871002"
204 aid_isim = "a0000000871004"
205
206 # Select which one to look for
207 if isim:
208 aid = aid_isim
209 else:
210 aid = aid_usim
211
212 # Find out how many records the EF.DIR has, then go through
213 # all records and try to find the AID we are looking for
214 aid_record_count = self._scc.record_count(['2F00'])
215 for i in range(0, aid_record_count):
216 record = self._scc.read_record(['2F00'], i + 1)
217 if aid in record[0]:
218 aid_len = int(record[0][6:8], 16)
219 return record[0][8:8 + aid_len * 2]
220
221 return None
222
Supreeth Herlee4e98312020-03-18 11:33:14 +0100223 # Fetch all the AIDs present on UICC
224 def read_aids(self):
225 try:
226 # Find out how many records the EF.DIR has
227 # and store all the AIDs in the UICC
228 rec_cnt = self._scc.record_count(['3f00', '2f00'])
229 for i in range(0, rec_cnt):
230 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
231 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
232 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
233 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
234 except Exception as e:
235 print("Can't read AIDs from SIM -- %s" % (str(e),))
236
Sylvain Munaut76504e02010-12-07 00:24:32 +0100237
238class _MagicSimBase(Card):
239 """
240 Theses cards uses several record based EFs to store the provider infos,
241 each possible provider uses a specific record number in each EF. The
242 indexes used are ( where N is the number of providers supported ) :
243 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100244 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100245
246 * 3f00/7f4d/8f0c : Operator Name
247
248 bytes 0-15 : provider name, padded with 0xff
249 byte 16 : length of the provider name
250 byte 17 : 01 for valid records, 00 otherwise
251
252 * 3f00/7f4d/8f0d : Programmable Binary EFs
253
254 * 3f00/7f4d/8f0e : Programmable Record EFs
255
256 """
257
258 @classmethod
259 def autodetect(kls, scc):
260 try:
261 for p, l, t in kls._files.values():
262 if not t:
263 continue
264 if scc.record_size(['3f00', '7f4d', p]) != l:
265 return None
266 except:
267 return None
268
269 return kls(scc)
270
271 def _get_count(self):
272 """
273 Selects the file and returns the total number of entries
274 and entry size
275 """
276 f = self._files['name']
277
278 r = self._scc.select_file(['3f00', '7f4d', f[0]])
279 rec_len = int(r[-1][28:30], 16)
280 tlen = int(r[-1][4:8],16)
281 rec_cnt = (tlen / rec_len) - 1;
282
283 if (rec_cnt < 1) or (rec_len != f[1]):
284 raise RuntimeError('Bad card type')
285
286 return rec_cnt
287
288 def program(self, p):
289 # Go to dir
290 self._scc.select_file(['3f00', '7f4d'])
291
292 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400293 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100294
295 # Operator name ( 3f00/7f4d/8f0c )
296 self._scc.update_record(self._files['name'][0], 2,
297 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
298 )
299
300 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
301 v = ''
302
303 # inline Ki
304 if self._ki_file is None:
305 v += p['ki']
306
307 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400308 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100309
310 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400311 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100312
313 # Ki
314 if self._ki_file:
315 v += self._ki_file + '10' + p['ki']
316
317 # PLMN_Sel
318 v+= '6f30' + '18' + rpad(hplmn, 36)
319
Alexander Chemeris21885242013-07-02 16:56:55 +0400320 # ACC
321 # This doesn't work with "fake" SuperSIM cards,
322 # but will hopefully work with real SuperSIMs.
323 if p.get('acc') is not None:
324 v+= '6f78' + '02' + lpad(p['acc'], 4)
325
Sylvain Munaut76504e02010-12-07 00:24:32 +0100326 self._scc.update_record(self._files['b_ef'][0], 1,
327 rpad(v, self._files['b_ef'][1]*2)
328 )
329
330 # SMSP ( 3f00/7f4d/8f0e )
331 # FIXME
332
333 # Write PLMN_Sel forcefully as well
334 r = self._scc.select_file(['3f00', '7f20', '6f30'])
335 tl = int(r[-1][4:8], 16)
336
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400337 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100338 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
339
340 def erase(self):
341 # Dummy
342 df = {}
343 for k, v in self._files.iteritems():
344 ofs = 1
345 fv = v[1] * 'ff'
346 if k == 'name':
347 ofs = 2
348 fv = fv[0:-4] + '0000'
349 df[v[0]] = (fv, ofs)
350
351 # Write
352 for n in range(0,self._get_count()):
353 for k, (msg, ofs) in df.iteritems():
354 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
355
356
357class SuperSim(_MagicSimBase):
358
359 name = 'supersim'
360
361 _files = {
362 'name' : ('8f0c', 18, True),
363 'b_ef' : ('8f0d', 74, True),
364 'r_ef' : ('8f0e', 50, True),
365 }
366
367 _ki_file = None
368
369
370class MagicSim(_MagicSimBase):
371
372 name = 'magicsim'
373
374 _files = {
375 'name' : ('8f0c', 18, True),
376 'b_ef' : ('8f0d', 130, True),
377 'r_ef' : ('8f0e', 102, False),
378 }
379
380 _ki_file = '6f1b'
381
382
383class FakeMagicSim(Card):
384 """
385 Theses cards have a record based EF 3f00/000c that contains the provider
386 informations. See the program method for its format. The records go from
387 1 to N.
388 """
389
390 name = 'fakemagicsim'
391
392 @classmethod
393 def autodetect(kls, scc):
394 try:
395 if scc.record_size(['3f00', '000c']) != 0x5a:
396 return None
397 except:
398 return None
399
400 return kls(scc)
401
402 def _get_infos(self):
403 """
404 Selects the file and returns the total number of entries
405 and entry size
406 """
407
408 r = self._scc.select_file(['3f00', '000c'])
409 rec_len = int(r[-1][28:30], 16)
410 tlen = int(r[-1][4:8],16)
411 rec_cnt = (tlen / rec_len) - 1;
412
413 if (rec_cnt < 1) or (rec_len != 0x5a):
414 raise RuntimeError('Bad card type')
415
416 return rec_cnt, rec_len
417
418 def program(self, p):
419 # Home PLMN
420 r = self._scc.select_file(['3f00', '7f20', '6f30'])
421 tl = int(r[-1][4:8], 16)
422
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400423 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
425
426 # Get total number of entries and entry size
427 rec_cnt, rec_len = self._get_infos()
428
429 # Set first entry
430 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200431 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100432 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200433 enc_iccid(p['iccid']) + # 10b ICCID
434 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
435 p['ki'] + # 16b Ki
436 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100437 )
438 self._scc.update_record('000c', 1, entry)
439
440 def erase(self):
441 # Get total number of entries and entry size
442 rec_cnt, rec_len = self._get_infos()
443
444 # Erase all entries
445 entry = 'ff' * rec_len
446 for i in range(0, rec_cnt):
447 self._scc.update_record('000c', 1+i, entry)
448
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200449
Harald Welte3156d902011-03-22 21:48:19 +0100450class GrcardSim(Card):
451 """
452 Greencard (grcard.cn) HZCOS GSM SIM
453 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
454 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
455 """
456
457 name = 'grcardsim'
458
459 @classmethod
460 def autodetect(kls, scc):
461 return None
462
463 def program(self, p):
464 # We don't really know yet what ADM PIN 4 is about
465 #self._scc.verify_chv(4, h2b("4444444444444444"))
466
467 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100468 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200469 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100470 else:
471 pin = h2b("4444444444444444")
472 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100473
474 # EF.ICCID
475 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400476 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100477
478 # EF.IMSI
479 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400480 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100481
482 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400483 if p.get('acc') is not None:
484 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100485
486 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200487 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200488 r = self._scc.select_file(['3f00', '7f10', '6f42'])
489 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100490
491 # Set the Ki using proprietary command
492 pdu = '80d4020010' + p['ki']
493 data, sw = self._scc._tp.send_apdu(pdu)
494
495 # EF.HPLMN
496 r = self._scc.select_file(['3f00', '7f20', '6f30'])
497 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400498 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100499 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
500
501 # EF.SPN (Service Provider Name)
502 r = self._scc.select_file(['3f00', '7f20', '6f30'])
503 size = int(r[-1][4:8], 16)
504 # FIXME
505
506 # FIXME: EF.MSISDN
507
508 def erase(self):
509 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100510
Harald Weltee10394b2011-12-07 12:34:14 +0100511class SysmoSIMgr1(GrcardSim):
512 """
513 sysmocom sysmoSIM-GR1
514 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
515 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
516 """
517 name = 'sysmosim-gr1'
518
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200519 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200520 def autodetect(kls, scc):
521 try:
522 # Look for ATR
523 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
524 return kls(scc)
525 except:
526 return None
527 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200528
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100529class SysmoUSIMgr1(Card):
530 """
531 sysmocom sysmoUSIM-GR1
532 """
533 name = 'sysmoUSIM-GR1'
534
535 @classmethod
536 def autodetect(kls, scc):
537 # TODO: Access the ATR
538 return None
539
540 def program(self, p):
541 # TODO: check if verify_chv could be used or what it needs
542 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
543 # Unlock the card..
544 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
545
546 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100547 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400548 p['opc'] + # 32b OPC
549 enc_iccid(p['iccid']) + # 10b ICCID
550 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100551 )
552 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
553
554 def erase(self):
555 return
556
Sylvain Munaut053c8952013-07-02 15:12:32 +0200557
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100558class SysmoSIMgr2(Card):
559 """
560 sysmocom sysmoSIM-GR2
561 """
562
563 name = 'sysmoSIM-GR2'
564
565 @classmethod
566 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900567 try:
568 # Look for ATR
569 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
570 return kls(scc)
571 except:
572 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100573 return None
574
575 def program(self, p):
576
577 # select MF
578 r = self._scc.select_file(['3f00'])
579
580 # authenticate as SUPER ADM using default key
581 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
582
583 # set ADM pin using proprietary command
584 # INS: D4
585 # P1: 3A for PIN, 3B for PUK
586 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
587 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100588 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200589 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100590 else:
591 pin = h2b("4444444444444444")
592
593 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100594 data, sw = self._scc._tp.send_apdu(pdu)
595
596 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100597
598 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100599
600 # write EF.ICCID
601 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
602
603 # select DF_GSM
604 r = self._scc.select_file(['7f20'])
605
606 # write EF.IMSI
607 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
608
609 # write EF.ACC
610 if p.get('acc') is not None:
611 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
612
613 # get size and write EF.HPLMN
614 r = self._scc.select_file(['6f30'])
615 size = int(r[-1][4:8], 16)
616 hplmn = enc_plmn(p['mcc'], p['mnc'])
617 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
618
619 # set COMP128 version 0 in proprietary file
620 data, sw = self._scc.update_binary('0001', '001000')
621
622 # set Ki in proprietary file
623 data, sw = self._scc.update_binary('0001', p['ki'], 3)
624
625 # select DF_TELECOM
626 r = self._scc.select_file(['3f00', '7f10'])
627
628 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200629 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200630 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100631
632 def erase(self):
633 return
634
Jan Balke3e840672015-01-26 15:36:27 +0100635class SysmoUSIMSJS1(Card):
636 """
637 sysmocom sysmoUSIM-SJS1
638 """
639
640 name = 'sysmoUSIM-SJS1'
641
642 def __init__(self, ssc):
643 super(SysmoUSIMSJS1, self).__init__(ssc)
644 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100645 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100646
647 @classmethod
648 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900649 try:
650 # Look for ATR
651 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"):
652 return kls(scc)
653 except:
654 return None
Jan Balke3e840672015-01-26 15:36:27 +0100655 return None
656
657 def program(self, p):
658
Philipp Maiere9604882017-03-21 17:24:31 +0100659 # authenticate as ADM using default key (written on the card..)
660 if not p['pin_adm']:
661 raise ValueError("Please provide a PIN-ADM as there is no default one")
662 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100663
664 # select MF
665 r = self._scc.select_file(['3f00'])
666
Philipp Maiere9604882017-03-21 17:24:31 +0100667 # write EF.ICCID
668 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
669
Jan Balke3e840672015-01-26 15:36:27 +0100670 # select DF_GSM
671 r = self._scc.select_file(['7f20'])
672
Jan Balke3e840672015-01-26 15:36:27 +0100673 # set Ki in proprietary file
674 data, sw = self._scc.update_binary('00FF', p['ki'])
675
Philipp Maier1be35bf2018-07-13 11:29:03 +0200676 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200677 if 'opc' in p:
678 content = "01" + p['opc']
679 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100680
Supreeth Herle7947d922019-06-08 07:50:53 +0200681 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100682 if p.get('name') is not None:
683 content = enc_spn(p['name'], True, True)
684 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200685
Supreeth Herlec8796a32019-12-23 12:23:42 +0100686 if p.get('acc') is not None:
687 self.update_acc(p['acc'])
688
Jan Balke3e840672015-01-26 15:36:27 +0100689 # write EF.IMSI
690 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
691
Philipp Maier2d15ea02019-03-20 12:40:36 +0100692 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200693 if p.get('mcc') and p.get('mnc'):
694 sw = self.update_plmnsel(p['mcc'], p['mnc'])
695 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100696 print("Programming PLMNsel failed with code %s"%sw)
697
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200698 # EF.PLMNwAcT
699 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100700 sw = self.update_plmn_act(p['mcc'], p['mnc'])
701 if sw != '9000':
702 print("Programming PLMNwAcT failed with code %s"%sw)
703
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200704 # EF.OPLMNwAcT
705 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100706 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
707 if sw != '9000':
708 print("Programming OPLMNwAcT failed with code %s"%sw)
709
Supreeth Herlef442fb42020-01-21 12:47:32 +0100710 # EF.HPLMNwAcT
711 if p.get('mcc') and p.get('mnc'):
712 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
713 if sw != '9000':
714 print("Programming HPLMNwAcT failed with code %s"%sw)
715
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200716 # EF.AD
717 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100718 sw = self.update_ad(p['mnc'])
719 if sw != '9000':
720 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100721
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200722 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200723 if p.get('smsp'):
724 r = self._scc.select_file(['3f00', '7f10'])
725 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100726
Supreeth Herle5a541012019-12-22 08:59:16 +0100727 # EF.MSISDN
728 # TODO: Alpha Identifier (currently 'ff'O * 20)
729 # TODO: Capability/Configuration1 Record Identifier
730 # TODO: Extension1 Record Identifier
731 if p.get('msisdn') is not None:
732 msisdn = enc_msisdn(p['msisdn'])
733 data = 'ff' * 20 + msisdn + 'ff' * 2
734
735 r = self._scc.select_file(['3f00', '7f10'])
736 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
737
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900738 def erase(self):
739 return
740
741
742class FairwavesSIM(Card):
743 """
744 FairwavesSIM
745
746 The SIM card is operating according to the standard.
747 For Ki/OP/OPC programming the following files are additionally open for writing:
748 3F00/7F20/FF01 – OP/OPC:
749 byte 1 = 0x01, bytes 2-17: OPC;
750 byte 1 = 0x00, bytes 2-17: OP;
751 3F00/7F20/FF02: Ki
752 """
753
Philipp Maier5a876312019-11-11 11:01:46 +0100754 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900755 # Propriatary files
756 _EF_num = {
757 'Ki': 'FF02',
758 'OP/OPC': 'FF01',
759 }
760 _EF = {
761 'Ki': DF['GSM']+[_EF_num['Ki']],
762 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
763 }
764
765 def __init__(self, ssc):
766 super(FairwavesSIM, self).__init__(ssc)
767 self._adm_chv_num = 0x11
768 self._adm2_chv_num = 0x12
769
770
771 @classmethod
772 def autodetect(kls, scc):
773 try:
774 # Look for ATR
775 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"):
776 return kls(scc)
777 except:
778 return None
779 return None
780
781
782 def verify_adm2(self, key):
783 '''
784 Authenticate with ADM2 key.
785
786 Fairwaves SIM cards support hierarchical key structure and ADM2 key
787 is a key which has access to proprietary files (Ki and OP/OPC).
788 That said, ADM key inherits permissions of ADM2 key and thus we rarely
789 need ADM2 key per se.
790 '''
791 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
792 return sw
793
794
795 def read_ki(self):
796 """
797 Read Ki in proprietary file.
798
799 Requires ADM1 access level
800 """
801 return self._scc.read_binary(self._EF['Ki'])
802
803
804 def update_ki(self, ki):
805 """
806 Set Ki in proprietary file.
807
808 Requires ADM1 access level
809 """
810 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
811 return sw
812
813
814 def read_op_opc(self):
815 """
816 Read Ki in proprietary file.
817
818 Requires ADM1 access level
819 """
820 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
821 type = 'OP' if ef[0:2] == '00' else 'OPC'
822 return ((type, ef[2:]), sw)
823
824
825 def update_op(self, op):
826 """
827 Set OP in proprietary file.
828
829 Requires ADM1 access level
830 """
831 content = '00' + op
832 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
833 return sw
834
835
836 def update_opc(self, opc):
837 """
838 Set OPC in proprietary file.
839
840 Requires ADM1 access level
841 """
842 content = '01' + opc
843 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
844 return sw
845
846
847 def program(self, p):
848 # authenticate as ADM1
849 if not p['pin_adm']:
850 raise ValueError("Please provide a PIN-ADM as there is no default one")
851 sw = self.verify_adm(h2b(p['pin_adm']))
852 if sw != '9000':
853 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
854
855 # TODO: Set operator name
856 if p.get('smsp') is not None:
857 sw = self.update_smsp(p['smsp'])
858 if sw != '9000':
859 print("Programming SMSP failed with code %s"%sw)
860 # This SIM doesn't support changing ICCID
861 if p.get('mcc') is not None and p.get('mnc') is not None:
862 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
863 if sw != '9000':
864 print("Programming MCC/MNC failed with code %s"%sw)
865 if p.get('imsi') is not None:
866 sw = self.update_imsi(p['imsi'])
867 if sw != '9000':
868 print("Programming IMSI failed with code %s"%sw)
869 if p.get('ki') is not None:
870 sw = self.update_ki(p['ki'])
871 if sw != '9000':
872 print("Programming Ki failed with code %s"%sw)
873 if p.get('opc') is not None:
874 sw = self.update_opc(p['opc'])
875 if sw != '9000':
876 print("Programming OPC failed with code %s"%sw)
877 if p.get('acc') is not None:
878 sw = self.update_acc(p['acc'])
879 if sw != '9000':
880 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100881
882 def erase(self):
883 return
884
885
Todd Neal9eeadfc2018-04-25 15:36:29 -0500886class OpenCellsSim(Card):
887 """
888 OpenCellsSim
889
890 """
891
Philipp Maier5a876312019-11-11 11:01:46 +0100892 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500893
894 def __init__(self, ssc):
895 super(OpenCellsSim, self).__init__(ssc)
896 self._adm_chv_num = 0x0A
897
898
899 @classmethod
900 def autodetect(kls, scc):
901 try:
902 # Look for ATR
903 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"):
904 return kls(scc)
905 except:
906 return None
907 return None
908
909
910 def program(self, p):
911 if not p['pin_adm']:
912 raise ValueError("Please provide a PIN-ADM as there is no default one")
913 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
914
915 # select MF
916 r = self._scc.select_file(['3f00'])
917
918 # write EF.ICCID
919 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
920
921 r = self._scc.select_file(['7ff0'])
922
923 # set Ki in proprietary file
924 data, sw = self._scc.update_binary('FF02', p['ki'])
925
926 # set OPC in proprietary file
927 data, sw = self._scc.update_binary('FF01', p['opc'])
928
929 # select DF_GSM
930 r = self._scc.select_file(['7f20'])
931
932 # write EF.IMSI
933 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
934
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200935class WavemobileSim(Card):
936 """
937 WavemobileSim
938
939 """
940
941 name = 'Wavemobile-SIM'
942
943 def __init__(self, ssc):
944 super(WavemobileSim, self).__init__(ssc)
945 self._adm_chv_num = 0x0A
946 self._scc.cla_byte = "00"
947 self._scc.sel_ctrl = "0004" #request an FCP
948
949 @classmethod
950 def autodetect(kls, scc):
951 try:
952 # Look for ATR
953 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"):
954 return kls(scc)
955 except:
956 return None
957 return None
958
959 def program(self, p):
960 if not p['pin_adm']:
961 raise ValueError("Please provide a PIN-ADM as there is no default one")
962 sw = self.verify_adm(h2b(p['pin_adm']))
963 if sw != '9000':
964 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
965
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200966 # EF.ICCID
967 # TODO: Add programming of the ICCID
968 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200969 print("Warning: Programming of the ICCID is not implemented for this type of card.")
970
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200971 # KI (Presumably a propritary file)
972 # TODO: Add programming of KI
973 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200974 print("Warning: Programming of the KI is not implemented for this type of card.")
975
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200976 # OPc (Presumably a propritary file)
977 # TODO: Add programming of OPc
978 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200979 print("Warning: Programming of the OPc is not implemented for this type of card.")
980
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200981 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200982 if p.get('smsp'):
983 sw = self.update_smsp(p['smsp'])
984 if sw != '9000':
985 print("Programming SMSP failed with code %s"%sw)
986
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200987 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200988 if p.get('imsi'):
989 sw = self.update_imsi(p['imsi'])
990 if sw != '9000':
991 print("Programming IMSI failed with code %s"%sw)
992
993 # EF.ACC
994 if p.get('acc'):
995 sw = self.update_acc(p['acc'])
996 if sw != '9000':
997 print("Programming ACC failed with code %s"%sw)
998
999 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001000 if p.get('mcc') and p.get('mnc'):
1001 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1002 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001003 print("Programming PLMNsel failed with code %s"%sw)
1004
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001005 # EF.PLMNwAcT
1006 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001007 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1008 if sw != '9000':
1009 print("Programming PLMNwAcT failed with code %s"%sw)
1010
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001011 # EF.OPLMNwAcT
1012 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001013 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1014 if sw != '9000':
1015 print("Programming OPLMNwAcT failed with code %s"%sw)
1016
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001017 # EF.AD
1018 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001019 sw = self.update_ad(p['mnc'])
1020 if sw != '9000':
1021 print("Programming AD failed with code %s"%sw)
1022
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001023 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001024
1025 def erase(self):
1026 return
1027
Todd Neal9eeadfc2018-04-25 15:36:29 -05001028
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001029class SysmoISIMSJA2(Card):
1030 """
1031 sysmocom sysmoISIM-SJA2
1032 """
1033
1034 name = 'sysmoISIM-SJA2'
1035
1036 def __init__(self, ssc):
1037 super(SysmoISIMSJA2, self).__init__(ssc)
1038 self._scc.cla_byte = "00"
1039 self._scc.sel_ctrl = "0004" #request an FCP
1040
1041 @classmethod
1042 def autodetect(kls, scc):
1043 try:
1044 # Try card model #1
1045 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1046 if scc.get_atr() == toBytes(atr):
1047 return kls(scc)
1048
1049 # Try card model #2
1050 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1051 if scc.get_atr() == toBytes(atr):
1052 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001053
1054 # Try card model #3
1055 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1056 if scc.get_atr() == toBytes(atr):
1057 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001058 except:
1059 return None
1060 return None
1061
1062 def program(self, p):
1063 # authenticate as ADM using default key (written on the card..)
1064 if not p['pin_adm']:
1065 raise ValueError("Please provide a PIN-ADM as there is no default one")
1066 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1067
1068 # This type of card does not allow to reprogram the ICCID.
1069 # Reprogramming the ICCID would mess up the card os software
1070 # license management, so the ICCID must be kept at its factory
1071 # setting!
1072 if p.get('iccid'):
1073 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1074
1075 # select DF_GSM
1076 self._scc.select_file(['7f20'])
1077
1078 # write EF.IMSI
1079 if p.get('imsi'):
1080 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1081
1082 # EF.PLMNsel
1083 if p.get('mcc') and p.get('mnc'):
1084 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1085 if sw != '9000':
1086 print("Programming PLMNsel failed with code %s"%sw)
1087
1088 # EF.PLMNwAcT
1089 if p.get('mcc') and p.get('mnc'):
1090 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1091 if sw != '9000':
1092 print("Programming PLMNwAcT failed with code %s"%sw)
1093
1094 # EF.OPLMNwAcT
1095 if p.get('mcc') and p.get('mnc'):
1096 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1097 if sw != '9000':
1098 print("Programming OPLMNwAcT failed with code %s"%sw)
1099
1100 # EF.AD
1101 if p.get('mcc') and p.get('mnc'):
1102 sw = self.update_ad(p['mnc'])
1103 if sw != '9000':
1104 print("Programming AD failed with code %s"%sw)
1105
1106 # EF.SMSP
1107 if p.get('smsp'):
1108 r = self._scc.select_file(['3f00', '7f10'])
1109 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1110
1111 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1112 # hard linked to EF-USIM_AUTH_KEY)
1113 self._scc.select_file(['3f00'])
1114 self._scc.select_file(['a515'])
1115 if p.get('ki'):
1116 self._scc.update_binary('6f20', p['ki'], 1)
1117 if p.get('opc'):
1118 self._scc.update_binary('6f20', p['opc'], 17)
1119
1120 # update EF-USIM_AUTH_KEY in ADF.ISIM
1121 self._scc.select_file(['3f00'])
1122 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001123 if (aid):
1124 self._scc.select_adf(aid)
1125 if p.get('ki'):
1126 self._scc.update_binary('af20', p['ki'], 1)
1127 if p.get('opc'):
1128 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001129
1130 # update EF-USIM_AUTH_KEY in ADF.USIM
1131 self._scc.select_file(['3f00'])
1132 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001133 if (aid):
1134 self._scc.select_adf(aid)
1135 if p.get('ki'):
1136 self._scc.update_binary('af20', p['ki'], 1)
1137 if p.get('opc'):
1138 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001139
1140 return
1141
1142 def erase(self):
1143 return
1144
1145
Todd Neal9eeadfc2018-04-25 15:36:29 -05001146# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001147_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001148 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001149 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001150
1151def card_autodetect(scc):
1152 for kls in _cards_classes:
1153 card = kls.autodetect(scc)
1154 if card is not None:
1155 card.reset()
1156 return card
1157 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001158
1159def card_detect(ctype, scc):
1160 # Detect type if needed
1161 card = None
1162 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1163
1164 if ctype in ("auto", "auto_once"):
1165 for kls in _cards_classes:
1166 card = kls.autodetect(scc)
1167 if card:
1168 print("Autodetected card type: %s" % card.name)
1169 card.reset()
1170 break
1171
1172 if card is None:
1173 print("Autodetection failed")
1174 return None
1175
1176 if ctype == "auto_once":
1177 ctype = card.name
1178
1179 elif ctype in ctypes:
1180 card = ctypes[ctype](scc)
1181
1182 else:
1183 raise ValueError("Unknown card type: %s" % ctype)
1184
1185 return card