blob: 8937ee89a508a2a8854c3bb9e7094f2df4536531 [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 the (full) AID for either ISIM or USIM or ISIM application
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100192 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
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100229 # Select ADF.U/ISIM in the Card using its full AID
230 def select_adf_by_aid(self, adf="usim"):
231 # Check for valid ADF name
232 if adf not in ["usim", "isim"]:
233 return None
234
235 # First (known) halves of the U/ISIM AID
236 aid_map = {}
237 aid_map["usim"] = "a0000000871002"
238 aid_map["isim"] = "a0000000871004"
239
240 for aid in self._aids:
241 if aid_map[adf] in aid:
242 (res, sw) = self._scc.select_adf(aid)
243 return sw
244
245 return None
246
Sylvain Munaut76504e02010-12-07 00:24:32 +0100247
248class _MagicSimBase(Card):
249 """
250 Theses cards uses several record based EFs to store the provider infos,
251 each possible provider uses a specific record number in each EF. The
252 indexes used are ( where N is the number of providers supported ) :
253 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100254 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100255
256 * 3f00/7f4d/8f0c : Operator Name
257
258 bytes 0-15 : provider name, padded with 0xff
259 byte 16 : length of the provider name
260 byte 17 : 01 for valid records, 00 otherwise
261
262 * 3f00/7f4d/8f0d : Programmable Binary EFs
263
264 * 3f00/7f4d/8f0e : Programmable Record EFs
265
266 """
267
268 @classmethod
269 def autodetect(kls, scc):
270 try:
271 for p, l, t in kls._files.values():
272 if not t:
273 continue
274 if scc.record_size(['3f00', '7f4d', p]) != l:
275 return None
276 except:
277 return None
278
279 return kls(scc)
280
281 def _get_count(self):
282 """
283 Selects the file and returns the total number of entries
284 and entry size
285 """
286 f = self._files['name']
287
288 r = self._scc.select_file(['3f00', '7f4d', f[0]])
289 rec_len = int(r[-1][28:30], 16)
290 tlen = int(r[-1][4:8],16)
291 rec_cnt = (tlen / rec_len) - 1;
292
293 if (rec_cnt < 1) or (rec_len != f[1]):
294 raise RuntimeError('Bad card type')
295
296 return rec_cnt
297
298 def program(self, p):
299 # Go to dir
300 self._scc.select_file(['3f00', '7f4d'])
301
302 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400303 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304
305 # Operator name ( 3f00/7f4d/8f0c )
306 self._scc.update_record(self._files['name'][0], 2,
307 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
308 )
309
310 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
311 v = ''
312
313 # inline Ki
314 if self._ki_file is None:
315 v += p['ki']
316
317 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400318 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100319
320 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400321 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100322
323 # Ki
324 if self._ki_file:
325 v += self._ki_file + '10' + p['ki']
326
327 # PLMN_Sel
328 v+= '6f30' + '18' + rpad(hplmn, 36)
329
Alexander Chemeris21885242013-07-02 16:56:55 +0400330 # ACC
331 # This doesn't work with "fake" SuperSIM cards,
332 # but will hopefully work with real SuperSIMs.
333 if p.get('acc') is not None:
334 v+= '6f78' + '02' + lpad(p['acc'], 4)
335
Sylvain Munaut76504e02010-12-07 00:24:32 +0100336 self._scc.update_record(self._files['b_ef'][0], 1,
337 rpad(v, self._files['b_ef'][1]*2)
338 )
339
340 # SMSP ( 3f00/7f4d/8f0e )
341 # FIXME
342
343 # Write PLMN_Sel forcefully as well
344 r = self._scc.select_file(['3f00', '7f20', '6f30'])
345 tl = int(r[-1][4:8], 16)
346
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400347 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100348 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
349
350 def erase(self):
351 # Dummy
352 df = {}
353 for k, v in self._files.iteritems():
354 ofs = 1
355 fv = v[1] * 'ff'
356 if k == 'name':
357 ofs = 2
358 fv = fv[0:-4] + '0000'
359 df[v[0]] = (fv, ofs)
360
361 # Write
362 for n in range(0,self._get_count()):
363 for k, (msg, ofs) in df.iteritems():
364 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
365
366
367class SuperSim(_MagicSimBase):
368
369 name = 'supersim'
370
371 _files = {
372 'name' : ('8f0c', 18, True),
373 'b_ef' : ('8f0d', 74, True),
374 'r_ef' : ('8f0e', 50, True),
375 }
376
377 _ki_file = None
378
379
380class MagicSim(_MagicSimBase):
381
382 name = 'magicsim'
383
384 _files = {
385 'name' : ('8f0c', 18, True),
386 'b_ef' : ('8f0d', 130, True),
387 'r_ef' : ('8f0e', 102, False),
388 }
389
390 _ki_file = '6f1b'
391
392
393class FakeMagicSim(Card):
394 """
395 Theses cards have a record based EF 3f00/000c that contains the provider
396 informations. See the program method for its format. The records go from
397 1 to N.
398 """
399
400 name = 'fakemagicsim'
401
402 @classmethod
403 def autodetect(kls, scc):
404 try:
405 if scc.record_size(['3f00', '000c']) != 0x5a:
406 return None
407 except:
408 return None
409
410 return kls(scc)
411
412 def _get_infos(self):
413 """
414 Selects the file and returns the total number of entries
415 and entry size
416 """
417
418 r = self._scc.select_file(['3f00', '000c'])
419 rec_len = int(r[-1][28:30], 16)
420 tlen = int(r[-1][4:8],16)
421 rec_cnt = (tlen / rec_len) - 1;
422
423 if (rec_cnt < 1) or (rec_len != 0x5a):
424 raise RuntimeError('Bad card type')
425
426 return rec_cnt, rec_len
427
428 def program(self, p):
429 # Home PLMN
430 r = self._scc.select_file(['3f00', '7f20', '6f30'])
431 tl = int(r[-1][4:8], 16)
432
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400433 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100434 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
435
436 # Get total number of entries and entry size
437 rec_cnt, rec_len = self._get_infos()
438
439 # Set first entry
440 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200441 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100442 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200443 enc_iccid(p['iccid']) + # 10b ICCID
444 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
445 p['ki'] + # 16b Ki
446 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100447 )
448 self._scc.update_record('000c', 1, entry)
449
450 def erase(self):
451 # Get total number of entries and entry size
452 rec_cnt, rec_len = self._get_infos()
453
454 # Erase all entries
455 entry = 'ff' * rec_len
456 for i in range(0, rec_cnt):
457 self._scc.update_record('000c', 1+i, entry)
458
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200459
Harald Welte3156d902011-03-22 21:48:19 +0100460class GrcardSim(Card):
461 """
462 Greencard (grcard.cn) HZCOS GSM SIM
463 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
464 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
465 """
466
467 name = 'grcardsim'
468
469 @classmethod
470 def autodetect(kls, scc):
471 return None
472
473 def program(self, p):
474 # We don't really know yet what ADM PIN 4 is about
475 #self._scc.verify_chv(4, h2b("4444444444444444"))
476
477 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100478 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200479 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100480 else:
481 pin = h2b("4444444444444444")
482 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100483
484 # EF.ICCID
485 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400486 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100487
488 # EF.IMSI
489 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400490 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100491
492 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400493 if p.get('acc') is not None:
494 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100495
496 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200497 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200498 r = self._scc.select_file(['3f00', '7f10', '6f42'])
499 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100500
501 # Set the Ki using proprietary command
502 pdu = '80d4020010' + p['ki']
503 data, sw = self._scc._tp.send_apdu(pdu)
504
505 # EF.HPLMN
506 r = self._scc.select_file(['3f00', '7f20', '6f30'])
507 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400508 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100509 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
510
511 # EF.SPN (Service Provider Name)
512 r = self._scc.select_file(['3f00', '7f20', '6f30'])
513 size = int(r[-1][4:8], 16)
514 # FIXME
515
516 # FIXME: EF.MSISDN
517
518 def erase(self):
519 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100520
Harald Weltee10394b2011-12-07 12:34:14 +0100521class SysmoSIMgr1(GrcardSim):
522 """
523 sysmocom sysmoSIM-GR1
524 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
525 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
526 """
527 name = 'sysmosim-gr1'
528
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200529 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200530 def autodetect(kls, scc):
531 try:
532 # Look for ATR
533 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
534 return kls(scc)
535 except:
536 return None
537 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200538
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100539class SysmoUSIMgr1(Card):
540 """
541 sysmocom sysmoUSIM-GR1
542 """
543 name = 'sysmoUSIM-GR1'
544
545 @classmethod
546 def autodetect(kls, scc):
547 # TODO: Access the ATR
548 return None
549
550 def program(self, p):
551 # TODO: check if verify_chv could be used or what it needs
552 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
553 # Unlock the card..
554 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
555
556 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100557 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400558 p['opc'] + # 32b OPC
559 enc_iccid(p['iccid']) + # 10b ICCID
560 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100561 )
562 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
563
564 def erase(self):
565 return
566
Sylvain Munaut053c8952013-07-02 15:12:32 +0200567
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100568class SysmoSIMgr2(Card):
569 """
570 sysmocom sysmoSIM-GR2
571 """
572
573 name = 'sysmoSIM-GR2'
574
575 @classmethod
576 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900577 try:
578 # Look for ATR
579 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
580 return kls(scc)
581 except:
582 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100583 return None
584
585 def program(self, p):
586
587 # select MF
588 r = self._scc.select_file(['3f00'])
589
590 # authenticate as SUPER ADM using default key
591 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
592
593 # set ADM pin using proprietary command
594 # INS: D4
595 # P1: 3A for PIN, 3B for PUK
596 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
597 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100598 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200599 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100600 else:
601 pin = h2b("4444444444444444")
602
603 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100604 data, sw = self._scc._tp.send_apdu(pdu)
605
606 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100607
608 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100609
610 # write EF.ICCID
611 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
612
613 # select DF_GSM
614 r = self._scc.select_file(['7f20'])
615
616 # write EF.IMSI
617 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
618
619 # write EF.ACC
620 if p.get('acc') is not None:
621 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
622
623 # get size and write EF.HPLMN
624 r = self._scc.select_file(['6f30'])
625 size = int(r[-1][4:8], 16)
626 hplmn = enc_plmn(p['mcc'], p['mnc'])
627 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
628
629 # set COMP128 version 0 in proprietary file
630 data, sw = self._scc.update_binary('0001', '001000')
631
632 # set Ki in proprietary file
633 data, sw = self._scc.update_binary('0001', p['ki'], 3)
634
635 # select DF_TELECOM
636 r = self._scc.select_file(['3f00', '7f10'])
637
638 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200639 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200640 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100641
642 def erase(self):
643 return
644
Jan Balke3e840672015-01-26 15:36:27 +0100645class SysmoUSIMSJS1(Card):
646 """
647 sysmocom sysmoUSIM-SJS1
648 """
649
650 name = 'sysmoUSIM-SJS1'
651
652 def __init__(self, ssc):
653 super(SysmoUSIMSJS1, self).__init__(ssc)
654 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100655 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100656
657 @classmethod
658 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900659 try:
660 # Look for ATR
661 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"):
662 return kls(scc)
663 except:
664 return None
Jan Balke3e840672015-01-26 15:36:27 +0100665 return None
666
667 def program(self, p):
668
Philipp Maiere9604882017-03-21 17:24:31 +0100669 # authenticate as ADM using default key (written on the card..)
670 if not p['pin_adm']:
671 raise ValueError("Please provide a PIN-ADM as there is no default one")
672 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100673
674 # select MF
675 r = self._scc.select_file(['3f00'])
676
Philipp Maiere9604882017-03-21 17:24:31 +0100677 # write EF.ICCID
678 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
679
Jan Balke3e840672015-01-26 15:36:27 +0100680 # select DF_GSM
681 r = self._scc.select_file(['7f20'])
682
Jan Balke3e840672015-01-26 15:36:27 +0100683 # set Ki in proprietary file
684 data, sw = self._scc.update_binary('00FF', p['ki'])
685
Philipp Maier1be35bf2018-07-13 11:29:03 +0200686 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200687 if 'opc' in p:
688 content = "01" + p['opc']
689 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100690
Supreeth Herle7947d922019-06-08 07:50:53 +0200691 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100692 if p.get('name') is not None:
693 content = enc_spn(p['name'], True, True)
694 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200695
Supreeth Herlec8796a32019-12-23 12:23:42 +0100696 if p.get('acc') is not None:
697 self.update_acc(p['acc'])
698
Jan Balke3e840672015-01-26 15:36:27 +0100699 # write EF.IMSI
700 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
701
Philipp Maier2d15ea02019-03-20 12:40:36 +0100702 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200703 if p.get('mcc') and p.get('mnc'):
704 sw = self.update_plmnsel(p['mcc'], p['mnc'])
705 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100706 print("Programming PLMNsel failed with code %s"%sw)
707
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200708 # EF.PLMNwAcT
709 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100710 sw = self.update_plmn_act(p['mcc'], p['mnc'])
711 if sw != '9000':
712 print("Programming PLMNwAcT failed with code %s"%sw)
713
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200714 # EF.OPLMNwAcT
715 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100716 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
717 if sw != '9000':
718 print("Programming OPLMNwAcT failed with code %s"%sw)
719
Supreeth Herlef442fb42020-01-21 12:47:32 +0100720 # EF.HPLMNwAcT
721 if p.get('mcc') and p.get('mnc'):
722 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
723 if sw != '9000':
724 print("Programming HPLMNwAcT failed with code %s"%sw)
725
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200726 # EF.AD
727 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100728 sw = self.update_ad(p['mnc'])
729 if sw != '9000':
730 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100731
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200732 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200733 if p.get('smsp'):
734 r = self._scc.select_file(['3f00', '7f10'])
735 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100736
Supreeth Herle5a541012019-12-22 08:59:16 +0100737 # EF.MSISDN
738 # TODO: Alpha Identifier (currently 'ff'O * 20)
739 # TODO: Capability/Configuration1 Record Identifier
740 # TODO: Extension1 Record Identifier
741 if p.get('msisdn') is not None:
742 msisdn = enc_msisdn(p['msisdn'])
743 data = 'ff' * 20 + msisdn + 'ff' * 2
744
745 r = self._scc.select_file(['3f00', '7f10'])
746 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
747
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900748 def erase(self):
749 return
750
751
752class FairwavesSIM(Card):
753 """
754 FairwavesSIM
755
756 The SIM card is operating according to the standard.
757 For Ki/OP/OPC programming the following files are additionally open for writing:
758 3F00/7F20/FF01 – OP/OPC:
759 byte 1 = 0x01, bytes 2-17: OPC;
760 byte 1 = 0x00, bytes 2-17: OP;
761 3F00/7F20/FF02: Ki
762 """
763
Philipp Maier5a876312019-11-11 11:01:46 +0100764 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900765 # Propriatary files
766 _EF_num = {
767 'Ki': 'FF02',
768 'OP/OPC': 'FF01',
769 }
770 _EF = {
771 'Ki': DF['GSM']+[_EF_num['Ki']],
772 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
773 }
774
775 def __init__(self, ssc):
776 super(FairwavesSIM, self).__init__(ssc)
777 self._adm_chv_num = 0x11
778 self._adm2_chv_num = 0x12
779
780
781 @classmethod
782 def autodetect(kls, scc):
783 try:
784 # Look for ATR
785 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"):
786 return kls(scc)
787 except:
788 return None
789 return None
790
791
792 def verify_adm2(self, key):
793 '''
794 Authenticate with ADM2 key.
795
796 Fairwaves SIM cards support hierarchical key structure and ADM2 key
797 is a key which has access to proprietary files (Ki and OP/OPC).
798 That said, ADM key inherits permissions of ADM2 key and thus we rarely
799 need ADM2 key per se.
800 '''
801 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
802 return sw
803
804
805 def read_ki(self):
806 """
807 Read Ki in proprietary file.
808
809 Requires ADM1 access level
810 """
811 return self._scc.read_binary(self._EF['Ki'])
812
813
814 def update_ki(self, ki):
815 """
816 Set Ki in proprietary file.
817
818 Requires ADM1 access level
819 """
820 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
821 return sw
822
823
824 def read_op_opc(self):
825 """
826 Read Ki in proprietary file.
827
828 Requires ADM1 access level
829 """
830 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
831 type = 'OP' if ef[0:2] == '00' else 'OPC'
832 return ((type, ef[2:]), sw)
833
834
835 def update_op(self, op):
836 """
837 Set OP in proprietary file.
838
839 Requires ADM1 access level
840 """
841 content = '00' + op
842 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
843 return sw
844
845
846 def update_opc(self, opc):
847 """
848 Set OPC in proprietary file.
849
850 Requires ADM1 access level
851 """
852 content = '01' + opc
853 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
854 return sw
855
856
857 def program(self, p):
858 # authenticate as ADM1
859 if not p['pin_adm']:
860 raise ValueError("Please provide a PIN-ADM as there is no default one")
861 sw = self.verify_adm(h2b(p['pin_adm']))
862 if sw != '9000':
863 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
864
865 # TODO: Set operator name
866 if p.get('smsp') is not None:
867 sw = self.update_smsp(p['smsp'])
868 if sw != '9000':
869 print("Programming SMSP failed with code %s"%sw)
870 # This SIM doesn't support changing ICCID
871 if p.get('mcc') is not None and p.get('mnc') is not None:
872 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
873 if sw != '9000':
874 print("Programming MCC/MNC failed with code %s"%sw)
875 if p.get('imsi') is not None:
876 sw = self.update_imsi(p['imsi'])
877 if sw != '9000':
878 print("Programming IMSI failed with code %s"%sw)
879 if p.get('ki') is not None:
880 sw = self.update_ki(p['ki'])
881 if sw != '9000':
882 print("Programming Ki failed with code %s"%sw)
883 if p.get('opc') is not None:
884 sw = self.update_opc(p['opc'])
885 if sw != '9000':
886 print("Programming OPC failed with code %s"%sw)
887 if p.get('acc') is not None:
888 sw = self.update_acc(p['acc'])
889 if sw != '9000':
890 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100891
892 def erase(self):
893 return
894
895
Todd Neal9eeadfc2018-04-25 15:36:29 -0500896class OpenCellsSim(Card):
897 """
898 OpenCellsSim
899
900 """
901
Philipp Maier5a876312019-11-11 11:01:46 +0100902 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500903
904 def __init__(self, ssc):
905 super(OpenCellsSim, self).__init__(ssc)
906 self._adm_chv_num = 0x0A
907
908
909 @classmethod
910 def autodetect(kls, scc):
911 try:
912 # Look for ATR
913 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"):
914 return kls(scc)
915 except:
916 return None
917 return None
918
919
920 def program(self, p):
921 if not p['pin_adm']:
922 raise ValueError("Please provide a PIN-ADM as there is no default one")
923 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
924
925 # select MF
926 r = self._scc.select_file(['3f00'])
927
928 # write EF.ICCID
929 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
930
931 r = self._scc.select_file(['7ff0'])
932
933 # set Ki in proprietary file
934 data, sw = self._scc.update_binary('FF02', p['ki'])
935
936 # set OPC in proprietary file
937 data, sw = self._scc.update_binary('FF01', p['opc'])
938
939 # select DF_GSM
940 r = self._scc.select_file(['7f20'])
941
942 # write EF.IMSI
943 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
944
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200945class WavemobileSim(Card):
946 """
947 WavemobileSim
948
949 """
950
951 name = 'Wavemobile-SIM'
952
953 def __init__(self, ssc):
954 super(WavemobileSim, self).__init__(ssc)
955 self._adm_chv_num = 0x0A
956 self._scc.cla_byte = "00"
957 self._scc.sel_ctrl = "0004" #request an FCP
958
959 @classmethod
960 def autodetect(kls, scc):
961 try:
962 # Look for ATR
963 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"):
964 return kls(scc)
965 except:
966 return None
967 return None
968
969 def program(self, p):
970 if not p['pin_adm']:
971 raise ValueError("Please provide a PIN-ADM as there is no default one")
972 sw = self.verify_adm(h2b(p['pin_adm']))
973 if sw != '9000':
974 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
975
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200976 # EF.ICCID
977 # TODO: Add programming of the ICCID
978 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200979 print("Warning: Programming of the ICCID is not implemented for this type of card.")
980
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200981 # KI (Presumably a propritary file)
982 # TODO: Add programming of KI
983 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200984 print("Warning: Programming of the KI is not implemented for this type of card.")
985
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200986 # OPc (Presumably a propritary file)
987 # TODO: Add programming of OPc
988 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200989 print("Warning: Programming of the OPc is not implemented for this type of card.")
990
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200991 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200992 if p.get('smsp'):
993 sw = self.update_smsp(p['smsp'])
994 if sw != '9000':
995 print("Programming SMSP failed with code %s"%sw)
996
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200997 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200998 if p.get('imsi'):
999 sw = self.update_imsi(p['imsi'])
1000 if sw != '9000':
1001 print("Programming IMSI failed with code %s"%sw)
1002
1003 # EF.ACC
1004 if p.get('acc'):
1005 sw = self.update_acc(p['acc'])
1006 if sw != '9000':
1007 print("Programming ACC failed with code %s"%sw)
1008
1009 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001010 if p.get('mcc') and p.get('mnc'):
1011 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1012 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001013 print("Programming PLMNsel failed with code %s"%sw)
1014
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001015 # EF.PLMNwAcT
1016 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001017 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1018 if sw != '9000':
1019 print("Programming PLMNwAcT failed with code %s"%sw)
1020
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001021 # EF.OPLMNwAcT
1022 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001023 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1024 if sw != '9000':
1025 print("Programming OPLMNwAcT failed with code %s"%sw)
1026
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001027 # EF.AD
1028 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001029 sw = self.update_ad(p['mnc'])
1030 if sw != '9000':
1031 print("Programming AD failed with code %s"%sw)
1032
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001033 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001034
1035 def erase(self):
1036 return
1037
Todd Neal9eeadfc2018-04-25 15:36:29 -05001038
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001039class SysmoISIMSJA2(Card):
1040 """
1041 sysmocom sysmoISIM-SJA2
1042 """
1043
1044 name = 'sysmoISIM-SJA2'
1045
1046 def __init__(self, ssc):
1047 super(SysmoISIMSJA2, self).__init__(ssc)
1048 self._scc.cla_byte = "00"
1049 self._scc.sel_ctrl = "0004" #request an FCP
1050
1051 @classmethod
1052 def autodetect(kls, scc):
1053 try:
1054 # Try card model #1
1055 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1056 if scc.get_atr() == toBytes(atr):
1057 return kls(scc)
1058
1059 # Try card model #2
1060 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1061 if scc.get_atr() == toBytes(atr):
1062 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001063
1064 # Try card model #3
1065 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1066 if scc.get_atr() == toBytes(atr):
1067 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001068 except:
1069 return None
1070 return None
1071
1072 def program(self, p):
1073 # authenticate as ADM using default key (written on the card..)
1074 if not p['pin_adm']:
1075 raise ValueError("Please provide a PIN-ADM as there is no default one")
1076 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1077
1078 # This type of card does not allow to reprogram the ICCID.
1079 # Reprogramming the ICCID would mess up the card os software
1080 # license management, so the ICCID must be kept at its factory
1081 # setting!
1082 if p.get('iccid'):
1083 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1084
1085 # select DF_GSM
1086 self._scc.select_file(['7f20'])
1087
1088 # write EF.IMSI
1089 if p.get('imsi'):
1090 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1091
1092 # EF.PLMNsel
1093 if p.get('mcc') and p.get('mnc'):
1094 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1095 if sw != '9000':
1096 print("Programming PLMNsel failed with code %s"%sw)
1097
1098 # EF.PLMNwAcT
1099 if p.get('mcc') and p.get('mnc'):
1100 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1101 if sw != '9000':
1102 print("Programming PLMNwAcT failed with code %s"%sw)
1103
1104 # EF.OPLMNwAcT
1105 if p.get('mcc') and p.get('mnc'):
1106 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1107 if sw != '9000':
1108 print("Programming OPLMNwAcT failed with code %s"%sw)
1109
Harald Welte32f0d412020-05-05 17:35:57 +02001110 # EF.HPLMNwAcT
1111 if p.get('mcc') and p.get('mnc'):
1112 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1113 if sw != '9000':
1114 print("Programming HPLMNwAcT failed with code %s"%sw)
1115
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001116 # EF.AD
1117 if p.get('mcc') and p.get('mnc'):
1118 sw = self.update_ad(p['mnc'])
1119 if sw != '9000':
1120 print("Programming AD failed with code %s"%sw)
1121
1122 # EF.SMSP
1123 if p.get('smsp'):
1124 r = self._scc.select_file(['3f00', '7f10'])
1125 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1126
1127 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1128 # hard linked to EF-USIM_AUTH_KEY)
1129 self._scc.select_file(['3f00'])
1130 self._scc.select_file(['a515'])
1131 if p.get('ki'):
1132 self._scc.update_binary('6f20', p['ki'], 1)
1133 if p.get('opc'):
1134 self._scc.update_binary('6f20', p['opc'], 17)
1135
1136 # update EF-USIM_AUTH_KEY in ADF.ISIM
1137 self._scc.select_file(['3f00'])
1138 aid = self.read_aid(isim = True)
Philipp Maierd9507862020-03-11 12:18:29 +01001139 if (aid):
1140 self._scc.select_adf(aid)
1141 if p.get('ki'):
1142 self._scc.update_binary('af20', p['ki'], 1)
1143 if p.get('opc'):
1144 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001145
1146 # update EF-USIM_AUTH_KEY in ADF.USIM
1147 self._scc.select_file(['3f00'])
1148 aid = self.read_aid()
Philipp Maierd9507862020-03-11 12:18:29 +01001149 if (aid):
1150 self._scc.select_adf(aid)
1151 if p.get('ki'):
1152 self._scc.update_binary('af20', p['ki'], 1)
1153 if p.get('opc'):
1154 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001155
1156 return
1157
1158 def erase(self):
1159 return
1160
1161
Todd Neal9eeadfc2018-04-25 15:36:29 -05001162# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001163_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001164 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001165 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001166
1167def card_autodetect(scc):
1168 for kls in _cards_classes:
1169 card = kls.autodetect(scc)
1170 if card is not None:
1171 card.reset()
1172 return card
1173 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001174
1175def card_detect(ctype, scc):
1176 # Detect type if needed
1177 card = None
1178 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1179
1180 if ctype in ("auto", "auto_once"):
1181 for kls in _cards_classes:
1182 card = kls.autodetect(scc)
1183 if card:
1184 print("Autodetected card type: %s" % card.name)
1185 card.reset()
1186 break
1187
1188 if card is None:
1189 print("Autodetection failed")
1190 return None
1191
1192 if ctype == "auto_once":
1193 ctype = card.name
1194
1195 elif ctype in ctypes:
1196 card = ctypes[ctype](scc)
1197
1198 else:
1199 raise ValueError("Unknown card type: %s" % ctype)
1200
1201 return card