blob: 277b831795d3a45522e959e95f1969cc9f766e8e [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
Supreeth Herle05b28072020-03-25 10:23:48 +0100339 def read_domain(self):
340 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
341 if sw == '9000':
342 # Skip the inital tag value ('80') byte and get length of contents
343 length = int(res[2:4], 16)
344 content = h2s(res[4:4+(length*2)])
345 return (content, sw)
346 else:
347 return (None, sw)
348
Sylvain Munaut76504e02010-12-07 00:24:32 +0100349
350class _MagicSimBase(Card):
351 """
352 Theses cards uses several record based EFs to store the provider infos,
353 each possible provider uses a specific record number in each EF. The
354 indexes used are ( where N is the number of providers supported ) :
355 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100356 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100357
358 * 3f00/7f4d/8f0c : Operator Name
359
360 bytes 0-15 : provider name, padded with 0xff
361 byte 16 : length of the provider name
362 byte 17 : 01 for valid records, 00 otherwise
363
364 * 3f00/7f4d/8f0d : Programmable Binary EFs
365
366 * 3f00/7f4d/8f0e : Programmable Record EFs
367
368 """
369
370 @classmethod
371 def autodetect(kls, scc):
372 try:
373 for p, l, t in kls._files.values():
374 if not t:
375 continue
376 if scc.record_size(['3f00', '7f4d', p]) != l:
377 return None
378 except:
379 return None
380
381 return kls(scc)
382
383 def _get_count(self):
384 """
385 Selects the file and returns the total number of entries
386 and entry size
387 """
388 f = self._files['name']
389
390 r = self._scc.select_file(['3f00', '7f4d', f[0]])
391 rec_len = int(r[-1][28:30], 16)
392 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200393 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100394
395 if (rec_cnt < 1) or (rec_len != f[1]):
396 raise RuntimeError('Bad card type')
397
398 return rec_cnt
399
400 def program(self, p):
401 # Go to dir
402 self._scc.select_file(['3f00', '7f4d'])
403
404 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400405 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100406
407 # Operator name ( 3f00/7f4d/8f0c )
408 self._scc.update_record(self._files['name'][0], 2,
409 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
410 )
411
412 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
413 v = ''
414
415 # inline Ki
416 if self._ki_file is None:
417 v += p['ki']
418
419 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400420 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100421
422 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400423 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424
425 # Ki
426 if self._ki_file:
427 v += self._ki_file + '10' + p['ki']
428
429 # PLMN_Sel
430 v+= '6f30' + '18' + rpad(hplmn, 36)
431
Alexander Chemeris21885242013-07-02 16:56:55 +0400432 # ACC
433 # This doesn't work with "fake" SuperSIM cards,
434 # but will hopefully work with real SuperSIMs.
435 if p.get('acc') is not None:
436 v+= '6f78' + '02' + lpad(p['acc'], 4)
437
Sylvain Munaut76504e02010-12-07 00:24:32 +0100438 self._scc.update_record(self._files['b_ef'][0], 1,
439 rpad(v, self._files['b_ef'][1]*2)
440 )
441
442 # SMSP ( 3f00/7f4d/8f0e )
443 # FIXME
444
445 # Write PLMN_Sel forcefully as well
446 r = self._scc.select_file(['3f00', '7f20', '6f30'])
447 tl = int(r[-1][4:8], 16)
448
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400449 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100450 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
451
452 def erase(self):
453 # Dummy
454 df = {}
455 for k, v in self._files.iteritems():
456 ofs = 1
457 fv = v[1] * 'ff'
458 if k == 'name':
459 ofs = 2
460 fv = fv[0:-4] + '0000'
461 df[v[0]] = (fv, ofs)
462
463 # Write
464 for n in range(0,self._get_count()):
465 for k, (msg, ofs) in df.iteritems():
466 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
467
468
469class SuperSim(_MagicSimBase):
470
471 name = 'supersim'
472
473 _files = {
474 'name' : ('8f0c', 18, True),
475 'b_ef' : ('8f0d', 74, True),
476 'r_ef' : ('8f0e', 50, True),
477 }
478
479 _ki_file = None
480
481
482class MagicSim(_MagicSimBase):
483
484 name = 'magicsim'
485
486 _files = {
487 'name' : ('8f0c', 18, True),
488 'b_ef' : ('8f0d', 130, True),
489 'r_ef' : ('8f0e', 102, False),
490 }
491
492 _ki_file = '6f1b'
493
494
495class FakeMagicSim(Card):
496 """
497 Theses cards have a record based EF 3f00/000c that contains the provider
498 informations. See the program method for its format. The records go from
499 1 to N.
500 """
501
502 name = 'fakemagicsim'
503
504 @classmethod
505 def autodetect(kls, scc):
506 try:
507 if scc.record_size(['3f00', '000c']) != 0x5a:
508 return None
509 except:
510 return None
511
512 return kls(scc)
513
514 def _get_infos(self):
515 """
516 Selects the file and returns the total number of entries
517 and entry size
518 """
519
520 r = self._scc.select_file(['3f00', '000c'])
521 rec_len = int(r[-1][28:30], 16)
522 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200523 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100524
525 if (rec_cnt < 1) or (rec_len != 0x5a):
526 raise RuntimeError('Bad card type')
527
528 return rec_cnt, rec_len
529
530 def program(self, p):
531 # Home PLMN
532 r = self._scc.select_file(['3f00', '7f20', '6f30'])
533 tl = int(r[-1][4:8], 16)
534
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400535 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100536 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
537
538 # Get total number of entries and entry size
539 rec_cnt, rec_len = self._get_infos()
540
541 # Set first entry
542 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200543 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100544 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200545 enc_iccid(p['iccid']) + # 10b ICCID
546 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
547 p['ki'] + # 16b Ki
548 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100549 )
550 self._scc.update_record('000c', 1, entry)
551
552 def erase(self):
553 # Get total number of entries and entry size
554 rec_cnt, rec_len = self._get_infos()
555
556 # Erase all entries
557 entry = 'ff' * rec_len
558 for i in range(0, rec_cnt):
559 self._scc.update_record('000c', 1+i, entry)
560
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200561
Harald Welte3156d902011-03-22 21:48:19 +0100562class GrcardSim(Card):
563 """
564 Greencard (grcard.cn) HZCOS GSM SIM
565 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
566 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
567 """
568
569 name = 'grcardsim'
570
571 @classmethod
572 def autodetect(kls, scc):
573 return None
574
575 def program(self, p):
576 # We don't really know yet what ADM PIN 4 is about
577 #self._scc.verify_chv(4, h2b("4444444444444444"))
578
579 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100580 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200581 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100582 else:
583 pin = h2b("4444444444444444")
584 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100585
586 # EF.ICCID
587 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400588 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100589
590 # EF.IMSI
591 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400592 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100593
594 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400595 if p.get('acc') is not None:
596 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100597
598 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200599 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200600 r = self._scc.select_file(['3f00', '7f10', '6f42'])
601 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100602
603 # Set the Ki using proprietary command
604 pdu = '80d4020010' + p['ki']
605 data, sw = self._scc._tp.send_apdu(pdu)
606
607 # EF.HPLMN
608 r = self._scc.select_file(['3f00', '7f20', '6f30'])
609 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400610 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100611 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
612
613 # EF.SPN (Service Provider Name)
614 r = self._scc.select_file(['3f00', '7f20', '6f30'])
615 size = int(r[-1][4:8], 16)
616 # FIXME
617
618 # FIXME: EF.MSISDN
619
Sylvain Munaut76504e02010-12-07 00:24:32 +0100620
Harald Weltee10394b2011-12-07 12:34:14 +0100621class SysmoSIMgr1(GrcardSim):
622 """
623 sysmocom sysmoSIM-GR1
624 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
625 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
626 """
627 name = 'sysmosim-gr1'
628
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200629 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200630 def autodetect(kls, scc):
631 try:
632 # Look for ATR
633 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
634 return kls(scc)
635 except:
636 return None
637 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200638
Harald Welteca673942020-06-03 15:19:40 +0200639class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100640 """
641 sysmocom sysmoUSIM-GR1
642 """
643 name = 'sysmoUSIM-GR1'
644
645 @classmethod
646 def autodetect(kls, scc):
647 # TODO: Access the ATR
648 return None
649
650 def program(self, p):
651 # TODO: check if verify_chv could be used or what it needs
652 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
653 # Unlock the card..
654 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
655
656 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100657 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400658 p['opc'] + # 32b OPC
659 enc_iccid(p['iccid']) + # 10b ICCID
660 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100661 )
662 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
663
Sylvain Munaut053c8952013-07-02 15:12:32 +0200664
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100665class SysmoSIMgr2(Card):
666 """
667 sysmocom sysmoSIM-GR2
668 """
669
670 name = 'sysmoSIM-GR2'
671
672 @classmethod
673 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900674 try:
675 # Look for ATR
676 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
677 return kls(scc)
678 except:
679 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100680 return None
681
682 def program(self, p):
683
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200684 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100685 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200686
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100687 # authenticate as SUPER ADM using default key
688 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
689
690 # set ADM pin using proprietary command
691 # INS: D4
692 # P1: 3A for PIN, 3B for PUK
693 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
694 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100695 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200696 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100697 else:
698 pin = h2b("4444444444444444")
699
700 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100701 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200702
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100703 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100704
705 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100706
707 # write EF.ICCID
708 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
709
710 # select DF_GSM
711 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200712
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100713 # write EF.IMSI
714 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
715
716 # write EF.ACC
717 if p.get('acc') is not None:
718 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
719
720 # get size and write EF.HPLMN
721 r = self._scc.select_file(['6f30'])
722 size = int(r[-1][4:8], 16)
723 hplmn = enc_plmn(p['mcc'], p['mnc'])
724 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
725
726 # set COMP128 version 0 in proprietary file
727 data, sw = self._scc.update_binary('0001', '001000')
728
729 # set Ki in proprietary file
730 data, sw = self._scc.update_binary('0001', p['ki'], 3)
731
732 # select DF_TELECOM
733 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200734
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100735 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200736 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200737 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100738
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100739
Harald Welteca673942020-06-03 15:19:40 +0200740class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100741 """
742 sysmocom sysmoUSIM-SJS1
743 """
744
745 name = 'sysmoUSIM-SJS1'
746
747 def __init__(self, ssc):
748 super(SysmoUSIMSJS1, self).__init__(ssc)
749 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100750 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100751
752 @classmethod
753 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900754 try:
755 # Look for ATR
756 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"):
757 return kls(scc)
758 except:
759 return None
Jan Balke3e840672015-01-26 15:36:27 +0100760 return None
761
762 def program(self, p):
763
Philipp Maiere9604882017-03-21 17:24:31 +0100764 # authenticate as ADM using default key (written on the card..)
765 if not p['pin_adm']:
766 raise ValueError("Please provide a PIN-ADM as there is no default one")
767 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100768
769 # select MF
770 r = self._scc.select_file(['3f00'])
771
Philipp Maiere9604882017-03-21 17:24:31 +0100772 # write EF.ICCID
773 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
774
Jan Balke3e840672015-01-26 15:36:27 +0100775 # select DF_GSM
776 r = self._scc.select_file(['7f20'])
777
Jan Balke3e840672015-01-26 15:36:27 +0100778 # set Ki in proprietary file
779 data, sw = self._scc.update_binary('00FF', p['ki'])
780
Philipp Maier1be35bf2018-07-13 11:29:03 +0200781 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200782 if 'opc' in p:
783 content = "01" + p['opc']
784 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100785
Supreeth Herle7947d922019-06-08 07:50:53 +0200786 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100787 if p.get('name') is not None:
788 content = enc_spn(p['name'], True, True)
789 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200790
Supreeth Herlec8796a32019-12-23 12:23:42 +0100791 if p.get('acc') is not None:
792 self.update_acc(p['acc'])
793
Jan Balke3e840672015-01-26 15:36:27 +0100794 # write EF.IMSI
795 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
796
Philipp Maier2d15ea02019-03-20 12:40:36 +0100797 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200798 if p.get('mcc') and p.get('mnc'):
799 sw = self.update_plmnsel(p['mcc'], p['mnc'])
800 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100801 print("Programming PLMNsel failed with code %s"%sw)
802
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200803 # EF.PLMNwAcT
804 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100805 sw = self.update_plmn_act(p['mcc'], p['mnc'])
806 if sw != '9000':
807 print("Programming PLMNwAcT failed with code %s"%sw)
808
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200809 # EF.OPLMNwAcT
810 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100811 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
812 if sw != '9000':
813 print("Programming OPLMNwAcT failed with code %s"%sw)
814
Supreeth Herlef442fb42020-01-21 12:47:32 +0100815 # EF.HPLMNwAcT
816 if p.get('mcc') and p.get('mnc'):
817 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
818 if sw != '9000':
819 print("Programming HPLMNwAcT failed with code %s"%sw)
820
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200821 # EF.AD
822 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100823 sw = self.update_ad(p['mnc'])
824 if sw != '9000':
825 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100826
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200827 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200828 if p.get('smsp'):
829 r = self._scc.select_file(['3f00', '7f10'])
830 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100831
Supreeth Herle5a541012019-12-22 08:59:16 +0100832 # EF.MSISDN
833 # TODO: Alpha Identifier (currently 'ff'O * 20)
834 # TODO: Capability/Configuration1 Record Identifier
835 # TODO: Extension1 Record Identifier
836 if p.get('msisdn') is not None:
837 msisdn = enc_msisdn(p['msisdn'])
838 data = 'ff' * 20 + msisdn + 'ff' * 2
839
840 r = self._scc.select_file(['3f00', '7f10'])
841 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
842
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900843
herlesupreeth4a3580b2020-09-29 10:11:36 +0200844class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900845 """
846 FairwavesSIM
847
848 The SIM card is operating according to the standard.
849 For Ki/OP/OPC programming the following files are additionally open for writing:
850 3F00/7F20/FF01 – OP/OPC:
851 byte 1 = 0x01, bytes 2-17: OPC;
852 byte 1 = 0x00, bytes 2-17: OP;
853 3F00/7F20/FF02: Ki
854 """
855
Philipp Maier5a876312019-11-11 11:01:46 +0100856 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900857 # Propriatary files
858 _EF_num = {
859 'Ki': 'FF02',
860 'OP/OPC': 'FF01',
861 }
862 _EF = {
863 'Ki': DF['GSM']+[_EF_num['Ki']],
864 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
865 }
866
867 def __init__(self, ssc):
868 super(FairwavesSIM, self).__init__(ssc)
869 self._adm_chv_num = 0x11
870 self._adm2_chv_num = 0x12
871
872
873 @classmethod
874 def autodetect(kls, scc):
875 try:
876 # Look for ATR
877 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"):
878 return kls(scc)
879 except:
880 return None
881 return None
882
883
884 def verify_adm2(self, key):
885 '''
886 Authenticate with ADM2 key.
887
888 Fairwaves SIM cards support hierarchical key structure and ADM2 key
889 is a key which has access to proprietary files (Ki and OP/OPC).
890 That said, ADM key inherits permissions of ADM2 key and thus we rarely
891 need ADM2 key per se.
892 '''
893 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
894 return sw
895
896
897 def read_ki(self):
898 """
899 Read Ki in proprietary file.
900
901 Requires ADM1 access level
902 """
903 return self._scc.read_binary(self._EF['Ki'])
904
905
906 def update_ki(self, ki):
907 """
908 Set Ki in proprietary file.
909
910 Requires ADM1 access level
911 """
912 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
913 return sw
914
915
916 def read_op_opc(self):
917 """
918 Read Ki in proprietary file.
919
920 Requires ADM1 access level
921 """
922 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
923 type = 'OP' if ef[0:2] == '00' else 'OPC'
924 return ((type, ef[2:]), sw)
925
926
927 def update_op(self, op):
928 """
929 Set OP in proprietary file.
930
931 Requires ADM1 access level
932 """
933 content = '00' + op
934 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
935 return sw
936
937
938 def update_opc(self, opc):
939 """
940 Set OPC in proprietary file.
941
942 Requires ADM1 access level
943 """
944 content = '01' + opc
945 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
946 return sw
947
948
949 def program(self, p):
950 # authenticate as ADM1
951 if not p['pin_adm']:
952 raise ValueError("Please provide a PIN-ADM as there is no default one")
953 sw = self.verify_adm(h2b(p['pin_adm']))
954 if sw != '9000':
955 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
956
957 # TODO: Set operator name
958 if p.get('smsp') is not None:
959 sw = self.update_smsp(p['smsp'])
960 if sw != '9000':
961 print("Programming SMSP failed with code %s"%sw)
962 # This SIM doesn't support changing ICCID
963 if p.get('mcc') is not None and p.get('mnc') is not None:
964 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
965 if sw != '9000':
966 print("Programming MCC/MNC failed with code %s"%sw)
967 if p.get('imsi') is not None:
968 sw = self.update_imsi(p['imsi'])
969 if sw != '9000':
970 print("Programming IMSI failed with code %s"%sw)
971 if p.get('ki') is not None:
972 sw = self.update_ki(p['ki'])
973 if sw != '9000':
974 print("Programming Ki failed with code %s"%sw)
975 if p.get('opc') is not None:
976 sw = self.update_opc(p['opc'])
977 if sw != '9000':
978 print("Programming OPC failed with code %s"%sw)
979 if p.get('acc') is not None:
980 sw = self.update_acc(p['acc'])
981 if sw != '9000':
982 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +0100983
Todd Neal9eeadfc2018-04-25 15:36:29 -0500984class OpenCellsSim(Card):
985 """
986 OpenCellsSim
987
988 """
989
Philipp Maier5a876312019-11-11 11:01:46 +0100990 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -0500991
992 def __init__(self, ssc):
993 super(OpenCellsSim, self).__init__(ssc)
994 self._adm_chv_num = 0x0A
995
996
997 @classmethod
998 def autodetect(kls, scc):
999 try:
1000 # Look for ATR
1001 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"):
1002 return kls(scc)
1003 except:
1004 return None
1005 return None
1006
1007
1008 def program(self, p):
1009 if not p['pin_adm']:
1010 raise ValueError("Please provide a PIN-ADM as there is no default one")
1011 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1012
1013 # select MF
1014 r = self._scc.select_file(['3f00'])
1015
1016 # write EF.ICCID
1017 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1018
1019 r = self._scc.select_file(['7ff0'])
1020
1021 # set Ki in proprietary file
1022 data, sw = self._scc.update_binary('FF02', p['ki'])
1023
1024 # set OPC in proprietary file
1025 data, sw = self._scc.update_binary('FF01', p['opc'])
1026
1027 # select DF_GSM
1028 r = self._scc.select_file(['7f20'])
1029
1030 # write EF.IMSI
1031 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1032
herlesupreeth4a3580b2020-09-29 10:11:36 +02001033class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001034 """
1035 WavemobileSim
1036
1037 """
1038
1039 name = 'Wavemobile-SIM'
1040
1041 def __init__(self, ssc):
1042 super(WavemobileSim, self).__init__(ssc)
1043 self._adm_chv_num = 0x0A
1044 self._scc.cla_byte = "00"
1045 self._scc.sel_ctrl = "0004" #request an FCP
1046
1047 @classmethod
1048 def autodetect(kls, scc):
1049 try:
1050 # Look for ATR
1051 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"):
1052 return kls(scc)
1053 except:
1054 return None
1055 return None
1056
1057 def program(self, p):
1058 if not p['pin_adm']:
1059 raise ValueError("Please provide a PIN-ADM as there is no default one")
1060 sw = self.verify_adm(h2b(p['pin_adm']))
1061 if sw != '9000':
1062 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1063
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001064 # EF.ICCID
1065 # TODO: Add programming of the ICCID
1066 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001067 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1068
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001069 # KI (Presumably a propritary file)
1070 # TODO: Add programming of KI
1071 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001072 print("Warning: Programming of the KI is not implemented for this type of card.")
1073
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001074 # OPc (Presumably a propritary file)
1075 # TODO: Add programming of OPc
1076 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001077 print("Warning: Programming of the OPc is not implemented for this type of card.")
1078
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001079 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001080 if p.get('smsp'):
1081 sw = self.update_smsp(p['smsp'])
1082 if sw != '9000':
1083 print("Programming SMSP failed with code %s"%sw)
1084
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001085 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001086 if p.get('imsi'):
1087 sw = self.update_imsi(p['imsi'])
1088 if sw != '9000':
1089 print("Programming IMSI failed with code %s"%sw)
1090
1091 # EF.ACC
1092 if p.get('acc'):
1093 sw = self.update_acc(p['acc'])
1094 if sw != '9000':
1095 print("Programming ACC failed with code %s"%sw)
1096
1097 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001098 if p.get('mcc') and p.get('mnc'):
1099 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1100 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001101 print("Programming PLMNsel failed with code %s"%sw)
1102
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001103 # EF.PLMNwAcT
1104 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001105 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1106 if sw != '9000':
1107 print("Programming PLMNwAcT failed with code %s"%sw)
1108
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001109 # EF.OPLMNwAcT
1110 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001111 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1112 if sw != '9000':
1113 print("Programming OPLMNwAcT failed with code %s"%sw)
1114
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001115 # EF.AD
1116 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001117 sw = self.update_ad(p['mnc'])
1118 if sw != '9000':
1119 print("Programming AD failed with code %s"%sw)
1120
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001121 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001122
Todd Neal9eeadfc2018-04-25 15:36:29 -05001123
herlesupreethb0c7d122020-12-23 09:25:46 +01001124class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001125 """
1126 sysmocom sysmoISIM-SJA2
1127 """
1128
1129 name = 'sysmoISIM-SJA2'
1130
1131 def __init__(self, ssc):
1132 super(SysmoISIMSJA2, self).__init__(ssc)
1133 self._scc.cla_byte = "00"
1134 self._scc.sel_ctrl = "0004" #request an FCP
1135
1136 @classmethod
1137 def autodetect(kls, scc):
1138 try:
1139 # Try card model #1
1140 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1141 if scc.get_atr() == toBytes(atr):
1142 return kls(scc)
1143
1144 # Try card model #2
1145 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1146 if scc.get_atr() == toBytes(atr):
1147 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001148
1149 # Try card model #3
1150 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1151 if scc.get_atr() == toBytes(atr):
1152 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001153 except:
1154 return None
1155 return None
1156
1157 def program(self, p):
1158 # authenticate as ADM using default key (written on the card..)
1159 if not p['pin_adm']:
1160 raise ValueError("Please provide a PIN-ADM as there is no default one")
1161 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1162
1163 # This type of card does not allow to reprogram the ICCID.
1164 # Reprogramming the ICCID would mess up the card os software
1165 # license management, so the ICCID must be kept at its factory
1166 # setting!
1167 if p.get('iccid'):
1168 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1169
1170 # select DF_GSM
1171 self._scc.select_file(['7f20'])
1172
1173 # write EF.IMSI
1174 if p.get('imsi'):
1175 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1176
1177 # EF.PLMNsel
1178 if p.get('mcc') and p.get('mnc'):
1179 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1180 if sw != '9000':
1181 print("Programming PLMNsel failed with code %s"%sw)
1182
1183 # EF.PLMNwAcT
1184 if p.get('mcc') and p.get('mnc'):
1185 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1186 if sw != '9000':
1187 print("Programming PLMNwAcT failed with code %s"%sw)
1188
1189 # EF.OPLMNwAcT
1190 if p.get('mcc') and p.get('mnc'):
1191 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1192 if sw != '9000':
1193 print("Programming OPLMNwAcT failed with code %s"%sw)
1194
Harald Welte32f0d412020-05-05 17:35:57 +02001195 # EF.HPLMNwAcT
1196 if p.get('mcc') and p.get('mnc'):
1197 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1198 if sw != '9000':
1199 print("Programming HPLMNwAcT failed with code %s"%sw)
1200
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001201 # EF.AD
1202 if p.get('mcc') and p.get('mnc'):
1203 sw = self.update_ad(p['mnc'])
1204 if sw != '9000':
1205 print("Programming AD failed with code %s"%sw)
1206
1207 # EF.SMSP
1208 if p.get('smsp'):
1209 r = self._scc.select_file(['3f00', '7f10'])
1210 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1211
Supreeth Herle80164052020-03-23 12:06:29 +01001212 # Populate AIDs
1213 self.read_aids()
1214
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001215 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1216 # hard linked to EF-USIM_AUTH_KEY)
1217 self._scc.select_file(['3f00'])
1218 self._scc.select_file(['a515'])
1219 if p.get('ki'):
1220 self._scc.update_binary('6f20', p['ki'], 1)
1221 if p.get('opc'):
1222 self._scc.update_binary('6f20', p['opc'], 17)
1223
1224 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001225 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001226 if p.get('ki'):
1227 self._scc.update_binary('af20', p['ki'], 1)
1228 if p.get('opc'):
1229 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001230
Supreeth Herlecf727f22020-03-24 17:32:21 +01001231 # update EF.P-CSCF in ADF.ISIM
1232 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1233 if p.get('pcscf'):
1234 sw = self.update_pcscf(p['pcscf'])
1235 else:
1236 sw = self.update_pcscf("")
1237 if sw != '9000':
1238 print("Programming P-CSCF failed with code %s"%sw)
1239
1240
herlesupreeth1a13c442020-09-11 21:16:51 +02001241 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001242 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001243 if p.get('ki'):
1244 self._scc.update_binary('af20', p['ki'], 1)
1245 if p.get('opc'):
1246 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001247
Harald Welteca673942020-06-03 15:19:40 +02001248 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001249 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001250 if p.get('mcc') and p.get('mnc'):
1251 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1252 if sw != '9000':
1253 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001254
1255 # update EF.ePDGId in ADF.USIM
1256 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1257 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001258 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001259 if sw != '9000':
1260 print("Programming ePDGId failed with code %s"%sw)
1261
Supreeth Herlef964df42020-03-24 13:15:37 +01001262 # update EF.ePDGSelection in ADF.USIM
1263 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1264 if p.get('epdgSelection'):
1265 epdg_plmn = p['epdgSelection']
1266 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1267 else:
1268 sw = self.update_ePDGSelection("", "")
1269 if sw != '9000':
1270 print("Programming ePDGSelection failed with code %s"%sw)
1271
1272
Supreeth Herleacc222f2020-03-24 13:26:53 +01001273 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1274 # Set service 106 and 107 as available in EF.UST
1275 if self.file_exists(EF_USIM_ADF_map['UST']):
1276 if p.get('epdgSelection') and p.get('epdgid'):
1277 sw = self.update_ust(106, 1)
1278 if sw != '9000':
1279 print("Programming UST failed with code %s"%sw)
1280 sw = self.update_ust(107, 1)
1281 if sw != '9000':
1282 print("Programming UST failed with code %s"%sw)
1283
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001284 return
1285
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001286
Todd Neal9eeadfc2018-04-25 15:36:29 -05001287# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001288_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001289 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001290 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001291
1292def card_autodetect(scc):
1293 for kls in _cards_classes:
1294 card = kls.autodetect(scc)
1295 if card is not None:
1296 card.reset()
1297 return card
1298 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001299
1300def card_detect(ctype, scc):
1301 # Detect type if needed
1302 card = None
1303 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1304
1305 if ctype in ("auto", "auto_once"):
1306 for kls in _cards_classes:
1307 card = kls.autodetect(scc)
1308 if card:
1309 print("Autodetected card type: %s" % card.name)
1310 card.reset()
1311 break
1312
1313 if card is None:
1314 print("Autodetection failed")
1315 return None
1316
1317 if ctype == "auto_once":
1318 ctype = card.name
1319
1320 elif ctype in ctypes:
1321 card = ctypes[ctype](scc)
1322
1323 else:
1324 raise ValueError("Unknown card type: %s" % ctype)
1325
1326 return card