blob: b9bd699e673992853de93252b4dbe4fa7c580829 [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
Harald Welteca673942020-06-03 15:19:40 +020027from pySim.ts_31_102 import EF_USIM_ADF_map
Supreeth Herle5ad9aec2020-03-24 17:26:40 +010028from pySim.ts_31_103 import EF_ISIM_ADF_map
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030029from pySim.utils import *
Alexander Chemeris8ad124a2018-01-10 14:17:55 +090030from smartcard.util import toBytes
Sylvain Munaut76504e02010-12-07 00:24:32 +010031
32class Card(object):
33
34 def __init__(self, scc):
35 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030036 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010037 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010038
Sylvain Munaut76504e02010-12-07 00:24:32 +010039 def reset(self):
40 self._scc.reset_card()
41
Philipp Maierd58c6322020-05-12 16:47:45 +020042 def erase(self):
43 print("warning: erasing is not supported for specified card type!")
44 return
45
Harald Welteca673942020-06-03 15:19:40 +020046 def file_exists(self, fid):
47 res_arr = self._scc.try_select_file(fid)
48 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020049 if res[1] != '9000':
50 return False
Harald Welteca673942020-06-03 15:19:40 +020051 return True
52
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030053 def verify_adm(self, key):
54 '''
55 Authenticate with ADM key
56 '''
57 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
58 return sw
59
60 def read_iccid(self):
61 (res, sw) = self._scc.read_binary(EF['ICCID'])
62 if sw == '9000':
63 return (dec_iccid(res), sw)
64 else:
65 return (None, sw)
66
67 def read_imsi(self):
68 (res, sw) = self._scc.read_binary(EF['IMSI'])
69 if sw == '9000':
70 return (dec_imsi(res), sw)
71 else:
72 return (None, sw)
73
74 def update_imsi(self, imsi):
75 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
76 return sw
77
78 def update_acc(self, acc):
79 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
80 return sw
81
Supreeth Herlea850a472020-03-19 12:44:11 +010082 def read_hplmn_act(self):
83 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
84 if sw == '9000':
85 return (format_xplmn_w_act(res), sw)
86 else:
87 return (None, sw)
88
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030089 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
90 """
91 Update Home PLMN with access technology bit-field
92
93 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
94 in ETSI TS 151 011 for the details of the access_tech field coding.
95 Some common values:
96 access_tech = '0080' # Only GSM is selected
97 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
98 """
99 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100100 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700101 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300102 hplmn = enc_plmn(mcc, mnc)
103 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700104 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300105 return sw
106
Supreeth Herle1757b262020-03-19 12:43:11 +0100107 def read_oplmn_act(self):
108 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
109 if sw == '9000':
110 return (format_xplmn_w_act(res), sw)
111 else:
112 return (None, sw)
113
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200114 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
115 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200116 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200117 """
118 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200119 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700120 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200121 hplmn = enc_plmn(mcc, mnc)
122 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700123 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200124 return sw
125
Supreeth Herle14084402020-03-19 12:42:10 +0100126 def read_plmn_act(self):
127 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
128 if sw == '9000':
129 return (format_xplmn_w_act(res), sw)
130 else:
131 return (None, sw)
132
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200133 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
134 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200135 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200136 """
137 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200138 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700139 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200140 hplmn = enc_plmn(mcc, mnc)
141 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700142 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200143 return sw
144
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200145 def update_plmnsel(self, mcc, mnc):
146 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700147 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200148 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200149 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
150 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200151
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300152 def update_smsp(self, smsp):
153 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
154 return sw
155
Philipp Maieree908ae2019-03-21 16:21:12 +0100156 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200157 #See also: 3GPP TS 31.102, chapter 4.2.18
158 mnclen = len(str(mnc))
159 if mnclen == 1:
160 mnclen = 2
161 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100162 raise RuntimeError('unable to calculate proper mnclen')
163
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200164 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
165
166 # Reset contents to EF.AD in case the file is uninintalized
167 if data.lower() == "ffffffff":
168 data = "00000000"
169
170 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100171 data, sw = self._scc.update_binary(EF['AD'], content)
172 return sw
173
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300174 def read_spn(self):
175 (spn, sw) = self._scc.read_binary(EF['SPN'])
176 if sw == '9000':
177 return (dec_spn(spn), sw)
178 else:
179 return (None, sw)
180
181 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
182 content = enc_spn(name, hplmn_disp, oplmn_disp)
183 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
184 return sw
185
Supreeth Herled21349a2020-04-01 08:37:47 +0200186 def read_binary(self, ef, length=None, offset=0):
187 ef_path = ef in EF and EF[ef] or ef
188 return self._scc.read_binary(ef_path, length, offset)
189
Supreeth Herlead10d662020-04-01 08:43:08 +0200190 def read_record(self, ef, rec_no):
191 ef_path = ef in EF and EF[ef] or ef
192 return self._scc.read_record(ef_path, rec_no)
193
Supreeth Herle98a69272020-03-18 12:14:48 +0100194 def read_gid1(self):
195 (res, sw) = self._scc.read_binary(EF['GID1'])
196 if sw == '9000':
197 return (res, sw)
198 else:
199 return (None, sw)
200
Supreeth Herle6d66af62020-03-19 12:49:16 +0100201 def read_msisdn(self):
202 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
203 if sw == '9000':
204 return (dec_msisdn(res), sw)
205 else:
206 return (None, sw)
207
Supreeth Herlee4e98312020-03-18 11:33:14 +0100208 # Fetch all the AIDs present on UICC
209 def read_aids(self):
210 try:
211 # Find out how many records the EF.DIR has
212 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100213 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100214 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100215 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100216 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
217 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
218 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
219 except Exception as e:
220 print("Can't read AIDs from SIM -- %s" % (str(e),))
221
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100222 # Select ADF.U/ISIM in the Card using its full AID
223 def select_adf_by_aid(self, adf="usim"):
224 # Check for valid ADF name
225 if adf not in ["usim", "isim"]:
226 return None
227
228 # First (known) halves of the U/ISIM AID
229 aid_map = {}
230 aid_map["usim"] = "a0000000871002"
231 aid_map["isim"] = "a0000000871004"
232
233 for aid in self._aids:
234 if aid_map[adf] in aid:
235 (res, sw) = self._scc.select_adf(aid)
236 return sw
237
238 return None
239
Philipp Maier5c2cc662020-05-12 16:27:12 +0200240 # Erase the contents of a file
241 def erase_binary(self, ef):
242 len = self._scc.binary_size(ef)
243 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
244
245 # Erase the contents of a single record
246 def erase_record(self, ef, rec_no):
247 len = self._scc.record_size(ef)
248 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
249
Harald Welteca673942020-06-03 15:19:40 +0200250class UsimCard(Card):
251 def __init__(self, ssc):
252 super(UsimCard, self).__init__(ssc)
253
254 def read_ehplmn(self):
255 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
256 if sw == '9000':
257 return (format_xplmn(res), sw)
258 else:
259 return (None, sw)
260
261 def update_ehplmn(self, mcc, mnc):
262 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
263 size = len(data[0]) // 2
264 ehplmn = enc_plmn(mcc, mnc)
265 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
266 return sw
267
herlesupreethf8232db2020-09-29 10:03:06 +0200268 def read_epdgid(self):
269 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
270 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100271 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200272 else:
273 return (None, sw)
274
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200275 def update_epdgid(self, epdgid):
Supreeth Herle3b342c22020-03-24 16:15:02 +0100276 epdgid_tlv = enc_addr_tlv(epdgid)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200277 data, sw = self._scc.update_binary(
278 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
279 return sw
Harald Welteca673942020-06-03 15:19:40 +0200280
Supreeth Herle99d55552020-03-24 13:03:43 +0100281 def read_ePDGSelection(self):
282 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
283 if sw == '9000':
284 return (format_ePDGSelection(res), sw)
285 else:
286 return (None, sw)
287
Supreeth Herlef964df42020-03-24 13:15:37 +0100288 def update_ePDGSelection(self, mcc, mnc):
289 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
290 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
291 # Reset contents
292 # 80 - Tag value
293 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
294 elif sw == '9000':
295 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
296 return sw
297
herlesupreeth4a3580b2020-09-29 10:11:36 +0200298 def read_ust(self):
299 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
300 if sw == '9000':
301 # Print those which are available
302 return ([res, dec_st(res, table="usim")], sw)
303 else:
304 return ([None, None], sw)
305
Supreeth Herleacc222f2020-03-24 13:26:53 +0100306 def update_ust(self, service, bit=1):
307 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
308 if sw == '9000':
309 content = enc_st(res, service, bit)
310 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
311 return sw
312
herlesupreethecbada92020-12-23 09:24:29 +0100313class IsimCard(Card):
314 def __init__(self, ssc):
315 super(IsimCard, self).__init__(ssc)
316
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100317 def read_pcscf(self):
318 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
319 pcscf_recs = ""
320 for i in range(0, rec_cnt):
321 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
322 if sw == '9000':
323 content = dec_addr_tlv(res)
324 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
325 else:
326 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
327 return pcscf_recs
328
Sylvain Munaut76504e02010-12-07 00:24:32 +0100329
330class _MagicSimBase(Card):
331 """
332 Theses cards uses several record based EFs to store the provider infos,
333 each possible provider uses a specific record number in each EF. The
334 indexes used are ( where N is the number of providers supported ) :
335 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100336 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100337
338 * 3f00/7f4d/8f0c : Operator Name
339
340 bytes 0-15 : provider name, padded with 0xff
341 byte 16 : length of the provider name
342 byte 17 : 01 for valid records, 00 otherwise
343
344 * 3f00/7f4d/8f0d : Programmable Binary EFs
345
346 * 3f00/7f4d/8f0e : Programmable Record EFs
347
348 """
349
350 @classmethod
351 def autodetect(kls, scc):
352 try:
353 for p, l, t in kls._files.values():
354 if not t:
355 continue
356 if scc.record_size(['3f00', '7f4d', p]) != l:
357 return None
358 except:
359 return None
360
361 return kls(scc)
362
363 def _get_count(self):
364 """
365 Selects the file and returns the total number of entries
366 and entry size
367 """
368 f = self._files['name']
369
370 r = self._scc.select_file(['3f00', '7f4d', f[0]])
371 rec_len = int(r[-1][28:30], 16)
372 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200373 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100374
375 if (rec_cnt < 1) or (rec_len != f[1]):
376 raise RuntimeError('Bad card type')
377
378 return rec_cnt
379
380 def program(self, p):
381 # Go to dir
382 self._scc.select_file(['3f00', '7f4d'])
383
384 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400385 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100386
387 # Operator name ( 3f00/7f4d/8f0c )
388 self._scc.update_record(self._files['name'][0], 2,
389 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
390 )
391
392 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
393 v = ''
394
395 # inline Ki
396 if self._ki_file is None:
397 v += p['ki']
398
399 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400400 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100401
402 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400403 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100404
405 # Ki
406 if self._ki_file:
407 v += self._ki_file + '10' + p['ki']
408
409 # PLMN_Sel
410 v+= '6f30' + '18' + rpad(hplmn, 36)
411
Alexander Chemeris21885242013-07-02 16:56:55 +0400412 # ACC
413 # This doesn't work with "fake" SuperSIM cards,
414 # but will hopefully work with real SuperSIMs.
415 if p.get('acc') is not None:
416 v+= '6f78' + '02' + lpad(p['acc'], 4)
417
Sylvain Munaut76504e02010-12-07 00:24:32 +0100418 self._scc.update_record(self._files['b_ef'][0], 1,
419 rpad(v, self._files['b_ef'][1]*2)
420 )
421
422 # SMSP ( 3f00/7f4d/8f0e )
423 # FIXME
424
425 # Write PLMN_Sel forcefully as well
426 r = self._scc.select_file(['3f00', '7f20', '6f30'])
427 tl = int(r[-1][4:8], 16)
428
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400429 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100430 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
431
432 def erase(self):
433 # Dummy
434 df = {}
435 for k, v in self._files.iteritems():
436 ofs = 1
437 fv = v[1] * 'ff'
438 if k == 'name':
439 ofs = 2
440 fv = fv[0:-4] + '0000'
441 df[v[0]] = (fv, ofs)
442
443 # Write
444 for n in range(0,self._get_count()):
445 for k, (msg, ofs) in df.iteritems():
446 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
447
448
449class SuperSim(_MagicSimBase):
450
451 name = 'supersim'
452
453 _files = {
454 'name' : ('8f0c', 18, True),
455 'b_ef' : ('8f0d', 74, True),
456 'r_ef' : ('8f0e', 50, True),
457 }
458
459 _ki_file = None
460
461
462class MagicSim(_MagicSimBase):
463
464 name = 'magicsim'
465
466 _files = {
467 'name' : ('8f0c', 18, True),
468 'b_ef' : ('8f0d', 130, True),
469 'r_ef' : ('8f0e', 102, False),
470 }
471
472 _ki_file = '6f1b'
473
474
475class FakeMagicSim(Card):
476 """
477 Theses cards have a record based EF 3f00/000c that contains the provider
478 informations. See the program method for its format. The records go from
479 1 to N.
480 """
481
482 name = 'fakemagicsim'
483
484 @classmethod
485 def autodetect(kls, scc):
486 try:
487 if scc.record_size(['3f00', '000c']) != 0x5a:
488 return None
489 except:
490 return None
491
492 return kls(scc)
493
494 def _get_infos(self):
495 """
496 Selects the file and returns the total number of entries
497 and entry size
498 """
499
500 r = self._scc.select_file(['3f00', '000c'])
501 rec_len = int(r[-1][28:30], 16)
502 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200503 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100504
505 if (rec_cnt < 1) or (rec_len != 0x5a):
506 raise RuntimeError('Bad card type')
507
508 return rec_cnt, rec_len
509
510 def program(self, p):
511 # Home PLMN
512 r = self._scc.select_file(['3f00', '7f20', '6f30'])
513 tl = int(r[-1][4:8], 16)
514
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400515 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100516 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
517
518 # Get total number of entries and entry size
519 rec_cnt, rec_len = self._get_infos()
520
521 # Set first entry
522 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200523 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100524 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200525 enc_iccid(p['iccid']) + # 10b ICCID
526 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
527 p['ki'] + # 16b Ki
528 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100529 )
530 self._scc.update_record('000c', 1, entry)
531
532 def erase(self):
533 # Get total number of entries and entry size
534 rec_cnt, rec_len = self._get_infos()
535
536 # Erase all entries
537 entry = 'ff' * rec_len
538 for i in range(0, rec_cnt):
539 self._scc.update_record('000c', 1+i, entry)
540
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200541
Harald Welte3156d902011-03-22 21:48:19 +0100542class GrcardSim(Card):
543 """
544 Greencard (grcard.cn) HZCOS GSM SIM
545 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
546 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
547 """
548
549 name = 'grcardsim'
550
551 @classmethod
552 def autodetect(kls, scc):
553 return None
554
555 def program(self, p):
556 # We don't really know yet what ADM PIN 4 is about
557 #self._scc.verify_chv(4, h2b("4444444444444444"))
558
559 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100560 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200561 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100562 else:
563 pin = h2b("4444444444444444")
564 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100565
566 # EF.ICCID
567 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400568 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100569
570 # EF.IMSI
571 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400572 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100573
574 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400575 if p.get('acc') is not None:
576 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100577
578 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200579 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200580 r = self._scc.select_file(['3f00', '7f10', '6f42'])
581 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100582
583 # Set the Ki using proprietary command
584 pdu = '80d4020010' + p['ki']
585 data, sw = self._scc._tp.send_apdu(pdu)
586
587 # EF.HPLMN
588 r = self._scc.select_file(['3f00', '7f20', '6f30'])
589 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400590 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100591 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
592
593 # EF.SPN (Service Provider Name)
594 r = self._scc.select_file(['3f00', '7f20', '6f30'])
595 size = int(r[-1][4:8], 16)
596 # FIXME
597
598 # FIXME: EF.MSISDN
599
Sylvain Munaut76504e02010-12-07 00:24:32 +0100600
Harald Weltee10394b2011-12-07 12:34:14 +0100601class SysmoSIMgr1(GrcardSim):
602 """
603 sysmocom sysmoSIM-GR1
604 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
605 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
606 """
607 name = 'sysmosim-gr1'
608
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200609 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200610 def autodetect(kls, scc):
611 try:
612 # Look for ATR
613 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
614 return kls(scc)
615 except:
616 return None
617 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200618
Harald Welteca673942020-06-03 15:19:40 +0200619class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100620 """
621 sysmocom sysmoUSIM-GR1
622 """
623 name = 'sysmoUSIM-GR1'
624
625 @classmethod
626 def autodetect(kls, scc):
627 # TODO: Access the ATR
628 return None
629
630 def program(self, p):
631 # TODO: check if verify_chv could be used or what it needs
632 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
633 # Unlock the card..
634 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
635
636 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100637 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400638 p['opc'] + # 32b OPC
639 enc_iccid(p['iccid']) + # 10b ICCID
640 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100641 )
642 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
643
Sylvain Munaut053c8952013-07-02 15:12:32 +0200644
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100645class SysmoSIMgr2(Card):
646 """
647 sysmocom sysmoSIM-GR2
648 """
649
650 name = 'sysmoSIM-GR2'
651
652 @classmethod
653 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900654 try:
655 # Look for ATR
656 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
657 return kls(scc)
658 except:
659 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100660 return None
661
662 def program(self, p):
663
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200664 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100665 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200666
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100667 # authenticate as SUPER ADM using default key
668 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
669
670 # set ADM pin using proprietary command
671 # INS: D4
672 # P1: 3A for PIN, 3B for PUK
673 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
674 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100675 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200676 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100677 else:
678 pin = h2b("4444444444444444")
679
680 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100681 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200682
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100683 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100684
685 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100686
687 # write EF.ICCID
688 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
689
690 # select DF_GSM
691 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200692
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100693 # write EF.IMSI
694 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
695
696 # write EF.ACC
697 if p.get('acc') is not None:
698 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
699
700 # get size and write EF.HPLMN
701 r = self._scc.select_file(['6f30'])
702 size = int(r[-1][4:8], 16)
703 hplmn = enc_plmn(p['mcc'], p['mnc'])
704 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
705
706 # set COMP128 version 0 in proprietary file
707 data, sw = self._scc.update_binary('0001', '001000')
708
709 # set Ki in proprietary file
710 data, sw = self._scc.update_binary('0001', p['ki'], 3)
711
712 # select DF_TELECOM
713 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200714
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100715 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200716 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200717 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100718
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100719
Harald Welteca673942020-06-03 15:19:40 +0200720class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100721 """
722 sysmocom sysmoUSIM-SJS1
723 """
724
725 name = 'sysmoUSIM-SJS1'
726
727 def __init__(self, ssc):
728 super(SysmoUSIMSJS1, self).__init__(ssc)
729 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100730 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100731
732 @classmethod
733 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900734 try:
735 # Look for ATR
736 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"):
737 return kls(scc)
738 except:
739 return None
Jan Balke3e840672015-01-26 15:36:27 +0100740 return None
741
742 def program(self, p):
743
Philipp Maiere9604882017-03-21 17:24:31 +0100744 # authenticate as ADM using default key (written on the card..)
745 if not p['pin_adm']:
746 raise ValueError("Please provide a PIN-ADM as there is no default one")
747 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100748
749 # select MF
750 r = self._scc.select_file(['3f00'])
751
Philipp Maiere9604882017-03-21 17:24:31 +0100752 # write EF.ICCID
753 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
754
Jan Balke3e840672015-01-26 15:36:27 +0100755 # select DF_GSM
756 r = self._scc.select_file(['7f20'])
757
Jan Balke3e840672015-01-26 15:36:27 +0100758 # set Ki in proprietary file
759 data, sw = self._scc.update_binary('00FF', p['ki'])
760
Philipp Maier1be35bf2018-07-13 11:29:03 +0200761 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200762 if 'opc' in p:
763 content = "01" + p['opc']
764 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100765
Supreeth Herle7947d922019-06-08 07:50:53 +0200766 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100767 if p.get('name') is not None:
768 content = enc_spn(p['name'], True, True)
769 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200770
Supreeth Herlec8796a32019-12-23 12:23:42 +0100771 if p.get('acc') is not None:
772 self.update_acc(p['acc'])
773
Jan Balke3e840672015-01-26 15:36:27 +0100774 # write EF.IMSI
775 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
776
Philipp Maier2d15ea02019-03-20 12:40:36 +0100777 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200778 if p.get('mcc') and p.get('mnc'):
779 sw = self.update_plmnsel(p['mcc'], p['mnc'])
780 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100781 print("Programming PLMNsel failed with code %s"%sw)
782
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200783 # EF.PLMNwAcT
784 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100785 sw = self.update_plmn_act(p['mcc'], p['mnc'])
786 if sw != '9000':
787 print("Programming PLMNwAcT failed with code %s"%sw)
788
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200789 # EF.OPLMNwAcT
790 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100791 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
792 if sw != '9000':
793 print("Programming OPLMNwAcT failed with code %s"%sw)
794
Supreeth Herlef442fb42020-01-21 12:47:32 +0100795 # EF.HPLMNwAcT
796 if p.get('mcc') and p.get('mnc'):
797 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
798 if sw != '9000':
799 print("Programming HPLMNwAcT failed with code %s"%sw)
800
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200801 # EF.AD
802 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100803 sw = self.update_ad(p['mnc'])
804 if sw != '9000':
805 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100806
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200807 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200808 if p.get('smsp'):
809 r = self._scc.select_file(['3f00', '7f10'])
810 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100811
Supreeth Herle5a541012019-12-22 08:59:16 +0100812 # EF.MSISDN
813 # TODO: Alpha Identifier (currently 'ff'O * 20)
814 # TODO: Capability/Configuration1 Record Identifier
815 # TODO: Extension1 Record Identifier
816 if p.get('msisdn') is not None:
817 msisdn = enc_msisdn(p['msisdn'])
818 data = 'ff' * 20 + msisdn + 'ff' * 2
819
820 r = self._scc.select_file(['3f00', '7f10'])
821 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
822
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900823
herlesupreeth4a3580b2020-09-29 10:11:36 +0200824class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900825 """
826 FairwavesSIM
827
828 The SIM card is operating according to the standard.
829 For Ki/OP/OPC programming the following files are additionally open for writing:
830 3F00/7F20/FF01 – OP/OPC:
831 byte 1 = 0x01, bytes 2-17: OPC;
832 byte 1 = 0x00, bytes 2-17: OP;
833 3F00/7F20/FF02: Ki
834 """
835
Philipp Maier5a876312019-11-11 11:01:46 +0100836 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900837 # Propriatary files
838 _EF_num = {
839 'Ki': 'FF02',
840 'OP/OPC': 'FF01',
841 }
842 _EF = {
843 'Ki': DF['GSM']+[_EF_num['Ki']],
844 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
845 }
846
847 def __init__(self, ssc):
848 super(FairwavesSIM, self).__init__(ssc)
849 self._adm_chv_num = 0x11
850 self._adm2_chv_num = 0x12
851
852
853 @classmethod
854 def autodetect(kls, scc):
855 try:
856 # Look for ATR
857 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"):
858 return kls(scc)
859 except:
860 return None
861 return None
862
863
864 def verify_adm2(self, key):
865 '''
866 Authenticate with ADM2 key.
867
868 Fairwaves SIM cards support hierarchical key structure and ADM2 key
869 is a key which has access to proprietary files (Ki and OP/OPC).
870 That said, ADM key inherits permissions of ADM2 key and thus we rarely
871 need ADM2 key per se.
872 '''
873 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
874 return sw
875
876
877 def read_ki(self):
878 """
879 Read Ki in proprietary file.
880
881 Requires ADM1 access level
882 """
883 return self._scc.read_binary(self._EF['Ki'])
884
885
886 def update_ki(self, ki):
887 """
888 Set Ki in proprietary file.
889
890 Requires ADM1 access level
891 """
892 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
893 return sw
894
895
896 def read_op_opc(self):
897 """
898 Read Ki in proprietary file.
899
900 Requires ADM1 access level
901 """
902 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
903 type = 'OP' if ef[0:2] == '00' else 'OPC'
904 return ((type, ef[2:]), sw)
905
906
907 def update_op(self, op):
908 """
909 Set OP in proprietary file.
910
911 Requires ADM1 access level
912 """
913 content = '00' + op
914 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
915 return sw
916
917
918 def update_opc(self, opc):
919 """
920 Set OPC in proprietary file.
921
922 Requires ADM1 access level
923 """
924 content = '01' + opc
925 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
926 return sw
927
928
929 def program(self, p):
930 # authenticate as ADM1
931 if not p['pin_adm']:
932 raise ValueError("Please provide a PIN-ADM as there is no default one")
933 sw = self.verify_adm(h2b(p['pin_adm']))
934 if sw != '9000':
935 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
936
937 # TODO: Set operator name
938 if p.get('smsp') is not None:
939 sw = self.update_smsp(p['smsp'])
940 if sw != '9000':
941 print("Programming SMSP failed with code %s"%sw)
942 # This SIM doesn't support changing ICCID
943 if p.get('mcc') is not None and p.get('mnc') is not None:
944 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
945 if sw != '9000':
946 print("Programming MCC/MNC failed with code %s"%sw)
947 if p.get('imsi') is not None:
948 sw = self.update_imsi(p['imsi'])
949 if sw != '9000':
950 print("Programming IMSI failed with code %s"%sw)
951 if p.get('ki') is not None:
952 sw = self.update_ki(p['ki'])
953 if sw != '9000':
954 print("Programming Ki failed with code %s"%sw)
955 if p.get('opc') is not None:
956 sw = self.update_opc(p['opc'])
957 if sw != '9000':
958 print("Programming OPC failed with code %s"%sw)
959 if p.get('acc') is not None:
960 sw = self.update_acc(p['acc'])
961 if sw != '9000':
962 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100963
Todd Neal9eeadfc2018-04-25 15:36:29 -0500964class OpenCellsSim(Card):
965 """
966 OpenCellsSim
967
968 """
969
Philipp Maier5a876312019-11-11 11:01:46 +0100970 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500971
972 def __init__(self, ssc):
973 super(OpenCellsSim, self).__init__(ssc)
974 self._adm_chv_num = 0x0A
975
976
977 @classmethod
978 def autodetect(kls, scc):
979 try:
980 # Look for ATR
981 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"):
982 return kls(scc)
983 except:
984 return None
985 return None
986
987
988 def program(self, p):
989 if not p['pin_adm']:
990 raise ValueError("Please provide a PIN-ADM as there is no default one")
991 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
992
993 # select MF
994 r = self._scc.select_file(['3f00'])
995
996 # write EF.ICCID
997 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
998
999 r = self._scc.select_file(['7ff0'])
1000
1001 # set Ki in proprietary file
1002 data, sw = self._scc.update_binary('FF02', p['ki'])
1003
1004 # set OPC in proprietary file
1005 data, sw = self._scc.update_binary('FF01', p['opc'])
1006
1007 # select DF_GSM
1008 r = self._scc.select_file(['7f20'])
1009
1010 # write EF.IMSI
1011 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1012
herlesupreeth4a3580b2020-09-29 10:11:36 +02001013class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001014 """
1015 WavemobileSim
1016
1017 """
1018
1019 name = 'Wavemobile-SIM'
1020
1021 def __init__(self, ssc):
1022 super(WavemobileSim, self).__init__(ssc)
1023 self._adm_chv_num = 0x0A
1024 self._scc.cla_byte = "00"
1025 self._scc.sel_ctrl = "0004" #request an FCP
1026
1027 @classmethod
1028 def autodetect(kls, scc):
1029 try:
1030 # Look for ATR
1031 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"):
1032 return kls(scc)
1033 except:
1034 return None
1035 return None
1036
1037 def program(self, p):
1038 if not p['pin_adm']:
1039 raise ValueError("Please provide a PIN-ADM as there is no default one")
1040 sw = self.verify_adm(h2b(p['pin_adm']))
1041 if sw != '9000':
1042 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1043
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001044 # EF.ICCID
1045 # TODO: Add programming of the ICCID
1046 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001047 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1048
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001049 # KI (Presumably a propritary file)
1050 # TODO: Add programming of KI
1051 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001052 print("Warning: Programming of the KI is not implemented for this type of card.")
1053
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001054 # OPc (Presumably a propritary file)
1055 # TODO: Add programming of OPc
1056 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001057 print("Warning: Programming of the OPc is not implemented for this type of card.")
1058
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001059 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001060 if p.get('smsp'):
1061 sw = self.update_smsp(p['smsp'])
1062 if sw != '9000':
1063 print("Programming SMSP failed with code %s"%sw)
1064
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001065 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001066 if p.get('imsi'):
1067 sw = self.update_imsi(p['imsi'])
1068 if sw != '9000':
1069 print("Programming IMSI failed with code %s"%sw)
1070
1071 # EF.ACC
1072 if p.get('acc'):
1073 sw = self.update_acc(p['acc'])
1074 if sw != '9000':
1075 print("Programming ACC failed with code %s"%sw)
1076
1077 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001078 if p.get('mcc') and p.get('mnc'):
1079 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1080 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001081 print("Programming PLMNsel failed with code %s"%sw)
1082
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001083 # EF.PLMNwAcT
1084 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001085 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1086 if sw != '9000':
1087 print("Programming PLMNwAcT failed with code %s"%sw)
1088
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001089 # EF.OPLMNwAcT
1090 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001091 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1092 if sw != '9000':
1093 print("Programming OPLMNwAcT failed with code %s"%sw)
1094
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001095 # EF.AD
1096 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001097 sw = self.update_ad(p['mnc'])
1098 if sw != '9000':
1099 print("Programming AD failed with code %s"%sw)
1100
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001101 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001102
Todd Neal9eeadfc2018-04-25 15:36:29 -05001103
herlesupreethb0c7d122020-12-23 09:25:46 +01001104class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001105 """
1106 sysmocom sysmoISIM-SJA2
1107 """
1108
1109 name = 'sysmoISIM-SJA2'
1110
1111 def __init__(self, ssc):
1112 super(SysmoISIMSJA2, self).__init__(ssc)
1113 self._scc.cla_byte = "00"
1114 self._scc.sel_ctrl = "0004" #request an FCP
1115
1116 @classmethod
1117 def autodetect(kls, scc):
1118 try:
1119 # Try card model #1
1120 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1121 if scc.get_atr() == toBytes(atr):
1122 return kls(scc)
1123
1124 # Try card model #2
1125 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1126 if scc.get_atr() == toBytes(atr):
1127 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001128
1129 # Try card model #3
1130 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1131 if scc.get_atr() == toBytes(atr):
1132 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001133 except:
1134 return None
1135 return None
1136
1137 def program(self, p):
1138 # authenticate as ADM using default key (written on the card..)
1139 if not p['pin_adm']:
1140 raise ValueError("Please provide a PIN-ADM as there is no default one")
1141 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1142
1143 # This type of card does not allow to reprogram the ICCID.
1144 # Reprogramming the ICCID would mess up the card os software
1145 # license management, so the ICCID must be kept at its factory
1146 # setting!
1147 if p.get('iccid'):
1148 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1149
1150 # select DF_GSM
1151 self._scc.select_file(['7f20'])
1152
1153 # write EF.IMSI
1154 if p.get('imsi'):
1155 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1156
1157 # EF.PLMNsel
1158 if p.get('mcc') and p.get('mnc'):
1159 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1160 if sw != '9000':
1161 print("Programming PLMNsel failed with code %s"%sw)
1162
1163 # EF.PLMNwAcT
1164 if p.get('mcc') and p.get('mnc'):
1165 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1166 if sw != '9000':
1167 print("Programming PLMNwAcT failed with code %s"%sw)
1168
1169 # EF.OPLMNwAcT
1170 if p.get('mcc') and p.get('mnc'):
1171 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1172 if sw != '9000':
1173 print("Programming OPLMNwAcT failed with code %s"%sw)
1174
Harald Welte32f0d412020-05-05 17:35:57 +02001175 # EF.HPLMNwAcT
1176 if p.get('mcc') and p.get('mnc'):
1177 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1178 if sw != '9000':
1179 print("Programming HPLMNwAcT failed with code %s"%sw)
1180
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001181 # EF.AD
1182 if p.get('mcc') and p.get('mnc'):
1183 sw = self.update_ad(p['mnc'])
1184 if sw != '9000':
1185 print("Programming AD failed with code %s"%sw)
1186
1187 # EF.SMSP
1188 if p.get('smsp'):
1189 r = self._scc.select_file(['3f00', '7f10'])
1190 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1191
Supreeth Herle80164052020-03-23 12:06:29 +01001192 # Populate AIDs
1193 self.read_aids()
1194
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001195 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1196 # hard linked to EF-USIM_AUTH_KEY)
1197 self._scc.select_file(['3f00'])
1198 self._scc.select_file(['a515'])
1199 if p.get('ki'):
1200 self._scc.update_binary('6f20', p['ki'], 1)
1201 if p.get('opc'):
1202 self._scc.update_binary('6f20', p['opc'], 17)
1203
1204 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001205 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001206 if p.get('ki'):
1207 self._scc.update_binary('af20', p['ki'], 1)
1208 if p.get('opc'):
1209 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001210
herlesupreeth1a13c442020-09-11 21:16:51 +02001211 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001212 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001213 if p.get('ki'):
1214 self._scc.update_binary('af20', p['ki'], 1)
1215 if p.get('opc'):
1216 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001217
Harald Welteca673942020-06-03 15:19:40 +02001218 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001219 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001220 if p.get('mcc') and p.get('mnc'):
1221 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1222 if sw != '9000':
1223 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001224
1225 # update EF.ePDGId in ADF.USIM
1226 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1227 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001228 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001229 if sw != '9000':
1230 print("Programming ePDGId failed with code %s"%sw)
1231
Supreeth Herlef964df42020-03-24 13:15:37 +01001232 # update EF.ePDGSelection in ADF.USIM
1233 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1234 if p.get('epdgSelection'):
1235 epdg_plmn = p['epdgSelection']
1236 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1237 else:
1238 sw = self.update_ePDGSelection("", "")
1239 if sw != '9000':
1240 print("Programming ePDGSelection failed with code %s"%sw)
1241
1242
Supreeth Herleacc222f2020-03-24 13:26:53 +01001243 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1244 # Set service 106 and 107 as available in EF.UST
1245 if self.file_exists(EF_USIM_ADF_map['UST']):
1246 if p.get('epdgSelection') and p.get('epdgid'):
1247 sw = self.update_ust(106, 1)
1248 if sw != '9000':
1249 print("Programming UST failed with code %s"%sw)
1250 sw = self.update_ust(107, 1)
1251 if sw != '9000':
1252 print("Programming UST failed with code %s"%sw)
1253
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001254 return
1255
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001256
Todd Neal9eeadfc2018-04-25 15:36:29 -05001257# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001258_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001259 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001260 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001261
1262def card_autodetect(scc):
1263 for kls in _cards_classes:
1264 card = kls.autodetect(scc)
1265 if card is not None:
1266 card.reset()
1267 return card
1268 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001269
1270def card_detect(ctype, scc):
1271 # Detect type if needed
1272 card = None
1273 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1274
1275 if ctype in ("auto", "auto_once"):
1276 for kls in _cards_classes:
1277 card = kls.autodetect(scc)
1278 if card:
1279 print("Autodetected card type: %s" % card.name)
1280 card.reset()
1281 break
1282
1283 if card is None:
1284 print("Autodetection failed")
1285 return None
1286
1287 if ctype == "auto_once":
1288 ctype = card.name
1289
1290 elif ctype in ctypes:
1291 card = ctypes[ctype](scc)
1292
1293 else:
1294 raise ValueError("Unknown card type: %s" % ctype)
1295
1296 return card