blob: 7e4791622e0c335aa67ff71702ac83bc65f8692a [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
Supreeth Herle79f43dd2020-03-25 11:43:19 +010031from pytlv.TLV import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010032
33class Card(object):
34
35 def __init__(self, scc):
36 self._scc = scc
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030037 self._adm_chv_num = 4
Supreeth Herlee4e98312020-03-18 11:33:14 +010038 self._aids = []
Sylvain Munaut76504e02010-12-07 00:24:32 +010039
Sylvain Munaut76504e02010-12-07 00:24:32 +010040 def reset(self):
41 self._scc.reset_card()
42
Philipp Maierd58c6322020-05-12 16:47:45 +020043 def erase(self):
44 print("warning: erasing is not supported for specified card type!")
45 return
46
Harald Welteca673942020-06-03 15:19:40 +020047 def file_exists(self, fid):
48 res_arr = self._scc.try_select_file(fid)
49 for res in res_arr:
Harald Welte1e424202020-08-31 15:04:19 +020050 if res[1] != '9000':
51 return False
Harald Welteca673942020-06-03 15:19:40 +020052 return True
53
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030054 def verify_adm(self, key):
55 '''
56 Authenticate with ADM key
57 '''
58 (res, sw) = self._scc.verify_chv(self._adm_chv_num, key)
59 return sw
60
61 def read_iccid(self):
62 (res, sw) = self._scc.read_binary(EF['ICCID'])
63 if sw == '9000':
64 return (dec_iccid(res), sw)
65 else:
66 return (None, sw)
67
68 def read_imsi(self):
69 (res, sw) = self._scc.read_binary(EF['IMSI'])
70 if sw == '9000':
71 return (dec_imsi(res), sw)
72 else:
73 return (None, sw)
74
75 def update_imsi(self, imsi):
76 data, sw = self._scc.update_binary(EF['IMSI'], enc_imsi(imsi))
77 return sw
78
79 def update_acc(self, acc):
80 data, sw = self._scc.update_binary(EF['ACC'], lpad(acc, 4))
81 return sw
82
Supreeth Herlea850a472020-03-19 12:44:11 +010083 def read_hplmn_act(self):
84 (res, sw) = self._scc.read_binary(EF['HPLMNAcT'])
85 if sw == '9000':
86 return (format_xplmn_w_act(res), sw)
87 else:
88 return (None, sw)
89
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030090 def update_hplmn_act(self, mcc, mnc, access_tech='FFFF'):
91 """
92 Update Home PLMN with access technology bit-field
93
94 See Section "10.3.37 EFHPLMNwAcT (HPLMN Selector with Access Technology)"
95 in ETSI TS 151 011 for the details of the access_tech field coding.
96 Some common values:
97 access_tech = '0080' # Only GSM is selected
98 access_tech = 'FFFF' # All technologues selected, even Reserved for Future Use ones
99 """
100 # get size and write EF.HPLMNwAcT
Supreeth Herle2d785972019-11-30 11:00:10 +0100101 data = self._scc.read_binary(EF['HPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700102 size = len(data[0]) // 2
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300103 hplmn = enc_plmn(mcc, mnc)
104 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700105 data, sw = self._scc.update_binary(EF['HPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300106 return sw
107
Supreeth Herle1757b262020-03-19 12:43:11 +0100108 def read_oplmn_act(self):
109 (res, sw) = self._scc.read_binary(EF['OPLMNwAcT'])
110 if sw == '9000':
111 return (format_xplmn_w_act(res), sw)
112 else:
113 return (None, sw)
114
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200115 def update_oplmn_act(self, mcc, mnc, access_tech='FFFF'):
116 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200117 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200118 """
119 # get size and write EF.OPLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200120 data = self._scc.read_binary(EF['OPLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700121 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200122 hplmn = enc_plmn(mcc, mnc)
123 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700124 data, sw = self._scc.update_binary(EF['OPLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200125 return sw
126
Supreeth Herle14084402020-03-19 12:42:10 +0100127 def read_plmn_act(self):
128 (res, sw) = self._scc.read_binary(EF['PLMNwAcT'])
129 if sw == '9000':
130 return (format_xplmn_w_act(res), sw)
131 else:
132 return (None, sw)
133
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200134 def update_plmn_act(self, mcc, mnc, access_tech='FFFF'):
135 """
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200136 See note in update_hplmn_act()
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200137 """
138 # get size and write EF.PLMNwAcT
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200139 data = self._scc.read_binary(EF['PLMNwAcT'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700140 size = len(data[0]) // 2
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200141 hplmn = enc_plmn(mcc, mnc)
142 content = hplmn + access_tech
Vadim Yanitskiy9664b2e2020-02-27 01:49:51 +0700143 data, sw = self._scc.update_binary(EF['PLMNwAcT'], content + 'ffffff0000' * (size // 5 - 1))
Philipp Maierc8ce82a2018-07-04 17:57:20 +0200144 return sw
145
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200146 def update_plmnsel(self, mcc, mnc):
147 data = self._scc.read_binary(EF['PLMNsel'], length=None, offset=0)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700148 size = len(data[0]) // 2
Philipp Maier5bf42602018-07-11 23:23:40 +0200149 hplmn = enc_plmn(mcc, mnc)
Philipp Maieraf9ae8b2018-07-13 11:15:49 +0200150 data, sw = self._scc.update_binary(EF['PLMNsel'], hplmn + 'ff' * (size-3))
151 return sw
Philipp Maier5bf42602018-07-11 23:23:40 +0200152
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300153 def update_smsp(self, smsp):
154 data, sw = self._scc.update_record(EF['SMSP'], 1, rpad(smsp, 84))
155 return sw
156
Philipp Maieree908ae2019-03-21 16:21:12 +0100157 def update_ad(self, mnc):
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200158 #See also: 3GPP TS 31.102, chapter 4.2.18
159 mnclen = len(str(mnc))
160 if mnclen == 1:
161 mnclen = 2
162 if mnclen > 3:
Philipp Maieree908ae2019-03-21 16:21:12 +0100163 raise RuntimeError('unable to calculate proper mnclen')
164
Philipp Maier7f9f64a2020-05-11 21:28:52 +0200165 data, sw = self._scc.read_binary(EF['AD'], length=None, offset=0)
166
167 # Reset contents to EF.AD in case the file is uninintalized
168 if data.lower() == "ffffffff":
169 data = "00000000"
170
171 content = data[0:6] + "%02X" % mnclen
Philipp Maieree908ae2019-03-21 16:21:12 +0100172 data, sw = self._scc.update_binary(EF['AD'], content)
173 return sw
174
Alexander Chemeriseb6807d2017-07-18 17:04:38 +0300175 def read_spn(self):
176 (spn, sw) = self._scc.read_binary(EF['SPN'])
177 if sw == '9000':
178 return (dec_spn(spn), sw)
179 else:
180 return (None, sw)
181
182 def update_spn(self, name, hplmn_disp=False, oplmn_disp=False):
183 content = enc_spn(name, hplmn_disp, oplmn_disp)
184 data, sw = self._scc.update_binary(EF['SPN'], rpad(content, 32))
185 return sw
186
Supreeth Herled21349a2020-04-01 08:37:47 +0200187 def read_binary(self, ef, length=None, offset=0):
188 ef_path = ef in EF and EF[ef] or ef
189 return self._scc.read_binary(ef_path, length, offset)
190
Supreeth Herlead10d662020-04-01 08:43:08 +0200191 def read_record(self, ef, rec_no):
192 ef_path = ef in EF and EF[ef] or ef
193 return self._scc.read_record(ef_path, rec_no)
194
Supreeth Herle98a69272020-03-18 12:14:48 +0100195 def read_gid1(self):
196 (res, sw) = self._scc.read_binary(EF['GID1'])
197 if sw == '9000':
198 return (res, sw)
199 else:
200 return (None, sw)
201
Supreeth Herle6d66af62020-03-19 12:49:16 +0100202 def read_msisdn(self):
203 (res, sw) = self._scc.read_record(EF['MSISDN'], 1)
204 if sw == '9000':
205 return (dec_msisdn(res), sw)
206 else:
207 return (None, sw)
208
Supreeth Herlee4e98312020-03-18 11:33:14 +0100209 # Fetch all the AIDs present on UICC
210 def read_aids(self):
211 try:
212 # Find out how many records the EF.DIR has
213 # and store all the AIDs in the UICC
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100214 rec_cnt = self._scc.record_count(EF['DIR'])
Supreeth Herlee4e98312020-03-18 11:33:14 +0100215 for i in range(0, rec_cnt):
Sebastian Viviani0dc8f692020-05-29 00:14:55 +0100216 rec = self._scc.read_record(EF['DIR'], i + 1)
Supreeth Herlee4e98312020-03-18 11:33:14 +0100217 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
218 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
219 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
220 except Exception as e:
221 print("Can't read AIDs from SIM -- %s" % (str(e),))
222
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100223 # Select ADF.U/ISIM in the Card using its full AID
224 def select_adf_by_aid(self, adf="usim"):
225 # Check for valid ADF name
226 if adf not in ["usim", "isim"]:
227 return None
228
229 # First (known) halves of the U/ISIM AID
230 aid_map = {}
231 aid_map["usim"] = "a0000000871002"
232 aid_map["isim"] = "a0000000871004"
233
234 for aid in self._aids:
235 if aid_map[adf] in aid:
236 (res, sw) = self._scc.select_adf(aid)
237 return sw
238
239 return None
240
Philipp Maier5c2cc662020-05-12 16:27:12 +0200241 # Erase the contents of a file
242 def erase_binary(self, ef):
243 len = self._scc.binary_size(ef)
244 self._scc.update_binary(ef, "ff" * len, offset=0, verify=True)
245
246 # Erase the contents of a single record
247 def erase_record(self, ef, rec_no):
248 len = self._scc.record_size(ef)
249 self._scc.update_record(ef, rec_no, "ff" * len, force_len=False, verify=True)
250
Harald Welteca673942020-06-03 15:19:40 +0200251class UsimCard(Card):
252 def __init__(self, ssc):
253 super(UsimCard, self).__init__(ssc)
254
255 def read_ehplmn(self):
256 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'])
257 if sw == '9000':
258 return (format_xplmn(res), sw)
259 else:
260 return (None, sw)
261
262 def update_ehplmn(self, mcc, mnc):
263 data = self._scc.read_binary(EF_USIM_ADF_map['EHPLMN'], length=None, offset=0)
264 size = len(data[0]) // 2
265 ehplmn = enc_plmn(mcc, mnc)
266 data, sw = self._scc.update_binary(EF_USIM_ADF_map['EHPLMN'], ehplmn)
267 return sw
268
herlesupreethf8232db2020-09-29 10:03:06 +0200269 def read_epdgid(self):
270 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGId'])
271 if sw == '9000':
Supreeth Herle3b342c22020-03-24 16:15:02 +0100272 return (dec_addr_tlv(res), sw)
herlesupreethf8232db2020-09-29 10:03:06 +0200273 else:
274 return (None, sw)
275
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200276 def update_epdgid(self, epdgid):
Supreeth Herle3b342c22020-03-24 16:15:02 +0100277 epdgid_tlv = enc_addr_tlv(epdgid)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200278 data, sw = self._scc.update_binary(
279 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
280 return sw
Harald Welteca673942020-06-03 15:19:40 +0200281
Supreeth Herle99d55552020-03-24 13:03:43 +0100282 def read_ePDGSelection(self):
283 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
284 if sw == '9000':
285 return (format_ePDGSelection(res), sw)
286 else:
287 return (None, sw)
288
Supreeth Herlef964df42020-03-24 13:15:37 +0100289 def update_ePDGSelection(self, mcc, mnc):
290 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
291 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
292 # Reset contents
293 # 80 - Tag value
294 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
295 elif sw == '9000':
296 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
297 return sw
298
herlesupreeth4a3580b2020-09-29 10:11:36 +0200299 def read_ust(self):
300 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
301 if sw == '9000':
302 # Print those which are available
303 return ([res, dec_st(res, table="usim")], sw)
304 else:
305 return ([None, None], sw)
306
Supreeth Herleacc222f2020-03-24 13:26:53 +0100307 def update_ust(self, service, bit=1):
308 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
309 if sw == '9000':
310 content = enc_st(res, service, bit)
311 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
312 return sw
313
herlesupreethecbada92020-12-23 09:24:29 +0100314class IsimCard(Card):
315 def __init__(self, ssc):
316 super(IsimCard, self).__init__(ssc)
317
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100318 def read_pcscf(self):
319 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
320 pcscf_recs = ""
321 for i in range(0, rec_cnt):
322 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
323 if sw == '9000':
324 content = dec_addr_tlv(res)
325 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
326 else:
327 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
328 return pcscf_recs
329
Supreeth Herlecf727f22020-03-24 17:32:21 +0100330 def update_pcscf(self, pcscf):
331 if len(pcscf) > 0:
332 content = enc_addr_tlv(pcscf)
333 else:
334 # Just the tag value
335 content = '80'
336 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
337 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, rpad(content, rec_size_bytes*2))
338 return sw
339
Supreeth Herle05b28072020-03-25 10:23:48 +0100340 def read_domain(self):
341 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
342 if sw == '9000':
343 # Skip the inital tag value ('80') byte and get length of contents
344 length = int(res[2:4], 16)
345 content = h2s(res[4:4+(length*2)])
346 return (content, sw)
347 else:
348 return (None, sw)
349
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100350 def update_domain(self, domain=None, mcc=None, mnc=None):
351 hex_str = ""
352 if domain:
353 hex_str = s2h(domain)
354 elif mcc and mnc:
355 # MCC and MNC always has 3 digits in domain form
356 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
357 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
358
359 # Build TLV
360 tlv = TLV(['80'])
361 content = tlv.build({'80': hex_str})
362
363 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
364 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
365 return sw
366
Sylvain Munaut76504e02010-12-07 00:24:32 +0100367
368class _MagicSimBase(Card):
369 """
370 Theses cards uses several record based EFs to store the provider infos,
371 each possible provider uses a specific record number in each EF. The
372 indexes used are ( where N is the number of providers supported ) :
373 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100374 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100375
376 * 3f00/7f4d/8f0c : Operator Name
377
378 bytes 0-15 : provider name, padded with 0xff
379 byte 16 : length of the provider name
380 byte 17 : 01 for valid records, 00 otherwise
381
382 * 3f00/7f4d/8f0d : Programmable Binary EFs
383
384 * 3f00/7f4d/8f0e : Programmable Record EFs
385
386 """
387
388 @classmethod
389 def autodetect(kls, scc):
390 try:
391 for p, l, t in kls._files.values():
392 if not t:
393 continue
394 if scc.record_size(['3f00', '7f4d', p]) != l:
395 return None
396 except:
397 return None
398
399 return kls(scc)
400
401 def _get_count(self):
402 """
403 Selects the file and returns the total number of entries
404 and entry size
405 """
406 f = self._files['name']
407
408 r = self._scc.select_file(['3f00', '7f4d', f[0]])
409 rec_len = int(r[-1][28:30], 16)
410 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200411 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100412
413 if (rec_cnt < 1) or (rec_len != f[1]):
414 raise RuntimeError('Bad card type')
415
416 return rec_cnt
417
418 def program(self, p):
419 # Go to dir
420 self._scc.select_file(['3f00', '7f4d'])
421
422 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400423 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424
425 # Operator name ( 3f00/7f4d/8f0c )
426 self._scc.update_record(self._files['name'][0], 2,
427 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
428 )
429
430 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
431 v = ''
432
433 # inline Ki
434 if self._ki_file is None:
435 v += p['ki']
436
437 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400438 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100439
440 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400441 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100442
443 # Ki
444 if self._ki_file:
445 v += self._ki_file + '10' + p['ki']
446
447 # PLMN_Sel
448 v+= '6f30' + '18' + rpad(hplmn, 36)
449
Alexander Chemeris21885242013-07-02 16:56:55 +0400450 # ACC
451 # This doesn't work with "fake" SuperSIM cards,
452 # but will hopefully work with real SuperSIMs.
453 if p.get('acc') is not None:
454 v+= '6f78' + '02' + lpad(p['acc'], 4)
455
Sylvain Munaut76504e02010-12-07 00:24:32 +0100456 self._scc.update_record(self._files['b_ef'][0], 1,
457 rpad(v, self._files['b_ef'][1]*2)
458 )
459
460 # SMSP ( 3f00/7f4d/8f0e )
461 # FIXME
462
463 # Write PLMN_Sel forcefully as well
464 r = self._scc.select_file(['3f00', '7f20', '6f30'])
465 tl = int(r[-1][4:8], 16)
466
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400467 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100468 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
469
470 def erase(self):
471 # Dummy
472 df = {}
473 for k, v in self._files.iteritems():
474 ofs = 1
475 fv = v[1] * 'ff'
476 if k == 'name':
477 ofs = 2
478 fv = fv[0:-4] + '0000'
479 df[v[0]] = (fv, ofs)
480
481 # Write
482 for n in range(0,self._get_count()):
483 for k, (msg, ofs) in df.iteritems():
484 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
485
486
487class SuperSim(_MagicSimBase):
488
489 name = 'supersim'
490
491 _files = {
492 'name' : ('8f0c', 18, True),
493 'b_ef' : ('8f0d', 74, True),
494 'r_ef' : ('8f0e', 50, True),
495 }
496
497 _ki_file = None
498
499
500class MagicSim(_MagicSimBase):
501
502 name = 'magicsim'
503
504 _files = {
505 'name' : ('8f0c', 18, True),
506 'b_ef' : ('8f0d', 130, True),
507 'r_ef' : ('8f0e', 102, False),
508 }
509
510 _ki_file = '6f1b'
511
512
513class FakeMagicSim(Card):
514 """
515 Theses cards have a record based EF 3f00/000c that contains the provider
516 informations. See the program method for its format. The records go from
517 1 to N.
518 """
519
520 name = 'fakemagicsim'
521
522 @classmethod
523 def autodetect(kls, scc):
524 try:
525 if scc.record_size(['3f00', '000c']) != 0x5a:
526 return None
527 except:
528 return None
529
530 return kls(scc)
531
532 def _get_infos(self):
533 """
534 Selects the file and returns the total number of entries
535 and entry size
536 """
537
538 r = self._scc.select_file(['3f00', '000c'])
539 rec_len = int(r[-1][28:30], 16)
540 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200541 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100542
543 if (rec_cnt < 1) or (rec_len != 0x5a):
544 raise RuntimeError('Bad card type')
545
546 return rec_cnt, rec_len
547
548 def program(self, p):
549 # Home PLMN
550 r = self._scc.select_file(['3f00', '7f20', '6f30'])
551 tl = int(r[-1][4:8], 16)
552
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400553 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100554 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
555
556 # Get total number of entries and entry size
557 rec_cnt, rec_len = self._get_infos()
558
559 # Set first entry
560 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200561 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100562 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200563 enc_iccid(p['iccid']) + # 10b ICCID
564 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
565 p['ki'] + # 16b Ki
566 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100567 )
568 self._scc.update_record('000c', 1, entry)
569
570 def erase(self):
571 # Get total number of entries and entry size
572 rec_cnt, rec_len = self._get_infos()
573
574 # Erase all entries
575 entry = 'ff' * rec_len
576 for i in range(0, rec_cnt):
577 self._scc.update_record('000c', 1+i, entry)
578
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200579
Harald Welte3156d902011-03-22 21:48:19 +0100580class GrcardSim(Card):
581 """
582 Greencard (grcard.cn) HZCOS GSM SIM
583 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
584 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
585 """
586
587 name = 'grcardsim'
588
589 @classmethod
590 def autodetect(kls, scc):
591 return None
592
593 def program(self, p):
594 # We don't really know yet what ADM PIN 4 is about
595 #self._scc.verify_chv(4, h2b("4444444444444444"))
596
597 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100598 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200599 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100600 else:
601 pin = h2b("4444444444444444")
602 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100603
604 # EF.ICCID
605 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400606 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100607
608 # EF.IMSI
609 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400610 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100611
612 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400613 if p.get('acc') is not None:
614 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100615
616 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200617 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200618 r = self._scc.select_file(['3f00', '7f10', '6f42'])
619 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100620
621 # Set the Ki using proprietary command
622 pdu = '80d4020010' + p['ki']
623 data, sw = self._scc._tp.send_apdu(pdu)
624
625 # EF.HPLMN
626 r = self._scc.select_file(['3f00', '7f20', '6f30'])
627 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400628 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100629 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
630
631 # EF.SPN (Service Provider Name)
632 r = self._scc.select_file(['3f00', '7f20', '6f30'])
633 size = int(r[-1][4:8], 16)
634 # FIXME
635
636 # FIXME: EF.MSISDN
637
Sylvain Munaut76504e02010-12-07 00:24:32 +0100638
Harald Weltee10394b2011-12-07 12:34:14 +0100639class SysmoSIMgr1(GrcardSim):
640 """
641 sysmocom sysmoSIM-GR1
642 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
643 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
644 """
645 name = 'sysmosim-gr1'
646
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200647 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200648 def autodetect(kls, scc):
649 try:
650 # Look for ATR
651 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
652 return kls(scc)
653 except:
654 return None
655 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200656
Harald Welteca673942020-06-03 15:19:40 +0200657class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100658 """
659 sysmocom sysmoUSIM-GR1
660 """
661 name = 'sysmoUSIM-GR1'
662
663 @classmethod
664 def autodetect(kls, scc):
665 # TODO: Access the ATR
666 return None
667
668 def program(self, p):
669 # TODO: check if verify_chv could be used or what it needs
670 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
671 # Unlock the card..
672 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
673
674 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100675 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400676 p['opc'] + # 32b OPC
677 enc_iccid(p['iccid']) + # 10b ICCID
678 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100679 )
680 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
681
Sylvain Munaut053c8952013-07-02 15:12:32 +0200682
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100683class SysmoSIMgr2(Card):
684 """
685 sysmocom sysmoSIM-GR2
686 """
687
688 name = 'sysmoSIM-GR2'
689
690 @classmethod
691 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900692 try:
693 # Look for ATR
694 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
695 return kls(scc)
696 except:
697 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100698 return None
699
700 def program(self, p):
701
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200702 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100703 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200704
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100705 # authenticate as SUPER ADM using default key
706 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
707
708 # set ADM pin using proprietary command
709 # INS: D4
710 # P1: 3A for PIN, 3B for PUK
711 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
712 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100713 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200714 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100715 else:
716 pin = h2b("4444444444444444")
717
718 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100719 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200720
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100721 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100722
723 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100724
725 # write EF.ICCID
726 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
727
728 # select DF_GSM
729 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200730
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100731 # write EF.IMSI
732 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
733
734 # write EF.ACC
735 if p.get('acc') is not None:
736 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
737
738 # get size and write EF.HPLMN
739 r = self._scc.select_file(['6f30'])
740 size = int(r[-1][4:8], 16)
741 hplmn = enc_plmn(p['mcc'], p['mnc'])
742 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
743
744 # set COMP128 version 0 in proprietary file
745 data, sw = self._scc.update_binary('0001', '001000')
746
747 # set Ki in proprietary file
748 data, sw = self._scc.update_binary('0001', p['ki'], 3)
749
750 # select DF_TELECOM
751 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200752
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100753 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200754 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200755 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100756
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100757
Harald Welteca673942020-06-03 15:19:40 +0200758class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100759 """
760 sysmocom sysmoUSIM-SJS1
761 """
762
763 name = 'sysmoUSIM-SJS1'
764
765 def __init__(self, ssc):
766 super(SysmoUSIMSJS1, self).__init__(ssc)
767 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100768 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100769
770 @classmethod
771 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900772 try:
773 # Look for ATR
774 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"):
775 return kls(scc)
776 except:
777 return None
Jan Balke3e840672015-01-26 15:36:27 +0100778 return None
779
780 def program(self, p):
781
Philipp Maiere9604882017-03-21 17:24:31 +0100782 # authenticate as ADM using default key (written on the card..)
783 if not p['pin_adm']:
784 raise ValueError("Please provide a PIN-ADM as there is no default one")
785 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100786
787 # select MF
788 r = self._scc.select_file(['3f00'])
789
Philipp Maiere9604882017-03-21 17:24:31 +0100790 # write EF.ICCID
791 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
792
Jan Balke3e840672015-01-26 15:36:27 +0100793 # select DF_GSM
794 r = self._scc.select_file(['7f20'])
795
Jan Balke3e840672015-01-26 15:36:27 +0100796 # set Ki in proprietary file
797 data, sw = self._scc.update_binary('00FF', p['ki'])
798
Philipp Maier1be35bf2018-07-13 11:29:03 +0200799 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200800 if 'opc' in p:
801 content = "01" + p['opc']
802 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100803
Supreeth Herle7947d922019-06-08 07:50:53 +0200804 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100805 if p.get('name') is not None:
806 content = enc_spn(p['name'], True, True)
807 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200808
Supreeth Herlec8796a32019-12-23 12:23:42 +0100809 if p.get('acc') is not None:
810 self.update_acc(p['acc'])
811
Jan Balke3e840672015-01-26 15:36:27 +0100812 # write EF.IMSI
813 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
814
Philipp Maier2d15ea02019-03-20 12:40:36 +0100815 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200816 if p.get('mcc') and p.get('mnc'):
817 sw = self.update_plmnsel(p['mcc'], p['mnc'])
818 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100819 print("Programming PLMNsel failed with code %s"%sw)
820
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200821 # EF.PLMNwAcT
822 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100823 sw = self.update_plmn_act(p['mcc'], p['mnc'])
824 if sw != '9000':
825 print("Programming PLMNwAcT failed with code %s"%sw)
826
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200827 # EF.OPLMNwAcT
828 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100829 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
830 if sw != '9000':
831 print("Programming OPLMNwAcT failed with code %s"%sw)
832
Supreeth Herlef442fb42020-01-21 12:47:32 +0100833 # EF.HPLMNwAcT
834 if p.get('mcc') and p.get('mnc'):
835 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
836 if sw != '9000':
837 print("Programming HPLMNwAcT failed with code %s"%sw)
838
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200839 # EF.AD
840 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100841 sw = self.update_ad(p['mnc'])
842 if sw != '9000':
843 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100844
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200845 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200846 if p.get('smsp'):
847 r = self._scc.select_file(['3f00', '7f10'])
848 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100849
Supreeth Herle5a541012019-12-22 08:59:16 +0100850 # EF.MSISDN
851 # TODO: Alpha Identifier (currently 'ff'O * 20)
852 # TODO: Capability/Configuration1 Record Identifier
853 # TODO: Extension1 Record Identifier
854 if p.get('msisdn') is not None:
855 msisdn = enc_msisdn(p['msisdn'])
856 data = 'ff' * 20 + msisdn + 'ff' * 2
857
858 r = self._scc.select_file(['3f00', '7f10'])
859 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
860
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900861
herlesupreeth4a3580b2020-09-29 10:11:36 +0200862class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900863 """
864 FairwavesSIM
865
866 The SIM card is operating according to the standard.
867 For Ki/OP/OPC programming the following files are additionally open for writing:
868 3F00/7F20/FF01 – OP/OPC:
869 byte 1 = 0x01, bytes 2-17: OPC;
870 byte 1 = 0x00, bytes 2-17: OP;
871 3F00/7F20/FF02: Ki
872 """
873
Philipp Maier5a876312019-11-11 11:01:46 +0100874 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900875 # Propriatary files
876 _EF_num = {
877 'Ki': 'FF02',
878 'OP/OPC': 'FF01',
879 }
880 _EF = {
881 'Ki': DF['GSM']+[_EF_num['Ki']],
882 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
883 }
884
885 def __init__(self, ssc):
886 super(FairwavesSIM, self).__init__(ssc)
887 self._adm_chv_num = 0x11
888 self._adm2_chv_num = 0x12
889
890
891 @classmethod
892 def autodetect(kls, scc):
893 try:
894 # Look for ATR
895 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"):
896 return kls(scc)
897 except:
898 return None
899 return None
900
901
902 def verify_adm2(self, key):
903 '''
904 Authenticate with ADM2 key.
905
906 Fairwaves SIM cards support hierarchical key structure and ADM2 key
907 is a key which has access to proprietary files (Ki and OP/OPC).
908 That said, ADM key inherits permissions of ADM2 key and thus we rarely
909 need ADM2 key per se.
910 '''
911 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
912 return sw
913
914
915 def read_ki(self):
916 """
917 Read Ki in proprietary file.
918
919 Requires ADM1 access level
920 """
921 return self._scc.read_binary(self._EF['Ki'])
922
923
924 def update_ki(self, ki):
925 """
926 Set Ki in proprietary file.
927
928 Requires ADM1 access level
929 """
930 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
931 return sw
932
933
934 def read_op_opc(self):
935 """
936 Read Ki in proprietary file.
937
938 Requires ADM1 access level
939 """
940 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
941 type = 'OP' if ef[0:2] == '00' else 'OPC'
942 return ((type, ef[2:]), sw)
943
944
945 def update_op(self, op):
946 """
947 Set OP in proprietary file.
948
949 Requires ADM1 access level
950 """
951 content = '00' + op
952 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
953 return sw
954
955
956 def update_opc(self, opc):
957 """
958 Set OPC in proprietary file.
959
960 Requires ADM1 access level
961 """
962 content = '01' + opc
963 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
964 return sw
965
966
967 def program(self, p):
968 # authenticate as ADM1
969 if not p['pin_adm']:
970 raise ValueError("Please provide a PIN-ADM as there is no default one")
971 sw = self.verify_adm(h2b(p['pin_adm']))
972 if sw != '9000':
973 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
974
975 # TODO: Set operator name
976 if p.get('smsp') is not None:
977 sw = self.update_smsp(p['smsp'])
978 if sw != '9000':
979 print("Programming SMSP failed with code %s"%sw)
980 # This SIM doesn't support changing ICCID
981 if p.get('mcc') is not None and p.get('mnc') is not None:
982 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
983 if sw != '9000':
984 print("Programming MCC/MNC failed with code %s"%sw)
985 if p.get('imsi') is not None:
986 sw = self.update_imsi(p['imsi'])
987 if sw != '9000':
988 print("Programming IMSI failed with code %s"%sw)
989 if p.get('ki') is not None:
990 sw = self.update_ki(p['ki'])
991 if sw != '9000':
992 print("Programming Ki failed with code %s"%sw)
993 if p.get('opc') is not None:
994 sw = self.update_opc(p['opc'])
995 if sw != '9000':
996 print("Programming OPC failed with code %s"%sw)
997 if p.get('acc') is not None:
998 sw = self.update_acc(p['acc'])
999 if sw != '9000':
1000 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001001
Todd Neal9eeadfc2018-04-25 15:36:29 -05001002class OpenCellsSim(Card):
1003 """
1004 OpenCellsSim
1005
1006 """
1007
Philipp Maier5a876312019-11-11 11:01:46 +01001008 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001009
1010 def __init__(self, ssc):
1011 super(OpenCellsSim, self).__init__(ssc)
1012 self._adm_chv_num = 0x0A
1013
1014
1015 @classmethod
1016 def autodetect(kls, scc):
1017 try:
1018 # Look for ATR
1019 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"):
1020 return kls(scc)
1021 except:
1022 return None
1023 return None
1024
1025
1026 def program(self, p):
1027 if not p['pin_adm']:
1028 raise ValueError("Please provide a PIN-ADM as there is no default one")
1029 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1030
1031 # select MF
1032 r = self._scc.select_file(['3f00'])
1033
1034 # write EF.ICCID
1035 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1036
1037 r = self._scc.select_file(['7ff0'])
1038
1039 # set Ki in proprietary file
1040 data, sw = self._scc.update_binary('FF02', p['ki'])
1041
1042 # set OPC in proprietary file
1043 data, sw = self._scc.update_binary('FF01', p['opc'])
1044
1045 # select DF_GSM
1046 r = self._scc.select_file(['7f20'])
1047
1048 # write EF.IMSI
1049 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1050
herlesupreeth4a3580b2020-09-29 10:11:36 +02001051class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001052 """
1053 WavemobileSim
1054
1055 """
1056
1057 name = 'Wavemobile-SIM'
1058
1059 def __init__(self, ssc):
1060 super(WavemobileSim, self).__init__(ssc)
1061 self._adm_chv_num = 0x0A
1062 self._scc.cla_byte = "00"
1063 self._scc.sel_ctrl = "0004" #request an FCP
1064
1065 @classmethod
1066 def autodetect(kls, scc):
1067 try:
1068 # Look for ATR
1069 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"):
1070 return kls(scc)
1071 except:
1072 return None
1073 return None
1074
1075 def program(self, p):
1076 if not p['pin_adm']:
1077 raise ValueError("Please provide a PIN-ADM as there is no default one")
1078 sw = self.verify_adm(h2b(p['pin_adm']))
1079 if sw != '9000':
1080 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1081
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001082 # EF.ICCID
1083 # TODO: Add programming of the ICCID
1084 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001085 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1086
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001087 # KI (Presumably a propritary file)
1088 # TODO: Add programming of KI
1089 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001090 print("Warning: Programming of the KI is not implemented for this type of card.")
1091
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001092 # OPc (Presumably a propritary file)
1093 # TODO: Add programming of OPc
1094 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001095 print("Warning: Programming of the OPc is not implemented for this type of card.")
1096
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001097 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001098 if p.get('smsp'):
1099 sw = self.update_smsp(p['smsp'])
1100 if sw != '9000':
1101 print("Programming SMSP failed with code %s"%sw)
1102
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001103 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001104 if p.get('imsi'):
1105 sw = self.update_imsi(p['imsi'])
1106 if sw != '9000':
1107 print("Programming IMSI failed with code %s"%sw)
1108
1109 # EF.ACC
1110 if p.get('acc'):
1111 sw = self.update_acc(p['acc'])
1112 if sw != '9000':
1113 print("Programming ACC failed with code %s"%sw)
1114
1115 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001116 if p.get('mcc') and p.get('mnc'):
1117 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1118 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001119 print("Programming PLMNsel failed with code %s"%sw)
1120
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001121 # EF.PLMNwAcT
1122 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001123 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1124 if sw != '9000':
1125 print("Programming PLMNwAcT failed with code %s"%sw)
1126
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001127 # EF.OPLMNwAcT
1128 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001129 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1130 if sw != '9000':
1131 print("Programming OPLMNwAcT failed with code %s"%sw)
1132
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001133 # EF.AD
1134 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001135 sw = self.update_ad(p['mnc'])
1136 if sw != '9000':
1137 print("Programming AD failed with code %s"%sw)
1138
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001139 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001140
Todd Neal9eeadfc2018-04-25 15:36:29 -05001141
herlesupreethb0c7d122020-12-23 09:25:46 +01001142class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001143 """
1144 sysmocom sysmoISIM-SJA2
1145 """
1146
1147 name = 'sysmoISIM-SJA2'
1148
1149 def __init__(self, ssc):
1150 super(SysmoISIMSJA2, self).__init__(ssc)
1151 self._scc.cla_byte = "00"
1152 self._scc.sel_ctrl = "0004" #request an FCP
1153
1154 @classmethod
1155 def autodetect(kls, scc):
1156 try:
1157 # Try card model #1
1158 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1159 if scc.get_atr() == toBytes(atr):
1160 return kls(scc)
1161
1162 # Try card model #2
1163 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1164 if scc.get_atr() == toBytes(atr):
1165 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001166
1167 # Try card model #3
1168 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1169 if scc.get_atr() == toBytes(atr):
1170 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001171 except:
1172 return None
1173 return None
1174
1175 def program(self, p):
1176 # authenticate as ADM using default key (written on the card..)
1177 if not p['pin_adm']:
1178 raise ValueError("Please provide a PIN-ADM as there is no default one")
1179 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1180
1181 # This type of card does not allow to reprogram the ICCID.
1182 # Reprogramming the ICCID would mess up the card os software
1183 # license management, so the ICCID must be kept at its factory
1184 # setting!
1185 if p.get('iccid'):
1186 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1187
1188 # select DF_GSM
1189 self._scc.select_file(['7f20'])
1190
1191 # write EF.IMSI
1192 if p.get('imsi'):
1193 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1194
1195 # EF.PLMNsel
1196 if p.get('mcc') and p.get('mnc'):
1197 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1198 if sw != '9000':
1199 print("Programming PLMNsel failed with code %s"%sw)
1200
1201 # EF.PLMNwAcT
1202 if p.get('mcc') and p.get('mnc'):
1203 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1204 if sw != '9000':
1205 print("Programming PLMNwAcT failed with code %s"%sw)
1206
1207 # EF.OPLMNwAcT
1208 if p.get('mcc') and p.get('mnc'):
1209 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1210 if sw != '9000':
1211 print("Programming OPLMNwAcT failed with code %s"%sw)
1212
Harald Welte32f0d412020-05-05 17:35:57 +02001213 # EF.HPLMNwAcT
1214 if p.get('mcc') and p.get('mnc'):
1215 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1216 if sw != '9000':
1217 print("Programming HPLMNwAcT failed with code %s"%sw)
1218
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001219 # EF.AD
1220 if p.get('mcc') and p.get('mnc'):
1221 sw = self.update_ad(p['mnc'])
1222 if sw != '9000':
1223 print("Programming AD failed with code %s"%sw)
1224
1225 # EF.SMSP
1226 if p.get('smsp'):
1227 r = self._scc.select_file(['3f00', '7f10'])
1228 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1229
Supreeth Herle80164052020-03-23 12:06:29 +01001230 # Populate AIDs
1231 self.read_aids()
1232
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001233 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1234 # hard linked to EF-USIM_AUTH_KEY)
1235 self._scc.select_file(['3f00'])
1236 self._scc.select_file(['a515'])
1237 if p.get('ki'):
1238 self._scc.update_binary('6f20', p['ki'], 1)
1239 if p.get('opc'):
1240 self._scc.update_binary('6f20', p['opc'], 17)
1241
1242 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001243 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001244 if p.get('ki'):
1245 self._scc.update_binary('af20', p['ki'], 1)
1246 if p.get('opc'):
1247 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001248
Supreeth Herlecf727f22020-03-24 17:32:21 +01001249 # update EF.P-CSCF in ADF.ISIM
1250 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1251 if p.get('pcscf'):
1252 sw = self.update_pcscf(p['pcscf'])
1253 else:
1254 sw = self.update_pcscf("")
1255 if sw != '9000':
1256 print("Programming P-CSCF failed with code %s"%sw)
1257
1258
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001259 # update EF.DOMAIN in ADF.ISIM
1260 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1261 if p.get('ims_hdomain'):
1262 sw = self.update_domain(domain=p['ims_hdomain'])
1263 else:
1264 sw = self.update_domain()
1265
1266 if sw != '9000':
1267 print("Programming Home Network Domain Name failed with code %s"%sw)
1268
herlesupreeth1a13c442020-09-11 21:16:51 +02001269 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001270 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001271 if p.get('ki'):
1272 self._scc.update_binary('af20', p['ki'], 1)
1273 if p.get('opc'):
1274 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001275
Harald Welteca673942020-06-03 15:19:40 +02001276 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001277 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001278 if p.get('mcc') and p.get('mnc'):
1279 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1280 if sw != '9000':
1281 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001282
1283 # update EF.ePDGId in ADF.USIM
1284 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1285 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001286 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001287 if sw != '9000':
1288 print("Programming ePDGId failed with code %s"%sw)
1289
Supreeth Herlef964df42020-03-24 13:15:37 +01001290 # update EF.ePDGSelection in ADF.USIM
1291 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1292 if p.get('epdgSelection'):
1293 epdg_plmn = p['epdgSelection']
1294 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1295 else:
1296 sw = self.update_ePDGSelection("", "")
1297 if sw != '9000':
1298 print("Programming ePDGSelection failed with code %s"%sw)
1299
1300
Supreeth Herleacc222f2020-03-24 13:26:53 +01001301 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1302 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001303 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001304 if self.file_exists(EF_USIM_ADF_map['UST']):
1305 if p.get('epdgSelection') and p.get('epdgid'):
1306 sw = self.update_ust(106, 1)
1307 if sw != '9000':
1308 print("Programming UST failed with code %s"%sw)
1309 sw = self.update_ust(107, 1)
1310 if sw != '9000':
1311 print("Programming UST failed with code %s"%sw)
1312
Supreeth Herle44e04622020-03-25 10:34:28 +01001313 sw = self.update_ust(95, 0)
1314 if sw != '9000':
1315 print("Programming UST failed with code %s"%sw)
1316 sw = self.update_ust(99, 0)
1317 if sw != '9000':
1318 print("Programming UST failed with code %s"%sw)
1319 sw = self.update_ust(115, 0)
1320 if sw != '9000':
1321 print("Programming UST failed with code %s"%sw)
1322
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001323 return
1324
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001325
Todd Neal9eeadfc2018-04-25 15:36:29 -05001326# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001327_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001328 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001329 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001330
1331def card_autodetect(scc):
1332 for kls in _cards_classes:
1333 card = kls.autodetect(scc)
1334 if card is not None:
1335 card.reset()
1336 return card
1337 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001338
1339def card_detect(ctype, scc):
1340 # Detect type if needed
1341 card = None
1342 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1343
1344 if ctype in ("auto", "auto_once"):
1345 for kls in _cards_classes:
1346 card = kls.autodetect(scc)
1347 if card:
1348 print("Autodetected card type: %s" % card.name)
1349 card.reset()
1350 break
1351
1352 if card is None:
1353 print("Autodetection failed")
1354 return None
1355
1356 if ctype == "auto_once":
1357 ctype = card.name
1358
1359 elif ctype in ctypes:
1360 card = ctypes[ctype](scc)
1361
1362 else:
1363 raise ValueError("Unknown card type: %s" % ctype)
1364
1365 return card