blob: 0b2d2a6d1e88b27ed3ed5bac1695f0617c69f646 [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
Supreeth Herlecf727f22020-03-24 17:32:21 +0100329 def update_pcscf(self, pcscf):
330 if len(pcscf) > 0:
331 content = enc_addr_tlv(pcscf)
332 else:
333 # Just the tag value
334 content = '80'
335 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
336 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, rpad(content, rec_size_bytes*2))
337 return sw
338
Sylvain Munaut76504e02010-12-07 00:24:32 +0100339
340class _MagicSimBase(Card):
341 """
342 Theses cards uses several record based EFs to store the provider infos,
343 each possible provider uses a specific record number in each EF. The
344 indexes used are ( where N is the number of providers supported ) :
345 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100346 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100347
348 * 3f00/7f4d/8f0c : Operator Name
349
350 bytes 0-15 : provider name, padded with 0xff
351 byte 16 : length of the provider name
352 byte 17 : 01 for valid records, 00 otherwise
353
354 * 3f00/7f4d/8f0d : Programmable Binary EFs
355
356 * 3f00/7f4d/8f0e : Programmable Record EFs
357
358 """
359
360 @classmethod
361 def autodetect(kls, scc):
362 try:
363 for p, l, t in kls._files.values():
364 if not t:
365 continue
366 if scc.record_size(['3f00', '7f4d', p]) != l:
367 return None
368 except:
369 return None
370
371 return kls(scc)
372
373 def _get_count(self):
374 """
375 Selects the file and returns the total number of entries
376 and entry size
377 """
378 f = self._files['name']
379
380 r = self._scc.select_file(['3f00', '7f4d', f[0]])
381 rec_len = int(r[-1][28:30], 16)
382 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200383 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100384
385 if (rec_cnt < 1) or (rec_len != f[1]):
386 raise RuntimeError('Bad card type')
387
388 return rec_cnt
389
390 def program(self, p):
391 # Go to dir
392 self._scc.select_file(['3f00', '7f4d'])
393
394 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400395 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100396
397 # Operator name ( 3f00/7f4d/8f0c )
398 self._scc.update_record(self._files['name'][0], 2,
399 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
400 )
401
402 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
403 v = ''
404
405 # inline Ki
406 if self._ki_file is None:
407 v += p['ki']
408
409 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400410 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100411
412 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400413 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100414
415 # Ki
416 if self._ki_file:
417 v += self._ki_file + '10' + p['ki']
418
419 # PLMN_Sel
420 v+= '6f30' + '18' + rpad(hplmn, 36)
421
Alexander Chemeris21885242013-07-02 16:56:55 +0400422 # ACC
423 # This doesn't work with "fake" SuperSIM cards,
424 # but will hopefully work with real SuperSIMs.
425 if p.get('acc') is not None:
426 v+= '6f78' + '02' + lpad(p['acc'], 4)
427
Sylvain Munaut76504e02010-12-07 00:24:32 +0100428 self._scc.update_record(self._files['b_ef'][0], 1,
429 rpad(v, self._files['b_ef'][1]*2)
430 )
431
432 # SMSP ( 3f00/7f4d/8f0e )
433 # FIXME
434
435 # Write PLMN_Sel forcefully as well
436 r = self._scc.select_file(['3f00', '7f20', '6f30'])
437 tl = int(r[-1][4:8], 16)
438
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400439 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100440 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
441
442 def erase(self):
443 # Dummy
444 df = {}
445 for k, v in self._files.iteritems():
446 ofs = 1
447 fv = v[1] * 'ff'
448 if k == 'name':
449 ofs = 2
450 fv = fv[0:-4] + '0000'
451 df[v[0]] = (fv, ofs)
452
453 # Write
454 for n in range(0,self._get_count()):
455 for k, (msg, ofs) in df.iteritems():
456 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
457
458
459class SuperSim(_MagicSimBase):
460
461 name = 'supersim'
462
463 _files = {
464 'name' : ('8f0c', 18, True),
465 'b_ef' : ('8f0d', 74, True),
466 'r_ef' : ('8f0e', 50, True),
467 }
468
469 _ki_file = None
470
471
472class MagicSim(_MagicSimBase):
473
474 name = 'magicsim'
475
476 _files = {
477 'name' : ('8f0c', 18, True),
478 'b_ef' : ('8f0d', 130, True),
479 'r_ef' : ('8f0e', 102, False),
480 }
481
482 _ki_file = '6f1b'
483
484
485class FakeMagicSim(Card):
486 """
487 Theses cards have a record based EF 3f00/000c that contains the provider
488 informations. See the program method for its format. The records go from
489 1 to N.
490 """
491
492 name = 'fakemagicsim'
493
494 @classmethod
495 def autodetect(kls, scc):
496 try:
497 if scc.record_size(['3f00', '000c']) != 0x5a:
498 return None
499 except:
500 return None
501
502 return kls(scc)
503
504 def _get_infos(self):
505 """
506 Selects the file and returns the total number of entries
507 and entry size
508 """
509
510 r = self._scc.select_file(['3f00', '000c'])
511 rec_len = int(r[-1][28:30], 16)
512 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200513 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100514
515 if (rec_cnt < 1) or (rec_len != 0x5a):
516 raise RuntimeError('Bad card type')
517
518 return rec_cnt, rec_len
519
520 def program(self, p):
521 # Home PLMN
522 r = self._scc.select_file(['3f00', '7f20', '6f30'])
523 tl = int(r[-1][4:8], 16)
524
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400525 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100526 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
527
528 # Get total number of entries and entry size
529 rec_cnt, rec_len = self._get_infos()
530
531 # Set first entry
532 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200533 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100534 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200535 enc_iccid(p['iccid']) + # 10b ICCID
536 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
537 p['ki'] + # 16b Ki
538 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100539 )
540 self._scc.update_record('000c', 1, entry)
541
542 def erase(self):
543 # Get total number of entries and entry size
544 rec_cnt, rec_len = self._get_infos()
545
546 # Erase all entries
547 entry = 'ff' * rec_len
548 for i in range(0, rec_cnt):
549 self._scc.update_record('000c', 1+i, entry)
550
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200551
Harald Welte3156d902011-03-22 21:48:19 +0100552class GrcardSim(Card):
553 """
554 Greencard (grcard.cn) HZCOS GSM SIM
555 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
556 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
557 """
558
559 name = 'grcardsim'
560
561 @classmethod
562 def autodetect(kls, scc):
563 return None
564
565 def program(self, p):
566 # We don't really know yet what ADM PIN 4 is about
567 #self._scc.verify_chv(4, h2b("4444444444444444"))
568
569 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100570 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200571 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100572 else:
573 pin = h2b("4444444444444444")
574 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100575
576 # EF.ICCID
577 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400578 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100579
580 # EF.IMSI
581 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400582 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100583
584 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400585 if p.get('acc') is not None:
586 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100587
588 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200589 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200590 r = self._scc.select_file(['3f00', '7f10', '6f42'])
591 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100592
593 # Set the Ki using proprietary command
594 pdu = '80d4020010' + p['ki']
595 data, sw = self._scc._tp.send_apdu(pdu)
596
597 # EF.HPLMN
598 r = self._scc.select_file(['3f00', '7f20', '6f30'])
599 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400600 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100601 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
602
603 # EF.SPN (Service Provider Name)
604 r = self._scc.select_file(['3f00', '7f20', '6f30'])
605 size = int(r[-1][4:8], 16)
606 # FIXME
607
608 # FIXME: EF.MSISDN
609
Sylvain Munaut76504e02010-12-07 00:24:32 +0100610
Harald Weltee10394b2011-12-07 12:34:14 +0100611class SysmoSIMgr1(GrcardSim):
612 """
613 sysmocom sysmoSIM-GR1
614 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
615 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
616 """
617 name = 'sysmosim-gr1'
618
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200619 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200620 def autodetect(kls, scc):
621 try:
622 # Look for ATR
623 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
624 return kls(scc)
625 except:
626 return None
627 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200628
Harald Welteca673942020-06-03 15:19:40 +0200629class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100630 """
631 sysmocom sysmoUSIM-GR1
632 """
633 name = 'sysmoUSIM-GR1'
634
635 @classmethod
636 def autodetect(kls, scc):
637 # TODO: Access the ATR
638 return None
639
640 def program(self, p):
641 # TODO: check if verify_chv could be used or what it needs
642 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
643 # Unlock the card..
644 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
645
646 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100647 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400648 p['opc'] + # 32b OPC
649 enc_iccid(p['iccid']) + # 10b ICCID
650 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100651 )
652 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
653
Sylvain Munaut053c8952013-07-02 15:12:32 +0200654
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100655class SysmoSIMgr2(Card):
656 """
657 sysmocom sysmoSIM-GR2
658 """
659
660 name = 'sysmoSIM-GR2'
661
662 @classmethod
663 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900664 try:
665 # Look for ATR
666 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
667 return kls(scc)
668 except:
669 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100670 return None
671
672 def program(self, p):
673
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200674 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100675 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200676
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100677 # authenticate as SUPER ADM using default key
678 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
679
680 # set ADM pin using proprietary command
681 # INS: D4
682 # P1: 3A for PIN, 3B for PUK
683 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
684 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100685 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200686 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100687 else:
688 pin = h2b("4444444444444444")
689
690 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100691 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200692
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100693 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100694
695 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100696
697 # write EF.ICCID
698 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
699
700 # select DF_GSM
701 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200702
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100703 # write EF.IMSI
704 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
705
706 # write EF.ACC
707 if p.get('acc') is not None:
708 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
709
710 # get size and write EF.HPLMN
711 r = self._scc.select_file(['6f30'])
712 size = int(r[-1][4:8], 16)
713 hplmn = enc_plmn(p['mcc'], p['mnc'])
714 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
715
716 # set COMP128 version 0 in proprietary file
717 data, sw = self._scc.update_binary('0001', '001000')
718
719 # set Ki in proprietary file
720 data, sw = self._scc.update_binary('0001', p['ki'], 3)
721
722 # select DF_TELECOM
723 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200724
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100725 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200726 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200727 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100728
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100729
Harald Welteca673942020-06-03 15:19:40 +0200730class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100731 """
732 sysmocom sysmoUSIM-SJS1
733 """
734
735 name = 'sysmoUSIM-SJS1'
736
737 def __init__(self, ssc):
738 super(SysmoUSIMSJS1, self).__init__(ssc)
739 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100740 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100741
742 @classmethod
743 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900744 try:
745 # Look for ATR
746 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"):
747 return kls(scc)
748 except:
749 return None
Jan Balke3e840672015-01-26 15:36:27 +0100750 return None
751
752 def program(self, p):
753
Philipp Maiere9604882017-03-21 17:24:31 +0100754 # authenticate as ADM using default key (written on the card..)
755 if not p['pin_adm']:
756 raise ValueError("Please provide a PIN-ADM as there is no default one")
757 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100758
759 # select MF
760 r = self._scc.select_file(['3f00'])
761
Philipp Maiere9604882017-03-21 17:24:31 +0100762 # write EF.ICCID
763 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
764
Jan Balke3e840672015-01-26 15:36:27 +0100765 # select DF_GSM
766 r = self._scc.select_file(['7f20'])
767
Jan Balke3e840672015-01-26 15:36:27 +0100768 # set Ki in proprietary file
769 data, sw = self._scc.update_binary('00FF', p['ki'])
770
Philipp Maier1be35bf2018-07-13 11:29:03 +0200771 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200772 if 'opc' in p:
773 content = "01" + p['opc']
774 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100775
Supreeth Herle7947d922019-06-08 07:50:53 +0200776 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100777 if p.get('name') is not None:
778 content = enc_spn(p['name'], True, True)
779 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200780
Supreeth Herlec8796a32019-12-23 12:23:42 +0100781 if p.get('acc') is not None:
782 self.update_acc(p['acc'])
783
Jan Balke3e840672015-01-26 15:36:27 +0100784 # write EF.IMSI
785 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
786
Philipp Maier2d15ea02019-03-20 12:40:36 +0100787 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200788 if p.get('mcc') and p.get('mnc'):
789 sw = self.update_plmnsel(p['mcc'], p['mnc'])
790 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100791 print("Programming PLMNsel failed with code %s"%sw)
792
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200793 # EF.PLMNwAcT
794 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100795 sw = self.update_plmn_act(p['mcc'], p['mnc'])
796 if sw != '9000':
797 print("Programming PLMNwAcT failed with code %s"%sw)
798
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200799 # EF.OPLMNwAcT
800 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100801 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
802 if sw != '9000':
803 print("Programming OPLMNwAcT failed with code %s"%sw)
804
Supreeth Herlef442fb42020-01-21 12:47:32 +0100805 # EF.HPLMNwAcT
806 if p.get('mcc') and p.get('mnc'):
807 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
808 if sw != '9000':
809 print("Programming HPLMNwAcT failed with code %s"%sw)
810
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200811 # EF.AD
812 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100813 sw = self.update_ad(p['mnc'])
814 if sw != '9000':
815 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100816
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200817 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200818 if p.get('smsp'):
819 r = self._scc.select_file(['3f00', '7f10'])
820 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100821
Supreeth Herle5a541012019-12-22 08:59:16 +0100822 # EF.MSISDN
823 # TODO: Alpha Identifier (currently 'ff'O * 20)
824 # TODO: Capability/Configuration1 Record Identifier
825 # TODO: Extension1 Record Identifier
826 if p.get('msisdn') is not None:
827 msisdn = enc_msisdn(p['msisdn'])
828 data = 'ff' * 20 + msisdn + 'ff' * 2
829
830 r = self._scc.select_file(['3f00', '7f10'])
831 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
832
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900833
herlesupreeth4a3580b2020-09-29 10:11:36 +0200834class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900835 """
836 FairwavesSIM
837
838 The SIM card is operating according to the standard.
839 For Ki/OP/OPC programming the following files are additionally open for writing:
840 3F00/7F20/FF01 – OP/OPC:
841 byte 1 = 0x01, bytes 2-17: OPC;
842 byte 1 = 0x00, bytes 2-17: OP;
843 3F00/7F20/FF02: Ki
844 """
845
Philipp Maier5a876312019-11-11 11:01:46 +0100846 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900847 # Propriatary files
848 _EF_num = {
849 'Ki': 'FF02',
850 'OP/OPC': 'FF01',
851 }
852 _EF = {
853 'Ki': DF['GSM']+[_EF_num['Ki']],
854 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
855 }
856
857 def __init__(self, ssc):
858 super(FairwavesSIM, self).__init__(ssc)
859 self._adm_chv_num = 0x11
860 self._adm2_chv_num = 0x12
861
862
863 @classmethod
864 def autodetect(kls, scc):
865 try:
866 # Look for ATR
867 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"):
868 return kls(scc)
869 except:
870 return None
871 return None
872
873
874 def verify_adm2(self, key):
875 '''
876 Authenticate with ADM2 key.
877
878 Fairwaves SIM cards support hierarchical key structure and ADM2 key
879 is a key which has access to proprietary files (Ki and OP/OPC).
880 That said, ADM key inherits permissions of ADM2 key and thus we rarely
881 need ADM2 key per se.
882 '''
883 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
884 return sw
885
886
887 def read_ki(self):
888 """
889 Read Ki in proprietary file.
890
891 Requires ADM1 access level
892 """
893 return self._scc.read_binary(self._EF['Ki'])
894
895
896 def update_ki(self, ki):
897 """
898 Set Ki in proprietary file.
899
900 Requires ADM1 access level
901 """
902 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
903 return sw
904
905
906 def read_op_opc(self):
907 """
908 Read Ki in proprietary file.
909
910 Requires ADM1 access level
911 """
912 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
913 type = 'OP' if ef[0:2] == '00' else 'OPC'
914 return ((type, ef[2:]), sw)
915
916
917 def update_op(self, op):
918 """
919 Set OP in proprietary file.
920
921 Requires ADM1 access level
922 """
923 content = '00' + op
924 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
925 return sw
926
927
928 def update_opc(self, opc):
929 """
930 Set OPC in proprietary file.
931
932 Requires ADM1 access level
933 """
934 content = '01' + opc
935 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
936 return sw
937
938
939 def program(self, p):
940 # authenticate as ADM1
941 if not p['pin_adm']:
942 raise ValueError("Please provide a PIN-ADM as there is no default one")
943 sw = self.verify_adm(h2b(p['pin_adm']))
944 if sw != '9000':
945 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
946
947 # TODO: Set operator name
948 if p.get('smsp') is not None:
949 sw = self.update_smsp(p['smsp'])
950 if sw != '9000':
951 print("Programming SMSP failed with code %s"%sw)
952 # This SIM doesn't support changing ICCID
953 if p.get('mcc') is not None and p.get('mnc') is not None:
954 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
955 if sw != '9000':
956 print("Programming MCC/MNC failed with code %s"%sw)
957 if p.get('imsi') is not None:
958 sw = self.update_imsi(p['imsi'])
959 if sw != '9000':
960 print("Programming IMSI failed with code %s"%sw)
961 if p.get('ki') is not None:
962 sw = self.update_ki(p['ki'])
963 if sw != '9000':
964 print("Programming Ki failed with code %s"%sw)
965 if p.get('opc') is not None:
966 sw = self.update_opc(p['opc'])
967 if sw != '9000':
968 print("Programming OPC failed with code %s"%sw)
969 if p.get('acc') is not None:
970 sw = self.update_acc(p['acc'])
971 if sw != '9000':
972 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100973
Todd Neal9eeadfc2018-04-25 15:36:29 -0500974class OpenCellsSim(Card):
975 """
976 OpenCellsSim
977
978 """
979
Philipp Maier5a876312019-11-11 11:01:46 +0100980 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500981
982 def __init__(self, ssc):
983 super(OpenCellsSim, self).__init__(ssc)
984 self._adm_chv_num = 0x0A
985
986
987 @classmethod
988 def autodetect(kls, scc):
989 try:
990 # Look for ATR
991 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"):
992 return kls(scc)
993 except:
994 return None
995 return None
996
997
998 def program(self, p):
999 if not p['pin_adm']:
1000 raise ValueError("Please provide a PIN-ADM as there is no default one")
1001 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1002
1003 # select MF
1004 r = self._scc.select_file(['3f00'])
1005
1006 # write EF.ICCID
1007 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1008
1009 r = self._scc.select_file(['7ff0'])
1010
1011 # set Ki in proprietary file
1012 data, sw = self._scc.update_binary('FF02', p['ki'])
1013
1014 # set OPC in proprietary file
1015 data, sw = self._scc.update_binary('FF01', p['opc'])
1016
1017 # select DF_GSM
1018 r = self._scc.select_file(['7f20'])
1019
1020 # write EF.IMSI
1021 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1022
herlesupreeth4a3580b2020-09-29 10:11:36 +02001023class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001024 """
1025 WavemobileSim
1026
1027 """
1028
1029 name = 'Wavemobile-SIM'
1030
1031 def __init__(self, ssc):
1032 super(WavemobileSim, self).__init__(ssc)
1033 self._adm_chv_num = 0x0A
1034 self._scc.cla_byte = "00"
1035 self._scc.sel_ctrl = "0004" #request an FCP
1036
1037 @classmethod
1038 def autodetect(kls, scc):
1039 try:
1040 # Look for ATR
1041 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"):
1042 return kls(scc)
1043 except:
1044 return None
1045 return None
1046
1047 def program(self, p):
1048 if not p['pin_adm']:
1049 raise ValueError("Please provide a PIN-ADM as there is no default one")
1050 sw = self.verify_adm(h2b(p['pin_adm']))
1051 if sw != '9000':
1052 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1053
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001054 # EF.ICCID
1055 # TODO: Add programming of the ICCID
1056 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001057 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1058
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001059 # KI (Presumably a propritary file)
1060 # TODO: Add programming of KI
1061 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001062 print("Warning: Programming of the KI is not implemented for this type of card.")
1063
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001064 # OPc (Presumably a propritary file)
1065 # TODO: Add programming of OPc
1066 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001067 print("Warning: Programming of the OPc is not implemented for this type of card.")
1068
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001069 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001070 if p.get('smsp'):
1071 sw = self.update_smsp(p['smsp'])
1072 if sw != '9000':
1073 print("Programming SMSP failed with code %s"%sw)
1074
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001075 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001076 if p.get('imsi'):
1077 sw = self.update_imsi(p['imsi'])
1078 if sw != '9000':
1079 print("Programming IMSI failed with code %s"%sw)
1080
1081 # EF.ACC
1082 if p.get('acc'):
1083 sw = self.update_acc(p['acc'])
1084 if sw != '9000':
1085 print("Programming ACC failed with code %s"%sw)
1086
1087 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001088 if p.get('mcc') and p.get('mnc'):
1089 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1090 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001091 print("Programming PLMNsel failed with code %s"%sw)
1092
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001093 # EF.PLMNwAcT
1094 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001095 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1096 if sw != '9000':
1097 print("Programming PLMNwAcT failed with code %s"%sw)
1098
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001099 # EF.OPLMNwAcT
1100 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001101 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1102 if sw != '9000':
1103 print("Programming OPLMNwAcT failed with code %s"%sw)
1104
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001105 # EF.AD
1106 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001107 sw = self.update_ad(p['mnc'])
1108 if sw != '9000':
1109 print("Programming AD failed with code %s"%sw)
1110
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001111 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001112
Todd Neal9eeadfc2018-04-25 15:36:29 -05001113
herlesupreethb0c7d122020-12-23 09:25:46 +01001114class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001115 """
1116 sysmocom sysmoISIM-SJA2
1117 """
1118
1119 name = 'sysmoISIM-SJA2'
1120
1121 def __init__(self, ssc):
1122 super(SysmoISIMSJA2, self).__init__(ssc)
1123 self._scc.cla_byte = "00"
1124 self._scc.sel_ctrl = "0004" #request an FCP
1125
1126 @classmethod
1127 def autodetect(kls, scc):
1128 try:
1129 # Try card model #1
1130 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1131 if scc.get_atr() == toBytes(atr):
1132 return kls(scc)
1133
1134 # Try card model #2
1135 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1136 if scc.get_atr() == toBytes(atr):
1137 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001138
1139 # Try card model #3
1140 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1141 if scc.get_atr() == toBytes(atr):
1142 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001143 except:
1144 return None
1145 return None
1146
1147 def program(self, p):
1148 # authenticate as ADM using default key (written on the card..)
1149 if not p['pin_adm']:
1150 raise ValueError("Please provide a PIN-ADM as there is no default one")
1151 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1152
1153 # This type of card does not allow to reprogram the ICCID.
1154 # Reprogramming the ICCID would mess up the card os software
1155 # license management, so the ICCID must be kept at its factory
1156 # setting!
1157 if p.get('iccid'):
1158 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1159
1160 # select DF_GSM
1161 self._scc.select_file(['7f20'])
1162
1163 # write EF.IMSI
1164 if p.get('imsi'):
1165 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1166
1167 # EF.PLMNsel
1168 if p.get('mcc') and p.get('mnc'):
1169 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1170 if sw != '9000':
1171 print("Programming PLMNsel failed with code %s"%sw)
1172
1173 # EF.PLMNwAcT
1174 if p.get('mcc') and p.get('mnc'):
1175 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1176 if sw != '9000':
1177 print("Programming PLMNwAcT failed with code %s"%sw)
1178
1179 # EF.OPLMNwAcT
1180 if p.get('mcc') and p.get('mnc'):
1181 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1182 if sw != '9000':
1183 print("Programming OPLMNwAcT failed with code %s"%sw)
1184
Harald Welte32f0d412020-05-05 17:35:57 +02001185 # EF.HPLMNwAcT
1186 if p.get('mcc') and p.get('mnc'):
1187 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1188 if sw != '9000':
1189 print("Programming HPLMNwAcT failed with code %s"%sw)
1190
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001191 # EF.AD
1192 if p.get('mcc') and p.get('mnc'):
1193 sw = self.update_ad(p['mnc'])
1194 if sw != '9000':
1195 print("Programming AD failed with code %s"%sw)
1196
1197 # EF.SMSP
1198 if p.get('smsp'):
1199 r = self._scc.select_file(['3f00', '7f10'])
1200 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1201
Supreeth Herle80164052020-03-23 12:06:29 +01001202 # Populate AIDs
1203 self.read_aids()
1204
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001205 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1206 # hard linked to EF-USIM_AUTH_KEY)
1207 self._scc.select_file(['3f00'])
1208 self._scc.select_file(['a515'])
1209 if p.get('ki'):
1210 self._scc.update_binary('6f20', p['ki'], 1)
1211 if p.get('opc'):
1212 self._scc.update_binary('6f20', p['opc'], 17)
1213
1214 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001215 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001216 if p.get('ki'):
1217 self._scc.update_binary('af20', p['ki'], 1)
1218 if p.get('opc'):
1219 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001220
Supreeth Herlecf727f22020-03-24 17:32:21 +01001221 # update EF.P-CSCF in ADF.ISIM
1222 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1223 if p.get('pcscf'):
1224 sw = self.update_pcscf(p['pcscf'])
1225 else:
1226 sw = self.update_pcscf("")
1227 if sw != '9000':
1228 print("Programming P-CSCF failed with code %s"%sw)
1229
1230
herlesupreeth1a13c442020-09-11 21:16:51 +02001231 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001232 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001233 if p.get('ki'):
1234 self._scc.update_binary('af20', p['ki'], 1)
1235 if p.get('opc'):
1236 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001237
Harald Welteca673942020-06-03 15:19:40 +02001238 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001239 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001240 if p.get('mcc') and p.get('mnc'):
1241 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1242 if sw != '9000':
1243 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001244
1245 # update EF.ePDGId in ADF.USIM
1246 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1247 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001248 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001249 if sw != '9000':
1250 print("Programming ePDGId failed with code %s"%sw)
1251
Supreeth Herlef964df42020-03-24 13:15:37 +01001252 # update EF.ePDGSelection in ADF.USIM
1253 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1254 if p.get('epdgSelection'):
1255 epdg_plmn = p['epdgSelection']
1256 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1257 else:
1258 sw = self.update_ePDGSelection("", "")
1259 if sw != '9000':
1260 print("Programming ePDGSelection failed with code %s"%sw)
1261
1262
Supreeth Herleacc222f2020-03-24 13:26:53 +01001263 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1264 # Set service 106 and 107 as available in EF.UST
1265 if self.file_exists(EF_USIM_ADF_map['UST']):
1266 if p.get('epdgSelection') and p.get('epdgid'):
1267 sw = self.update_ust(106, 1)
1268 if sw != '9000':
1269 print("Programming UST failed with code %s"%sw)
1270 sw = self.update_ust(107, 1)
1271 if sw != '9000':
1272 print("Programming UST failed with code %s"%sw)
1273
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001274 return
1275
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001276
Todd Neal9eeadfc2018-04-25 15:36:29 -05001277# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001278_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001279 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001280 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001281
1282def card_autodetect(scc):
1283 for kls in _cards_classes:
1284 card = kls.autodetect(scc)
1285 if card is not None:
1286 card.reset()
1287 return card
1288 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001289
1290def card_detect(ctype, scc):
1291 # Detect type if needed
1292 card = None
1293 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1294
1295 if ctype in ("auto", "auto_once"):
1296 for kls in _cards_classes:
1297 card = kls.autodetect(scc)
1298 if card:
1299 print("Autodetected card type: %s" % card.name)
1300 card.reset()
1301 break
1302
1303 if card is None:
1304 print("Autodetection failed")
1305 return None
1306
1307 if ctype == "auto_once":
1308 ctype = card.name
1309
1310 elif ctype in ctypes:
1311 card = ctypes[ctype](scc)
1312
1313 else:
1314 raise ValueError("Unknown card type: %s" % ctype)
1315
1316 return card