blob: 73b07635067c984d48c8b84470d9d5b6e21f9bed [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
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200151 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
152
153 # Reset contents to EF.AD in case the file is uninintalized
154 if data.lower() == "ffffffff":
155 data = "00000000"
156
157 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100158 data, sw = self._scc.update_binary(EF['AD'], content)
159 return sw
160
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300161 def read_spn(self):
162 (spn, sw) = self._scc.read_binary(EF['SPN'])
163 if sw == '9000':
164 return (dec_spn(spn), sw)
165 else:
166 return (None, sw)
167
168 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
169 content = enc_spn(name, hplmn_disp, oplmn_disp)
170 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
171 return sw
172
Supreeth Herled21349a2020-04-01 08:37:47 +0200173 def read_binary(self, ef, length=None, offset=0):
174 ef_path = ef in EF and EF[ef] or ef
175 return self._scc.read_binary(ef_path, length, offset)
176
Supreeth Herlead10d662020-04-01 08:43:08 +0200177 def read_record(self, ef, rec_no):
178 ef_path = ef in EF and EF[ef] or ef
179 return self._scc.read_record(ef_path, rec_no)
180
Supreeth Herle98a69272020-03-18 12:14:48 +0100181 def read_gid1(self):
182 (res, sw) = self._scc.read_binary(EF['GID1'])
183 if sw == '9000':
184 return (res, sw)
185 else:
186 return (None, sw)
187
Supreeth Herle6d66af62020-03-19 12:49:16 +0100188 def read_msisdn(self):
189 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
190 if sw == '9000':
191 return (dec_msisdn(res), sw)
192 else:
193 return (None, sw)
194
Supreeth Herlee26331e2020-03-20 18:50:39 +0100195 # Read the (full) AID for either ISIM or USIM or ISIM application
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100196 def read_aid(self, isim = False):
197
198 # First (known) halves of the AID
199 aid_usim = "a0000000871002"
200 aid_isim = "a0000000871004"
201
202 # Select which one to look for
203 if isim:
204 aid = aid_isim
205 else:
206 aid = aid_usim
207
208 # Find out how many records the EF.DIR has, then go through
209 # all records and try to find the AID we are looking for
210 aid_record_count = self._scc.record_count(['2F00'])
211 for i in range(0, aid_record_count):
212 record = self._scc.read_record(['2F00'], i + 1)
213 if aid in record[0]:
214 aid_len = int(record[0][6:8], 16)
215 return record[0][8:8 + aid_len * 2]
216
217 return None
218
Supreeth Herlee4e98312020-03-18 11:33:14 +0100219 # Fetch all the AIDs present on UICC
220 def read_aids(self):
221 try:
222 # Find out how many records the EF.DIR has
223 # and store all the AIDs in the UICC
224 rec_cnt = self._scc.record_count(['3f00', '2f00'])
225 for i in range(0, rec_cnt):
226 rec = self._scc.read_record(['3f00', '2f00'], i + 1)
227 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
228 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
229 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
230 except Exception as e:
231 print("Can't read AIDs from SIM -- %s" % (str(e),))
232
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100233 # Select ADF.U/ISIM in the Card using its full AID
234 def select_adf_by_aid(self, adf="usim"):
235 # Check for valid ADF name
236 if adf not in ["usim", "isim"]:
237 return None
238
239 # First (known) halves of the U/ISIM AID
240 aid_map = {}
241 aid_map["usim"] = "a0000000871002"
242 aid_map["isim"] = "a0000000871004"
243
244 for aid in self._aids:
245 if aid_map[adf] in aid:
246 (res, sw) = self._scc.select_adf(aid)
247 return sw
248
249 return None
250
Philipp Maier5c2cc662020-05-12 16:27:12 +0200251 # Erase the contents of a file
252 def erase_binary(self, ef):
253 len = self._scc.binary_size(ef)
254 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
255
256 # Erase the contents of a single record
257 def erase_record(self, ef, rec_no):
258 len = self._scc.record_size(ef)
259 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
260
Sylvain Munaut76504e02010-12-07 00:24:32 +0100261
262class _MagicSimBase(Card):
263 """
264 Theses cards uses several record based EFs to store the provider infos,
265 each possible provider uses a specific record number in each EF. The
266 indexes used are ( where N is the number of providers supported ) :
267 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100268 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100269
270 * 3f00/7f4d/8f0c : Operator Name
271
272 bytes 0-15 : provider name, padded with 0xff
273 byte 16 : length of the provider name
274 byte 17 : 01 for valid records, 00 otherwise
275
276 * 3f00/7f4d/8f0d : Programmable Binary EFs
277
278 * 3f00/7f4d/8f0e : Programmable Record EFs
279
280 """
281
282 @classmethod
283 def autodetect(kls, scc):
284 try:
285 for p, l, t in kls._files.values():
286 if not t:
287 continue
288 if scc.record_size(['3f00', '7f4d', p]) != l:
289 return None
290 except:
291 return None
292
293 return kls(scc)
294
295 def _get_count(self):
296 """
297 Selects the file and returns the total number of entries
298 and entry size
299 """
300 f = self._files['name']
301
302 r = self._scc.select_file(['3f00', '7f4d', f[0]])
303 rec_len = int(r[-1][28:30], 16)
304 tlen = int(r[-1][4:8],16)
305 rec_cnt = (tlen / rec_len) - 1;
306
307 if (rec_cnt < 1) or (rec_len != f[1]):
308 raise RuntimeError('Bad card type')
309
310 return rec_cnt
311
312 def program(self, p):
313 # Go to dir
314 self._scc.select_file(['3f00', '7f4d'])
315
316 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400317 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100318
319 # Operator name ( 3f00/7f4d/8f0c )
320 self._scc.update_record(self._files['name'][0], 2,
321 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
322 )
323
324 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
325 v = ''
326
327 # inline Ki
328 if self._ki_file is None:
329 v += p['ki']
330
331 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400332 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100333
334 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400335 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100336
337 # Ki
338 if self._ki_file:
339 v += self._ki_file + '10' + p['ki']
340
341 # PLMN_Sel
342 v+= '6f30' + '18' + rpad(hplmn, 36)
343
Alexander Chemeris21885242013-07-02 16:56:55 +0400344 # ACC
345 # This doesn't work with "fake" SuperSIM cards,
346 # but will hopefully work with real SuperSIMs.
347 if p.get('acc') is not None:
348 v+= '6f78' + '02' + lpad(p['acc'], 4)
349
Sylvain Munaut76504e02010-12-07 00:24:32 +0100350 self._scc.update_record(self._files['b_ef'][0], 1,
351 rpad(v, self._files['b_ef'][1]*2)
352 )
353
354 # SMSP ( 3f00/7f4d/8f0e )
355 # FIXME
356
357 # Write PLMN_Sel forcefully as well
358 r = self._scc.select_file(['3f00', '7f20', '6f30'])
359 tl = int(r[-1][4:8], 16)
360
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400361 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100362 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
363
364 def erase(self):
365 # Dummy
366 df = {}
367 for k, v in self._files.iteritems():
368 ofs = 1
369 fv = v[1] * 'ff'
370 if k == 'name':
371 ofs = 2
372 fv = fv[0:-4] + '0000'
373 df[v[0]] = (fv, ofs)
374
375 # Write
376 for n in range(0,self._get_count()):
377 for k, (msg, ofs) in df.iteritems():
378 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
379
380
381class SuperSim(_MagicSimBase):
382
383 name = 'supersim'
384
385 _files = {
386 'name' : ('8f0c', 18, True),
387 'b_ef' : ('8f0d', 74, True),
388 'r_ef' : ('8f0e', 50, True),
389 }
390
391 _ki_file = None
392
393
394class MagicSim(_MagicSimBase):
395
396 name = 'magicsim'
397
398 _files = {
399 'name' : ('8f0c', 18, True),
400 'b_ef' : ('8f0d', 130, True),
401 'r_ef' : ('8f0e', 102, False),
402 }
403
404 _ki_file = '6f1b'
405
406
407class FakeMagicSim(Card):
408 """
409 Theses cards have a record based EF 3f00/000c that contains the provider
410 informations. See the program method for its format. The records go from
411 1 to N.
412 """
413
414 name = 'fakemagicsim'
415
416 @classmethod
417 def autodetect(kls, scc):
418 try:
419 if scc.record_size(['3f00', '000c']) != 0x5a:
420 return None
421 except:
422 return None
423
424 return kls(scc)
425
426 def _get_infos(self):
427 """
428 Selects the file and returns the total number of entries
429 and entry size
430 """
431
432 r = self._scc.select_file(['3f00', '000c'])
433 rec_len = int(r[-1][28:30], 16)
434 tlen = int(r[-1][4:8],16)
435 rec_cnt = (tlen / rec_len) - 1;
436
437 if (rec_cnt < 1) or (rec_len != 0x5a):
438 raise RuntimeError('Bad card type')
439
440 return rec_cnt, rec_len
441
442 def program(self, p):
443 # Home PLMN
444 r = self._scc.select_file(['3f00', '7f20', '6f30'])
445 tl = int(r[-1][4:8], 16)
446
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400447 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100448 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
449
450 # Get total number of entries and entry size
451 rec_cnt, rec_len = self._get_infos()
452
453 # Set first entry
454 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200455 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100456 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200457 enc_iccid(p['iccid']) + # 10b ICCID
458 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
459 p['ki'] + # 16b Ki
460 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100461 )
462 self._scc.update_record('000c', 1, entry)
463
464 def erase(self):
465 # Get total number of entries and entry size
466 rec_cnt, rec_len = self._get_infos()
467
468 # Erase all entries
469 entry = 'ff' * rec_len
470 for i in range(0, rec_cnt):
471 self._scc.update_record('000c', 1+i, entry)
472
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200473
Harald Welte3156d902011-03-22 21:48:19 +0100474class GrcardSim(Card):
475 """
476 Greencard (grcard.cn) HZCOS GSM SIM
477 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
478 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
479 """
480
481 name = 'grcardsim'
482
483 @classmethod
484 def autodetect(kls, scc):
485 return None
486
487 def program(self, p):
488 # We don't really know yet what ADM PIN 4 is about
489 #self._scc.verify_chv(4, h2b("4444444444444444"))
490
491 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100492 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200493 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100494 else:
495 pin = h2b("4444444444444444")
496 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100497
498 # EF.ICCID
499 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400500 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100501
502 # EF.IMSI
503 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400504 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100505
506 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400507 if p.get('acc') is not None:
508 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100509
510 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200511 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200512 r = self._scc.select_file(['3f00', '7f10', '6f42'])
513 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100514
515 # Set the Ki using proprietary command
516 pdu = '80d4020010' + p['ki']
517 data, sw = self._scc._tp.send_apdu(pdu)
518
519 # EF.HPLMN
520 r = self._scc.select_file(['3f00', '7f20', '6f30'])
521 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400522 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100523 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
524
525 # EF.SPN (Service Provider Name)
526 r = self._scc.select_file(['3f00', '7f20', '6f30'])
527 size = int(r[-1][4:8], 16)
528 # FIXME
529
530 # FIXME: EF.MSISDN
531
532 def erase(self):
533 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100534
Harald Weltee10394b2011-12-07 12:34:14 +0100535class SysmoSIMgr1(GrcardSim):
536 """
537 sysmocom sysmoSIM-GR1
538 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
539 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
540 """
541 name = 'sysmosim-gr1'
542
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200543 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200544 def autodetect(kls, scc):
545 try:
546 # Look for ATR
547 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
548 return kls(scc)
549 except:
550 return None
551 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200552
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100553class SysmoUSIMgr1(Card):
554 """
555 sysmocom sysmoUSIM-GR1
556 """
557 name = 'sysmoUSIM-GR1'
558
559 @classmethod
560 def autodetect(kls, scc):
561 # TODO: Access the ATR
562 return None
563
564 def program(self, p):
565 # TODO: check if verify_chv could be used or what it needs
566 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
567 # Unlock the card..
568 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
569
570 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100571 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400572 p['opc'] + # 32b OPC
573 enc_iccid(p['iccid']) + # 10b ICCID
574 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100575 )
576 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
577
578 def erase(self):
579 return
580
Sylvain Munaut053c8952013-07-02 15:12:32 +0200581
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100582class SysmoSIMgr2(Card):
583 """
584 sysmocom sysmoSIM-GR2
585 """
586
587 name = 'sysmoSIM-GR2'
588
589 @classmethod
590 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900591 try:
592 # Look for ATR
593 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
594 return kls(scc)
595 except:
596 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100597 return None
598
599 def program(self, p):
600
601 # select MF
602 r = self._scc.select_file(['3f00'])
603
604 # authenticate as SUPER ADM using default key
605 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
606
607 # set ADM pin using proprietary command
608 # INS: D4
609 # P1: 3A for PIN, 3B for PUK
610 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
611 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100612 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200613 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100614 else:
615 pin = h2b("4444444444444444")
616
617 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100618 data, sw = self._scc._tp.send_apdu(pdu)
619
620 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100621
622 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100623
624 # write EF.ICCID
625 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
626
627 # select DF_GSM
628 r = self._scc.select_file(['7f20'])
629
630 # write EF.IMSI
631 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
632
633 # write EF.ACC
634 if p.get('acc') is not None:
635 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
636
637 # get size and write EF.HPLMN
638 r = self._scc.select_file(['6f30'])
639 size = int(r[-1][4:8], 16)
640 hplmn = enc_plmn(p['mcc'], p['mnc'])
641 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
642
643 # set COMP128 version 0 in proprietary file
644 data, sw = self._scc.update_binary('0001', '001000')
645
646 # set Ki in proprietary file
647 data, sw = self._scc.update_binary('0001', p['ki'], 3)
648
649 # select DF_TELECOM
650 r = self._scc.select_file(['3f00', '7f10'])
651
652 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200653 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200654 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100655
656 def erase(self):
657 return
658
Jan Balke3e840672015-01-26 15:36:27 +0100659class SysmoUSIMSJS1(Card):
660 """
661 sysmocom sysmoUSIM-SJS1
662 """
663
664 name = 'sysmoUSIM-SJS1'
665
666 def __init__(self, ssc):
667 super(SysmoUSIMSJS1, self).__init__(ssc)
668 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100669 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100670
671 @classmethod
672 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900673 try:
674 # Look for ATR
675 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"):
676 return kls(scc)
677 except:
678 return None
Jan Balke3e840672015-01-26 15:36:27 +0100679 return None
680
681 def program(self, p):
682
Philipp Maiere9604882017-03-21 17:24:31 +0100683 # authenticate as ADM using default key (written on the card..)
684 if not p['pin_adm']:
685 raise ValueError("Please provide a PIN-ADM as there is no default one")
686 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100687
688 # select MF
689 r = self._scc.select_file(['3f00'])
690
Philipp Maiere9604882017-03-21 17:24:31 +0100691 # write EF.ICCID
692 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
693
Jan Balke3e840672015-01-26 15:36:27 +0100694 # select DF_GSM
695 r = self._scc.select_file(['7f20'])
696
Jan Balke3e840672015-01-26 15:36:27 +0100697 # set Ki in proprietary file
698 data, sw = self._scc.update_binary('00FF', p['ki'])
699
Philipp Maier1be35bf2018-07-13 11:29:03 +0200700 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200701 if 'opc' in p:
702 content = "01" + p['opc']
703 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100704
Supreeth Herle7947d922019-06-08 07:50:53 +0200705 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100706 if p.get('name') is not None:
707 content = enc_spn(p['name'], True, True)
708 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200709
Supreeth Herlec8796a32019-12-23 12:23:42 +0100710 if p.get('acc') is not None:
711 self.update_acc(p['acc'])
712
Jan Balke3e840672015-01-26 15:36:27 +0100713 # write EF.IMSI
714 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
715
Philipp Maier2d15ea02019-03-20 12:40:36 +0100716 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200717 if p.get('mcc') and p.get('mnc'):
718 sw = self.update_plmnsel(p['mcc'], p['mnc'])
719 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100720 print("Programming PLMNsel failed with code %s"%sw)
721
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200722 # EF.PLMNwAcT
723 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100724 sw = self.update_plmn_act(p['mcc'], p['mnc'])
725 if sw != '9000':
726 print("Programming PLMNwAcT failed with code %s"%sw)
727
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200728 # EF.OPLMNwAcT
729 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100730 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
731 if sw != '9000':
732 print("Programming OPLMNwAcT failed with code %s"%sw)
733
Supreeth Herlef442fb42020-01-21 12:47:32 +0100734 # EF.HPLMNwAcT
735 if p.get('mcc') and p.get('mnc'):
736 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
737 if sw != '9000':
738 print("Programming HPLMNwAcT failed with code %s"%sw)
739
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200740 # EF.AD
741 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100742 sw = self.update_ad(p['mnc'])
743 if sw != '9000':
744 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100745
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200746 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200747 if p.get('smsp'):
748 r = self._scc.select_file(['3f00', '7f10'])
749 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100750
Supreeth Herle5a541012019-12-22 08:59:16 +0100751 # EF.MSISDN
752 # TODO: Alpha Identifier (currently 'ff'O * 20)
753 # TODO: Capability/Configuration1 Record Identifier
754 # TODO: Extension1 Record Identifier
755 if p.get('msisdn') is not None:
756 msisdn = enc_msisdn(p['msisdn'])
757 data = 'ff' * 20 + msisdn + 'ff' * 2
758
759 r = self._scc.select_file(['3f00', '7f10'])
760 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
761
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900762 def erase(self):
763 return
764
765
766class FairwavesSIM(Card):
767 """
768 FairwavesSIM
769
770 The SIM card is operating according to the standard.
771 For Ki/OP/OPC programming the following files are additionally open for writing:
772 3F00/7F20/FF01 – OP/OPC:
773 byte 1 = 0x01, bytes 2-17: OPC;
774 byte 1 = 0x00, bytes 2-17: OP;
775 3F00/7F20/FF02: Ki
776 """
777
Philipp Maier5a876312019-11-11 11:01:46 +0100778 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900779 # Propriatary files
780 _EF_num = {
781 'Ki': 'FF02',
782 'OP/OPC': 'FF01',
783 }
784 _EF = {
785 'Ki': DF['GSM']+[_EF_num['Ki']],
786 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
787 }
788
789 def __init__(self, ssc):
790 super(FairwavesSIM, self).__init__(ssc)
791 self._adm_chv_num = 0x11
792 self._adm2_chv_num = 0x12
793
794
795 @classmethod
796 def autodetect(kls, scc):
797 try:
798 # Look for ATR
799 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"):
800 return kls(scc)
801 except:
802 return None
803 return None
804
805
806 def verify_adm2(self, key):
807 '''
808 Authenticate with ADM2 key.
809
810 Fairwaves SIM cards support hierarchical key structure and ADM2 key
811 is a key which has access to proprietary files (Ki and OP/OPC).
812 That said, ADM key inherits permissions of ADM2 key and thus we rarely
813 need ADM2 key per se.
814 '''
815 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
816 return sw
817
818
819 def read_ki(self):
820 """
821 Read Ki in proprietary file.
822
823 Requires ADM1 access level
824 """
825 return self._scc.read_binary(self._EF['Ki'])
826
827
828 def update_ki(self, ki):
829 """
830 Set Ki in proprietary file.
831
832 Requires ADM1 access level
833 """
834 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
835 return sw
836
837
838 def read_op_opc(self):
839 """
840 Read Ki in proprietary file.
841
842 Requires ADM1 access level
843 """
844 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
845 type = 'OP' if ef[0:2] == '00' else 'OPC'
846 return ((type, ef[2:]), sw)
847
848
849 def update_op(self, op):
850 """
851 Set OP in proprietary file.
852
853 Requires ADM1 access level
854 """
855 content = '00' + op
856 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
857 return sw
858
859
860 def update_opc(self, opc):
861 """
862 Set OPC in proprietary file.
863
864 Requires ADM1 access level
865 """
866 content = '01' + opc
867 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
868 return sw
869
870
871 def program(self, p):
872 # authenticate as ADM1
873 if not p['pin_adm']:
874 raise ValueError("Please provide a PIN-ADM as there is no default one")
875 sw = self.verify_adm(h2b(p['pin_adm']))
876 if sw != '9000':
877 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
878
879 # TODO: Set operator name
880 if p.get('smsp') is not None:
881 sw = self.update_smsp(p['smsp'])
882 if sw != '9000':
883 print("Programming SMSP failed with code %s"%sw)
884 # This SIM doesn't support changing ICCID
885 if p.get('mcc') is not None and p.get('mnc') is not None:
886 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
887 if sw != '9000':
888 print("Programming MCC/MNC failed with code %s"%sw)
889 if p.get('imsi') is not None:
890 sw = self.update_imsi(p['imsi'])
891 if sw != '9000':
892 print("Programming IMSI failed with code %s"%sw)
893 if p.get('ki') is not None:
894 sw = self.update_ki(p['ki'])
895 if sw != '9000':
896 print("Programming Ki failed with code %s"%sw)
897 if p.get('opc') is not None:
898 sw = self.update_opc(p['opc'])
899 if sw != '9000':
900 print("Programming OPC failed with code %s"%sw)
901 if p.get('acc') is not None:
902 sw = self.update_acc(p['acc'])
903 if sw != '9000':
904 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100905
906 def erase(self):
907 return
908
909
Todd Neal9eeadfc2018-04-25 15:36:29 -0500910class OpenCellsSim(Card):
911 """
912 OpenCellsSim
913
914 """
915
Philipp Maier5a876312019-11-11 11:01:46 +0100916 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500917
918 def __init__(self, ssc):
919 super(OpenCellsSim, self).__init__(ssc)
920 self._adm_chv_num = 0x0A
921
922
923 @classmethod
924 def autodetect(kls, scc):
925 try:
926 # Look for ATR
927 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"):
928 return kls(scc)
929 except:
930 return None
931 return None
932
933
934 def program(self, p):
935 if not p['pin_adm']:
936 raise ValueError("Please provide a PIN-ADM as there is no default one")
937 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
938
939 # select MF
940 r = self._scc.select_file(['3f00'])
941
942 # write EF.ICCID
943 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
944
945 r = self._scc.select_file(['7ff0'])
946
947 # set Ki in proprietary file
948 data, sw = self._scc.update_binary('FF02', p['ki'])
949
950 # set OPC in proprietary file
951 data, sw = self._scc.update_binary('FF01', p['opc'])
952
953 # select DF_GSM
954 r = self._scc.select_file(['7f20'])
955
956 # write EF.IMSI
957 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
958
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200959class WavemobileSim(Card):
960 """
961 WavemobileSim
962
963 """
964
965 name = 'Wavemobile-SIM'
966
967 def __init__(self, ssc):
968 super(WavemobileSim, self).__init__(ssc)
969 self._adm_chv_num = 0x0A
970 self._scc.cla_byte = "00"
971 self._scc.sel_ctrl = "0004" #request an FCP
972
973 @classmethod
974 def autodetect(kls, scc):
975 try:
976 # Look for ATR
977 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"):
978 return kls(scc)
979 except:
980 return None
981 return None
982
983 def program(self, p):
984 if not p['pin_adm']:
985 raise ValueError("Please provide a PIN-ADM as there is no default one")
986 sw = self.verify_adm(h2b(p['pin_adm']))
987 if sw != '9000':
988 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
989
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200990 # EF.ICCID
991 # TODO: Add programming of the ICCID
992 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200993 print("Warning: Programming of the ICCID is not implemented for this type of card.")
994
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200995 # KI (Presumably a propritary file)
996 # TODO: Add programming of KI
997 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200998 print("Warning: Programming of the KI is not implemented for this type of card.")
999
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001000 # OPc (Presumably a propritary file)
1001 # TODO: Add programming of OPc
1002 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001003 print("Warning: Programming of the OPc is not implemented for this type of card.")
1004
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001005 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001006 if p.get('smsp'):
1007 sw = self.update_smsp(p['smsp'])
1008 if sw != '9000':
1009 print("Programming SMSP failed with code %s"%sw)
1010
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001011 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001012 if p.get('imsi'):
1013 sw = self.update_imsi(p['imsi'])
1014 if sw != '9000':
1015 print("Programming IMSI failed with code %s"%sw)
1016
1017 # EF.ACC
1018 if p.get('acc'):
1019 sw = self.update_acc(p['acc'])
1020 if sw != '9000':
1021 print("Programming ACC failed with code %s"%sw)
1022
1023 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001024 if p.get('mcc') and p.get('mnc'):
1025 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1026 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001027 print("Programming PLMNsel failed with code %s"%sw)
1028
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001029 # EF.PLMNwAcT
1030 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001031 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1032 if sw != '9000':
1033 print("Programming PLMNwAcT failed with code %s"%sw)
1034
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001035 # EF.OPLMNwAcT
1036 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001037 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1038 if sw != '9000':
1039 print("Programming OPLMNwAcT failed with code %s"%sw)
1040
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001041 # EF.AD
1042 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001043 sw = self.update_ad(p['mnc'])
1044 if sw != '9000':
1045 print("Programming AD failed with code %s"%sw)
1046
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001047 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001048
1049 def erase(self):
1050 return
1051
Todd Neal9eeadfc2018-04-25 15:36:29 -05001052
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001053class SysmoISIMSJA2(Card):
1054 """
1055 sysmocom sysmoISIM-SJA2
1056 """
1057
1058 name = 'sysmoISIM-SJA2'
1059
1060 def __init__(self, ssc):
1061 super(SysmoISIMSJA2, self).__init__(ssc)
1062 self._scc.cla_byte = "00"
1063 self._scc.sel_ctrl = "0004" #request an FCP
1064
1065 @classmethod
1066 def autodetect(kls, scc):
1067 try:
1068 # Try card model #1
1069 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1070 if scc.get_atr() == toBytes(atr):
1071 return kls(scc)
1072
1073 # Try card model #2
1074 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1075 if scc.get_atr() == toBytes(atr):
1076 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001077
1078 # Try card model #3
1079 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1080 if scc.get_atr() == toBytes(atr):
1081 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001082 except:
1083 return None
1084 return None
1085
1086 def program(self, p):
1087 # authenticate as ADM using default key (written on the card..)
1088 if not p['pin_adm']:
1089 raise ValueError("Please provide a PIN-ADM as there is no default one")
1090 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1091
1092 # This type of card does not allow to reprogram the ICCID.
1093 # Reprogramming the ICCID would mess up the card os software
1094 # license management, so the ICCID must be kept at its factory
1095 # setting!
1096 if p.get('iccid'):
1097 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1098
1099 # select DF_GSM
1100 self._scc.select_file(['7f20'])
1101
1102 # write EF.IMSI
1103 if p.get('imsi'):
1104 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1105
1106 # EF.PLMNsel
1107 if p.get('mcc') and p.get('mnc'):
1108 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1109 if sw != '9000':
1110 print("Programming PLMNsel failed with code %s"%sw)
1111
1112 # EF.PLMNwAcT
1113 if p.get('mcc') and p.get('mnc'):
1114 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1115 if sw != '9000':
1116 print("Programming PLMNwAcT failed with code %s"%sw)
1117
1118 # EF.OPLMNwAcT
1119 if p.get('mcc') and p.get('mnc'):
1120 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1121 if sw != '9000':
1122 print("Programming OPLMNwAcT failed with code %s"%sw)
1123
Harald Welte32f0d412020-05-05 17:35:57 +02001124 # EF.HPLMNwAcT
1125 if p.get('mcc') and p.get('mnc'):
1126 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1127 if sw != '9000':
1128 print("Programming HPLMNwAcT failed with code %s"%sw)
1129
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001130 # EF.AD
1131 if p.get('mcc') and p.get('mnc'):
1132 sw = self.update_ad(p['mnc'])
1133 if sw != '9000':
1134 print("Programming AD failed with code %s"%sw)
1135
1136 # EF.SMSP
1137 if p.get('smsp'):
1138 r = self._scc.select_file(['3f00', '7f10'])
1139 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1140
1141 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1142 # hard linked to EF-USIM_AUTH_KEY)
1143 self._scc.select_file(['3f00'])
1144 self._scc.select_file(['a515'])
1145 if p.get('ki'):
1146 self._scc.update_binary('6f20', p['ki'], 1)
1147 if p.get('opc'):
1148 self._scc.update_binary('6f20', p['opc'], 17)
1149
1150 # update EF-USIM_AUTH_KEY in ADF.ISIM
1151 self._scc.select_file(['3f00'])
1152 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001153 if (aid):
1154 self._scc.select_adf(aid)
1155 if p.get('ki'):
1156 self._scc.update_binary('af20', p['ki'], 1)
1157 if p.get('opc'):
1158 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001159
1160 # update EF-USIM_AUTH_KEY in ADF.USIM
1161 self._scc.select_file(['3f00'])
1162 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001163 if (aid):
1164 self._scc.select_adf(aid)
1165 if p.get('ki'):
1166 self._scc.update_binary('af20', p['ki'], 1)
1167 if p.get('opc'):
1168 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001169
1170 return
1171
1172 def erase(self):
1173 return
1174
1175
Todd Neal9eeadfc2018-04-25 15:36:29 -05001176# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001177_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001178 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001179 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001180
1181def card_autodetect(scc):
1182 for kls in _cards_classes:
1183 card = kls.autodetect(scc)
1184 if card is not None:
1185 card.reset()
1186 return card
1187 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001188
1189def card_detect(ctype, scc):
1190 # Detect type if needed
1191 card = None
1192 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1193
1194 if ctype in ("auto", "auto_once"):
1195 for kls in _cards_classes:
1196 card = kls.autodetect(scc)
1197 if card:
1198 print("Autodetected card type: %s" % card.name)
1199 card.reset()
1200 break
1201
1202 if card is None:
1203 print("Autodetection failed")
1204 return None
1205
1206 if ctype == "auto_once":
1207 ctype = card.name
1208
1209 elif ctype in ctypes:
1210 card = ctypes[ctype](scc)
1211
1212 else:
1213 raise ValueError("Unknown card type: %s" % ctype)
1214
1215 return card