blob: 850d084bbd1aa08964f34e0fbad6bba99abc4a52 [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 Herle47790342020-03-25 12:51:38 +0100277 size = self._scc.binary_size(EF_USIM_ADF_map['ePDGId']) * 2
278 if len(epdgid) > 0:
Supreeth Herlec491dc02020-03-25 14:56:13 +0100279 addr_type = get_addr_type(epdgid)
280 if addr_type == None:
281 raise ValueError("Unknown ePDG Id address type or invalid address provided")
282 epdgid_tlv = rpad(enc_addr_tlv(epdgid, ('%02x' % addr_type)), size)
Supreeth Herle47790342020-03-25 12:51:38 +0100283 else:
284 epdgid_tlv = rpad('ff', size)
herlesupreeth5d0a30c2020-09-29 09:44:24 +0200285 data, sw = self._scc.update_binary(
286 EF_USIM_ADF_map['ePDGId'], epdgid_tlv)
287 return sw
Harald Welteca673942020-06-03 15:19:40 +0200288
Supreeth Herle99d55552020-03-24 13:03:43 +0100289 def read_ePDGSelection(self):
290 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'])
291 if sw == '9000':
292 return (format_ePDGSelection(res), sw)
293 else:
294 return (None, sw)
295
Supreeth Herlef964df42020-03-24 13:15:37 +0100296 def update_ePDGSelection(self, mcc, mnc):
297 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['ePDGSelection'], length=None, offset=0)
298 if sw == '9000' and (len(mcc) == 0 or len(mnc) == 0):
299 # Reset contents
300 # 80 - Tag value
301 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], rpad('', len(res)))
302 elif sw == '9000':
303 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['ePDGSelection'], enc_ePDGSelection(res, mcc, mnc))
304 return sw
305
herlesupreeth4a3580b2020-09-29 10:11:36 +0200306 def read_ust(self):
307 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
308 if sw == '9000':
309 # Print those which are available
310 return ([res, dec_st(res, table="usim")], sw)
311 else:
312 return ([None, None], sw)
313
Supreeth Herleacc222f2020-03-24 13:26:53 +0100314 def update_ust(self, service, bit=1):
315 (res, sw) = self._scc.read_binary(EF_USIM_ADF_map['UST'])
316 if sw == '9000':
317 content = enc_st(res, service, bit)
318 (res, sw) = self._scc.update_binary(EF_USIM_ADF_map['UST'], content)
319 return sw
320
herlesupreethecbada92020-12-23 09:24:29 +0100321class IsimCard(Card):
322 def __init__(self, ssc):
323 super(IsimCard, self).__init__(ssc)
324
Supreeth Herle5ad9aec2020-03-24 17:26:40 +0100325 def read_pcscf(self):
326 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['PCSCF'])
327 pcscf_recs = ""
328 for i in range(0, rec_cnt):
329 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['PCSCF'], i + 1)
330 if sw == '9000':
331 content = dec_addr_tlv(res)
332 pcscf_recs += "%s" % (len(content) and content or '\tNot available\n')
333 else:
334 pcscf_recs += "\tP-CSCF: Can't read, response code = %s\n" % (sw)
335 return pcscf_recs
336
Supreeth Herlecf727f22020-03-24 17:32:21 +0100337 def update_pcscf(self, pcscf):
338 if len(pcscf) > 0:
herlesupreeth12790852020-12-24 09:38:42 +0100339 addr_type = get_addr_type(pcscf)
340 if addr_type == None:
341 raise ValueError("Unknown PCSCF address type or invalid address provided")
342 content = enc_addr_tlv(pcscf, ('%02x' % addr_type))
Supreeth Herlecf727f22020-03-24 17:32:21 +0100343 else:
344 # Just the tag value
345 content = '80'
346 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['PCSCF'])
herlesupreeth12790852020-12-24 09:38:42 +0100347 pcscf_tlv = rpad(content, rec_size_bytes*2)
348 data, sw = self._scc.update_record(EF_ISIM_ADF_map['PCSCF'], 1, pcscf_tlv)
Supreeth Herlecf727f22020-03-24 17:32:21 +0100349 return sw
350
Supreeth Herle05b28072020-03-25 10:23:48 +0100351 def read_domain(self):
352 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['DOMAIN'])
353 if sw == '9000':
354 # Skip the inital tag value ('80') byte and get length of contents
355 length = int(res[2:4], 16)
356 content = h2s(res[4:4+(length*2)])
357 return (content, sw)
358 else:
359 return (None, sw)
360
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100361 def update_domain(self, domain=None, mcc=None, mnc=None):
362 hex_str = ""
363 if domain:
364 hex_str = s2h(domain)
365 elif mcc and mnc:
366 # MCC and MNC always has 3 digits in domain form
367 plmn_str = 'mnc' + lpad(mnc, 3, "0") + '.mcc' + lpad(mcc, 3, "0")
368 hex_str = s2h('ims.' + plmn_str + '.3gppnetwork.org')
369
370 # Build TLV
371 tlv = TLV(['80'])
372 content = tlv.build({'80': hex_str})
373
374 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['DOMAIN'])
375 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['DOMAIN'], rpad(content, bin_size_bytes*2))
376 return sw
377
Supreeth Herle3f67f9c2020-03-25 15:38:02 +0100378 def read_impi(self):
379 (res, sw) = self._scc.read_binary(EF_ISIM_ADF_map['IMPI'])
380 if sw == '9000':
381 # Skip the inital tag value ('80') byte and get length of contents
382 length = int(res[2:4], 16)
383 content = h2s(res[4:4+(length*2)])
384 return (content, sw)
385 else:
386 return (None, sw)
387
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100388 def update_impi(self, impi=None):
389 hex_str = ""
390 if impi:
391 hex_str = s2h(impi)
392 # Build TLV
393 tlv = TLV(['80'])
394 content = tlv.build({'80': hex_str})
395
396 bin_size_bytes = self._scc.binary_size(EF_ISIM_ADF_map['IMPI'])
397 data, sw = self._scc.update_binary(EF_ISIM_ADF_map['IMPI'], rpad(content, bin_size_bytes*2))
398 return sw
399
Supreeth Herle0c02d8a2020-03-26 09:00:06 +0100400 def read_impu(self):
401 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['IMPU'])
402 impu_recs = ""
403 for i in range(0, rec_cnt):
404 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['IMPU'], i + 1)
405 if sw == '9000':
406 # Skip the inital tag value ('80') byte and get length of contents
407 length = int(res[2:4], 16)
408 content = h2s(res[4:4+(length*2)])
409 impu_recs += "\t%s\n" % (len(content) and content or 'Not available')
410 else:
411 impu_recs += "IMS public user identity: Can't read, response code = %s\n" % (sw)
412 return impu_recs
413
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100414 def update_impu(self, impu=None):
415 hex_str = ""
416 if impu:
417 hex_str = s2h(impu)
418 # Build TLV
419 tlv = TLV(['80'])
420 content = tlv.build({'80': hex_str})
421
422 rec_size_bytes = self._scc.record_size(EF_ISIM_ADF_map['IMPU'])
423 impu_tlv = rpad(content, rec_size_bytes*2)
424 data, sw = self._scc.update_record(EF_ISIM_ADF_map['IMPU'], 1, impu_tlv)
425 return sw
426
Supreeth Herlebe3b6412020-06-01 12:53:57 +0200427 def read_iari(self):
428 rec_cnt = self._scc.record_count(EF_ISIM_ADF_map['UICCIARI'])
429 uiari_recs = ""
430 for i in range(0, rec_cnt):
431 (res, sw) = self._scc.read_record(EF_ISIM_ADF_map['UICCIARI'], i + 1)
432 if sw == '9000':
433 # Skip the inital tag value ('80') byte and get length of contents
434 length = int(res[2:4], 16)
435 content = h2s(res[4:4+(length*2)])
436 uiari_recs += "\t%s\n" % (len(content) and content or 'Not available')
437 else:
438 uiari_recs += "UICC IARI: Can't read, response code = %s\n" % (sw)
439 return uiari_recs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100440
441class _MagicSimBase(Card):
442 """
443 Theses cards uses several record based EFs to store the provider infos,
444 each possible provider uses a specific record number in each EF. The
445 indexes used are ( where N is the number of providers supported ) :
446 - [2 .. N+1] for the operator name
Supreeth Herle9ca41c12020-01-21 12:50:30 +0100447 - [1 .. N] for the programable EFs
Sylvain Munaut76504e02010-12-07 00:24:32 +0100448
449 * 3f00/7f4d/8f0c : Operator Name
450
451 bytes 0-15 : provider name, padded with 0xff
452 byte 16 : length of the provider name
453 byte 17 : 01 for valid records, 00 otherwise
454
455 * 3f00/7f4d/8f0d : Programmable Binary EFs
456
457 * 3f00/7f4d/8f0e : Programmable Record EFs
458
459 """
460
461 @classmethod
462 def autodetect(kls, scc):
463 try:
464 for p, l, t in kls._files.values():
465 if not t:
466 continue
467 if scc.record_size(['3f00', '7f4d', p]) != l:
468 return None
469 except:
470 return None
471
472 return kls(scc)
473
474 def _get_count(self):
475 """
476 Selects the file and returns the total number of entries
477 and entry size
478 """
479 f = self._files['name']
480
481 r = self._scc.select_file(['3f00', '7f4d', f[0]])
482 rec_len = int(r[-1][28:30], 16)
483 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200484 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100485
486 if (rec_cnt < 1) or (rec_len != f[1]):
487 raise RuntimeError('Bad card type')
488
489 return rec_cnt
490
491 def program(self, p):
492 # Go to dir
493 self._scc.select_file(['3f00', '7f4d'])
494
495 # Home PLMN in PLMN_Sel format
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400496 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100497
498 # Operator name ( 3f00/7f4d/8f0c )
499 self._scc.update_record(self._files['name'][0], 2,
500 rpad(b2h(p['name']), 32) + ('%02x' % len(p['name'])) + '01'
501 )
502
503 # ICCID/IMSI/Ki/HPLMN ( 3f00/7f4d/8f0d )
504 v = ''
505
506 # inline Ki
507 if self._ki_file is None:
508 v += p['ki']
509
510 # ICCID
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400511 v += '3f00' + '2fe2' + '0a' + enc_iccid(p['iccid'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100512
513 # IMSI
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400514 v += '7f20' + '6f07' + '09' + enc_imsi(p['imsi'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100515
516 # Ki
517 if self._ki_file:
518 v += self._ki_file + '10' + p['ki']
519
520 # PLMN_Sel
521 v+= '6f30' + '18' + rpad(hplmn, 36)
522
Alexander Chemeris21885242013-07-02 16:56:55 +0400523 # ACC
524 # This doesn't work with "fake" SuperSIM cards,
525 # but will hopefully work with real SuperSIMs.
526 if p.get('acc') is not None:
527 v+= '6f78' + '02' + lpad(p['acc'], 4)
528
Sylvain Munaut76504e02010-12-07 00:24:32 +0100529 self._scc.update_record(self._files['b_ef'][0], 1,
530 rpad(v, self._files['b_ef'][1]*2)
531 )
532
533 # SMSP ( 3f00/7f4d/8f0e )
534 # FIXME
535
536 # Write PLMN_Sel forcefully as well
537 r = self._scc.select_file(['3f00', '7f20', '6f30'])
538 tl = int(r[-1][4:8], 16)
539
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400540 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100541 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
542
543 def erase(self):
544 # Dummy
545 df = {}
546 for k, v in self._files.iteritems():
547 ofs = 1
548 fv = v[1] * 'ff'
549 if k == 'name':
550 ofs = 2
551 fv = fv[0:-4] + '0000'
552 df[v[0]] = (fv, ofs)
553
554 # Write
555 for n in range(0,self._get_count()):
556 for k, (msg, ofs) in df.iteritems():
557 self._scc.update_record(['3f00', '7f4d', k], n + ofs, msg)
558
559
560class SuperSim(_MagicSimBase):
561
562 name = 'supersim'
563
564 _files = {
565 'name' : ('8f0c', 18, True),
566 'b_ef' : ('8f0d', 74, True),
567 'r_ef' : ('8f0e', 50, True),
568 }
569
570 _ki_file = None
571
572
573class MagicSim(_MagicSimBase):
574
575 name = 'magicsim'
576
577 _files = {
578 'name' : ('8f0c', 18, True),
579 'b_ef' : ('8f0d', 130, True),
580 'r_ef' : ('8f0e', 102, False),
581 }
582
583 _ki_file = '6f1b'
584
585
586class FakeMagicSim(Card):
587 """
588 Theses cards have a record based EF 3f00/000c that contains the provider
589 informations. See the program method for its format. The records go from
590 1 to N.
591 """
592
593 name = 'fakemagicsim'
594
595 @classmethod
596 def autodetect(kls, scc):
597 try:
598 if scc.record_size(['3f00', '000c']) != 0x5a:
599 return None
600 except:
601 return None
602
603 return kls(scc)
604
605 def _get_infos(self):
606 """
607 Selects the file and returns the total number of entries
608 and entry size
609 """
610
611 r = self._scc.select_file(['3f00', '000c'])
612 rec_len = int(r[-1][28:30], 16)
613 tlen = int(r[-1][4:8],16)
Daniel Willmann677d41b2020-10-19 10:34:31 +0200614 rec_cnt = (tlen / rec_len) - 1
Sylvain Munaut76504e02010-12-07 00:24:32 +0100615
616 if (rec_cnt < 1) or (rec_len != 0x5a):
617 raise RuntimeError('Bad card type')
618
619 return rec_cnt, rec_len
620
621 def program(self, p):
622 # Home PLMN
623 r = self._scc.select_file(['3f00', '7f20', '6f30'])
624 tl = int(r[-1][4:8], 16)
625
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400626 hplmn = enc_plmn(p['mcc'], p['mnc'])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100627 self._scc.update_binary('6f30', hplmn + 'ff' * (tl-3))
628
629 # Get total number of entries and entry size
630 rec_cnt, rec_len = self._get_infos()
631
632 # Set first entry
633 entry = (
Philipp Maier45daa922019-04-01 15:49:45 +0200634 '81' + # 1b Status: Valid & Active
Sylvain Munaut76504e02010-12-07 00:24:32 +0100635 rpad(b2h(p['name'][0:14]), 28) + # 14b Entry Name
Philipp Maier45daa922019-04-01 15:49:45 +0200636 enc_iccid(p['iccid']) + # 10b ICCID
637 enc_imsi(p['imsi']) + # 9b IMSI_len + id_type(9) + IMSI
638 p['ki'] + # 16b Ki
639 lpad(p['smsp'], 80) # 40b SMSP (padded with ff if needed)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100640 )
641 self._scc.update_record('000c', 1, entry)
642
643 def erase(self):
644 # Get total number of entries and entry size
645 rec_cnt, rec_len = self._get_infos()
646
647 # Erase all entries
648 entry = 'ff' * rec_len
649 for i in range(0, rec_cnt):
650 self._scc.update_record('000c', 1+i, entry)
651
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200652
Harald Welte3156d902011-03-22 21:48:19 +0100653class GrcardSim(Card):
654 """
655 Greencard (grcard.cn) HZCOS GSM SIM
656 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
657 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
658 """
659
660 name = 'grcardsim'
661
662 @classmethod
663 def autodetect(kls, scc):
664 return None
665
666 def program(self, p):
667 # We don't really know yet what ADM PIN 4 is about
668 #self._scc.verify_chv(4, h2b("4444444444444444"))
669
670 # Authenticate using ADM PIN 5
Jan Balkec3ebd332015-01-26 12:22:55 +0100671 if p['pin_adm']:
Philipp Maiera3de5a32018-08-23 10:27:04 +0200672 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100673 else:
674 pin = h2b("4444444444444444")
675 self._scc.verify_chv(5, pin)
Harald Welte3156d902011-03-22 21:48:19 +0100676
677 # EF.ICCID
678 r = self._scc.select_file(['3f00', '2fe2'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400679 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
Harald Welte3156d902011-03-22 21:48:19 +0100680
681 # EF.IMSI
682 r = self._scc.select_file(['3f00', '7f20', '6f07'])
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400683 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
Harald Welte3156d902011-03-22 21:48:19 +0100684
685 # EF.ACC
Alexander Chemeris21885242013-07-02 16:56:55 +0400686 if p.get('acc') is not None:
687 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
Harald Welte3156d902011-03-22 21:48:19 +0100688
689 # EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200690 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200691 r = self._scc.select_file(['3f00', '7f10', '6f42'])
692 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Harald Welte3156d902011-03-22 21:48:19 +0100693
694 # Set the Ki using proprietary command
695 pdu = '80d4020010' + p['ki']
696 data, sw = self._scc._tp.send_apdu(pdu)
697
698 # EF.HPLMN
699 r = self._scc.select_file(['3f00', '7f20', '6f30'])
700 size = int(r[-1][4:8], 16)
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400701 hplmn = enc_plmn(p['mcc'], p['mnc'])
Harald Welte3156d902011-03-22 21:48:19 +0100702 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
703
704 # EF.SPN (Service Provider Name)
705 r = self._scc.select_file(['3f00', '7f20', '6f30'])
706 size = int(r[-1][4:8], 16)
707 # FIXME
708
709 # FIXME: EF.MSISDN
710
Sylvain Munaut76504e02010-12-07 00:24:32 +0100711
Harald Weltee10394b2011-12-07 12:34:14 +0100712class SysmoSIMgr1(GrcardSim):
713 """
714 sysmocom sysmoSIM-GR1
715 These cards have a much more regular ISO 7816-4 / TS 11.11 structure,
716 and use standard UPDATE RECORD / UPDATE BINARY commands except for Ki.
717 """
718 name = 'sysmosim-gr1'
719
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200720 @classmethod
Philipp Maier087feff2018-08-23 09:41:36 +0200721 def autodetect(kls, scc):
722 try:
723 # Look for ATR
724 if scc.get_atr() == toBytes("3B 99 18 00 11 88 22 33 44 55 66 77 60"):
725 return kls(scc)
726 except:
727 return None
728 return None
Sylvain Munaut5da8d4e2013-07-02 15:13:24 +0200729
Harald Welteca673942020-06-03 15:19:40 +0200730class SysmoUSIMgr1(UsimCard):
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100731 """
732 sysmocom sysmoUSIM-GR1
733 """
734 name = 'sysmoUSIM-GR1'
735
736 @classmethod
737 def autodetect(kls, scc):
738 # TODO: Access the ATR
739 return None
740
741 def program(self, p):
742 # TODO: check if verify_chv could be used or what it needs
743 # self._scc.verify_chv(0x0A, [0x33,0x32,0x32,0x31,0x33,0x32,0x33,0x32])
744 # Unlock the card..
745 data, sw = self._scc._tp.send_apdu_checksw("0020000A083332323133323332")
746
747 # TODO: move into SimCardCommands
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100748 par = ( p['ki'] + # 16b K
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400749 p['opc'] + # 32b OPC
750 enc_iccid(p['iccid']) + # 10b ICCID
751 enc_imsi(p['imsi']) # 9b IMSI_len + id_type(9) + IMSI
Holger Hans Peter Freyther4d91bf42012-03-22 14:28:38 +0100752 )
753 data, sw = self._scc._tp.send_apdu_checksw("0099000033" + par)
754
Sylvain Munaut053c8952013-07-02 15:12:32 +0200755
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100756class SysmoSIMgr2(Card):
757 """
758 sysmocom sysmoSIM-GR2
759 """
760
761 name = 'sysmoSIM-GR2'
762
763 @classmethod
764 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900765 try:
766 # Look for ATR
767 if scc.get_atr() == toBytes("3B 7D 94 00 00 55 55 53 0A 74 86 93 0B 24 7C 4D 54 68"):
768 return kls(scc)
769 except:
770 return None
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100771 return None
772
773 def program(self, p):
774
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200775 # select MF
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100776 r = self._scc.select_file(['3f00'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200777
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100778 # authenticate as SUPER ADM using default key
779 self._scc.verify_chv(0x0b, h2b("3838383838383838"))
780
781 # set ADM pin using proprietary command
782 # INS: D4
783 # P1: 3A for PIN, 3B for PUK
784 # P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
785 # P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
Jan Balkec3ebd332015-01-26 12:22:55 +0100786 if p['pin_adm']:
Daniel Willmann7d38d742018-06-15 07:31:50 +0200787 pin = h2b(p['pin_adm'])
Jan Balkec3ebd332015-01-26 12:22:55 +0100788 else:
789 pin = h2b("4444444444444444")
790
791 pdu = 'A0D43A0508' + b2h(pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100792 data, sw = self._scc._tp.send_apdu(pdu)
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200793
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100794 # authenticate as ADM (enough to write file, and can set PINs)
Jan Balkec3ebd332015-01-26 12:22:55 +0100795
796 self._scc.verify_chv(0x05, pin)
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100797
798 # write EF.ICCID
799 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
800
801 # select DF_GSM
802 r = self._scc.select_file(['7f20'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200803
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100804 # write EF.IMSI
805 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
806
807 # write EF.ACC
808 if p.get('acc') is not None:
809 data, sw = self._scc.update_binary('6f78', lpad(p['acc'], 4))
810
811 # get size and write EF.HPLMN
812 r = self._scc.select_file(['6f30'])
813 size = int(r[-1][4:8], 16)
814 hplmn = enc_plmn(p['mcc'], p['mnc'])
815 self._scc.update_binary('6f30', hplmn + 'ff' * (size-3))
816
817 # set COMP128 version 0 in proprietary file
818 data, sw = self._scc.update_binary('0001', '001000')
819
820 # set Ki in proprietary file
821 data, sw = self._scc.update_binary('0001', p['ki'], 3)
822
823 # select DF_TELECOM
824 r = self._scc.select_file(['3f00', '7f10'])
Daniel Willmann5d8cd9b2020-10-19 11:01:49 +0200825
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100826 # write EF.SMSP
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200827 if p.get('smsp'):
Harald Welte23888da2019-08-28 23:19:11 +0200828 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 80))
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100829
Sylvain Munaut2fc205c2013-12-23 17:22:56 +0100830
Harald Welteca673942020-06-03 15:19:40 +0200831class SysmoUSIMSJS1(UsimCard):
Jan Balke3e840672015-01-26 15:36:27 +0100832 """
833 sysmocom sysmoUSIM-SJS1
834 """
835
836 name = 'sysmoUSIM-SJS1'
837
838 def __init__(self, ssc):
839 super(SysmoUSIMSJS1, self).__init__(ssc)
840 self._scc.cla_byte = "00"
Philipp Maier2d15ea02019-03-20 12:40:36 +0100841 self._scc.sel_ctrl = "0004" #request an FCP
Jan Balke3e840672015-01-26 15:36:27 +0100842
843 @classmethod
844 def autodetect(kls, scc):
Alexander Chemeris8ad124a2018-01-10 14:17:55 +0900845 try:
846 # Look for ATR
847 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"):
848 return kls(scc)
849 except:
850 return None
Jan Balke3e840672015-01-26 15:36:27 +0100851 return None
852
853 def program(self, p):
854
Philipp Maiere9604882017-03-21 17:24:31 +0100855 # authenticate as ADM using default key (written on the card..)
856 if not p['pin_adm']:
857 raise ValueError("Please provide a PIN-ADM as there is no default one")
858 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
Jan Balke3e840672015-01-26 15:36:27 +0100859
860 # select MF
861 r = self._scc.select_file(['3f00'])
862
Philipp Maiere9604882017-03-21 17:24:31 +0100863 # write EF.ICCID
864 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
865
Jan Balke3e840672015-01-26 15:36:27 +0100866 # select DF_GSM
867 r = self._scc.select_file(['7f20'])
868
Jan Balke3e840672015-01-26 15:36:27 +0100869 # set Ki in proprietary file
870 data, sw = self._scc.update_binary('00FF', p['ki'])
871
Philipp Maier1be35bf2018-07-13 11:29:03 +0200872 # set OPc in proprietary file
Daniel Willmann67acdbc2018-06-15 07:42:48 +0200873 if 'opc' in p:
874 content = "01" + p['opc']
875 data, sw = self._scc.update_binary('00F7', content)
Jan Balke3e840672015-01-26 15:36:27 +0100876
Supreeth Herle7947d922019-06-08 07:50:53 +0200877 # set Service Provider Name
Supreeth Herle840a9e22020-01-21 13:32:46 +0100878 if p.get('name') is not None:
879 content = enc_spn(p['name'], True, True)
880 data, sw = self._scc.update_binary('6F46', rpad(content, 32))
Supreeth Herle7947d922019-06-08 07:50:53 +0200881
Supreeth Herlec8796a32019-12-23 12:23:42 +0100882 if p.get('acc') is not None:
883 self.update_acc(p['acc'])
884
Jan Balke3e840672015-01-26 15:36:27 +0100885 # write EF.IMSI
886 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
887
Philipp Maier2d15ea02019-03-20 12:40:36 +0100888 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200889 if p.get('mcc') and p.get('mnc'):
890 sw = self.update_plmnsel(p['mcc'], p['mnc'])
891 if sw != '9000':
Philipp Maier2d15ea02019-03-20 12:40:36 +0100892 print("Programming PLMNsel failed with code %s"%sw)
893
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200894 # EF.PLMNwAcT
895 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100896 sw = self.update_plmn_act(p['mcc'], p['mnc'])
897 if sw != '9000':
898 print("Programming PLMNwAcT failed with code %s"%sw)
899
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200900 # EF.OPLMNwAcT
901 if p.get('mcc') and p.get('mnc'):
Philipp Maier2d15ea02019-03-20 12:40:36 +0100902 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
903 if sw != '9000':
904 print("Programming OPLMNwAcT failed with code %s"%sw)
905
Supreeth Herlef442fb42020-01-21 12:47:32 +0100906 # EF.HPLMNwAcT
907 if p.get('mcc') and p.get('mnc'):
908 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
909 if sw != '9000':
910 print("Programming HPLMNwAcT failed with code %s"%sw)
911
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200912 # EF.AD
913 if p.get('mcc') and p.get('mnc'):
Philipp Maieree908ae2019-03-21 16:21:12 +0100914 sw = self.update_ad(p['mnc'])
915 if sw != '9000':
916 print("Programming AD failed with code %s"%sw)
Philipp Maier2d15ea02019-03-20 12:40:36 +0100917
Daniel Willmann1d087ef2017-08-31 10:08:45 +0200918 # EF.SMSP
Harald Welte23888da2019-08-28 23:19:11 +0200919 if p.get('smsp'):
920 r = self._scc.select_file(['3f00', '7f10'])
921 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
Jan Balke3e840672015-01-26 15:36:27 +0100922
Supreeth Herle5a541012019-12-22 08:59:16 +0100923 # EF.MSISDN
924 # TODO: Alpha Identifier (currently 'ff'O * 20)
925 # TODO: Capability/Configuration1 Record Identifier
926 # TODO: Extension1 Record Identifier
927 if p.get('msisdn') is not None:
928 msisdn = enc_msisdn(p['msisdn'])
929 data = 'ff' * 20 + msisdn + 'ff' * 2
930
931 r = self._scc.select_file(['3f00', '7f10'])
932 data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
933
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900934
herlesupreeth4a3580b2020-09-29 10:11:36 +0200935class FairwavesSIM(UsimCard):
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900936 """
937 FairwavesSIM
938
939 The SIM card is operating according to the standard.
940 For Ki/OP/OPC programming the following files are additionally open for writing:
941 3F00/7F20/FF01 – OP/OPC:
942 byte 1 = 0x01, bytes 2-17: OPC;
943 byte 1 = 0x00, bytes 2-17: OP;
944 3F00/7F20/FF02: Ki
945 """
946
Philipp Maier5a876312019-11-11 11:01:46 +0100947 name = 'Fairwaves-SIM'
Alexander Chemerise0d9d882018-01-10 14:18:32 +0900948 # Propriatary files
949 _EF_num = {
950 'Ki': 'FF02',
951 'OP/OPC': 'FF01',
952 }
953 _EF = {
954 'Ki': DF['GSM']+[_EF_num['Ki']],
955 'OP/OPC': DF['GSM']+[_EF_num['OP/OPC']],
956 }
957
958 def __init__(self, ssc):
959 super(FairwavesSIM, self).__init__(ssc)
960 self._adm_chv_num = 0x11
961 self._adm2_chv_num = 0x12
962
963
964 @classmethod
965 def autodetect(kls, scc):
966 try:
967 # Look for ATR
968 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"):
969 return kls(scc)
970 except:
971 return None
972 return None
973
974
975 def verify_adm2(self, key):
976 '''
977 Authenticate with ADM2 key.
978
979 Fairwaves SIM cards support hierarchical key structure and ADM2 key
980 is a key which has access to proprietary files (Ki and OP/OPC).
981 That said, ADM key inherits permissions of ADM2 key and thus we rarely
982 need ADM2 key per se.
983 '''
984 (res, sw) = self._scc.verify_chv(self._adm2_chv_num, key)
985 return sw
986
987
988 def read_ki(self):
989 """
990 Read Ki in proprietary file.
991
992 Requires ADM1 access level
993 """
994 return self._scc.read_binary(self._EF['Ki'])
995
996
997 def update_ki(self, ki):
998 """
999 Set Ki in proprietary file.
1000
1001 Requires ADM1 access level
1002 """
1003 data, sw = self._scc.update_binary(self._EF['Ki'], ki)
1004 return sw
1005
1006
1007 def read_op_opc(self):
1008 """
1009 Read Ki in proprietary file.
1010
1011 Requires ADM1 access level
1012 """
1013 (ef, sw) = self._scc.read_binary(self._EF['OP/OPC'])
1014 type = 'OP' if ef[0:2] == '00' else 'OPC'
1015 return ((type, ef[2:]), sw)
1016
1017
1018 def update_op(self, op):
1019 """
1020 Set OP in proprietary file.
1021
1022 Requires ADM1 access level
1023 """
1024 content = '00' + op
1025 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1026 return sw
1027
1028
1029 def update_opc(self, opc):
1030 """
1031 Set OPC in proprietary file.
1032
1033 Requires ADM1 access level
1034 """
1035 content = '01' + opc
1036 data, sw = self._scc.update_binary(self._EF['OP/OPC'], content)
1037 return sw
1038
1039
1040 def program(self, p):
1041 # authenticate as ADM1
1042 if not p['pin_adm']:
1043 raise ValueError("Please provide a PIN-ADM as there is no default one")
1044 sw = self.verify_adm(h2b(p['pin_adm']))
1045 if sw != '9000':
1046 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1047
1048 # TODO: Set operator name
1049 if p.get('smsp') is not None:
1050 sw = self.update_smsp(p['smsp'])
1051 if sw != '9000':
1052 print("Programming SMSP failed with code %s"%sw)
1053 # This SIM doesn't support changing ICCID
1054 if p.get('mcc') is not None and p.get('mnc') is not None:
1055 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1056 if sw != '9000':
1057 print("Programming MCC/MNC failed with code %s"%sw)
1058 if p.get('imsi') is not None:
1059 sw = self.update_imsi(p['imsi'])
1060 if sw != '9000':
1061 print("Programming IMSI failed with code %s"%sw)
1062 if p.get('ki') is not None:
1063 sw = self.update_ki(p['ki'])
1064 if sw != '9000':
1065 print("Programming Ki failed with code %s"%sw)
1066 if p.get('opc') is not None:
1067 sw = self.update_opc(p['opc'])
1068 if sw != '9000':
1069 print("Programming OPC failed with code %s"%sw)
1070 if p.get('acc') is not None:
1071 sw = self.update_acc(p['acc'])
1072 if sw != '9000':
1073 print("Programming ACC failed with code %s"%sw)
Jan Balke3e840672015-01-26 15:36:27 +01001074
Todd Neal9eeadfc2018-04-25 15:36:29 -05001075class OpenCellsSim(Card):
1076 """
1077 OpenCellsSim
1078
1079 """
1080
Philipp Maier5a876312019-11-11 11:01:46 +01001081 name = 'OpenCells-SIM'
Todd Neal9eeadfc2018-04-25 15:36:29 -05001082
1083 def __init__(self, ssc):
1084 super(OpenCellsSim, self).__init__(ssc)
1085 self._adm_chv_num = 0x0A
1086
1087
1088 @classmethod
1089 def autodetect(kls, scc):
1090 try:
1091 # Look for ATR
1092 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"):
1093 return kls(scc)
1094 except:
1095 return None
1096 return None
1097
1098
1099 def program(self, p):
1100 if not p['pin_adm']:
1101 raise ValueError("Please provide a PIN-ADM as there is no default one")
1102 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1103
1104 # select MF
1105 r = self._scc.select_file(['3f00'])
1106
1107 # write EF.ICCID
1108 data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
1109
1110 r = self._scc.select_file(['7ff0'])
1111
1112 # set Ki in proprietary file
1113 data, sw = self._scc.update_binary('FF02', p['ki'])
1114
1115 # set OPC in proprietary file
1116 data, sw = self._scc.update_binary('FF01', p['opc'])
1117
1118 # select DF_GSM
1119 r = self._scc.select_file(['7f20'])
1120
1121 # write EF.IMSI
1122 data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1123
herlesupreeth4a3580b2020-09-29 10:11:36 +02001124class WavemobileSim(UsimCard):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001125 """
1126 WavemobileSim
1127
1128 """
1129
1130 name = 'Wavemobile-SIM'
1131
1132 def __init__(self, ssc):
1133 super(WavemobileSim, self).__init__(ssc)
1134 self._adm_chv_num = 0x0A
1135 self._scc.cla_byte = "00"
1136 self._scc.sel_ctrl = "0004" #request an FCP
1137
1138 @classmethod
1139 def autodetect(kls, scc):
1140 try:
1141 # Look for ATR
1142 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"):
1143 return kls(scc)
1144 except:
1145 return None
1146 return None
1147
1148 def program(self, p):
1149 if not p['pin_adm']:
1150 raise ValueError("Please provide a PIN-ADM as there is no default one")
1151 sw = self.verify_adm(h2b(p['pin_adm']))
1152 if sw != '9000':
1153 raise RuntimeError('Failed to authenticate with ADM key %s'%(p['pin_adm'],))
1154
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001155 # EF.ICCID
1156 # TODO: Add programming of the ICCID
1157 if p.get('iccid'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001158 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1159
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001160 # KI (Presumably a propritary file)
1161 # TODO: Add programming of KI
1162 if p.get('ki'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001163 print("Warning: Programming of the KI is not implemented for this type of card.")
1164
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001165 # OPc (Presumably a propritary file)
1166 # TODO: Add programming of OPc
1167 if p.get('opc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001168 print("Warning: Programming of the OPc is not implemented for this type of card.")
1169
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001170 # EF.SMSP
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001171 if p.get('smsp'):
1172 sw = self.update_smsp(p['smsp'])
1173 if sw != '9000':
1174 print("Programming SMSP failed with code %s"%sw)
1175
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001176 # EF.IMSI
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001177 if p.get('imsi'):
1178 sw = self.update_imsi(p['imsi'])
1179 if sw != '9000':
1180 print("Programming IMSI failed with code %s"%sw)
1181
1182 # EF.ACC
1183 if p.get('acc'):
1184 sw = self.update_acc(p['acc'])
1185 if sw != '9000':
1186 print("Programming ACC failed with code %s"%sw)
1187
1188 # EF.PLMNsel
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001189 if p.get('mcc') and p.get('mnc'):
1190 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1191 if sw != '9000':
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001192 print("Programming PLMNsel failed with code %s"%sw)
1193
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001194 # EF.PLMNwAcT
1195 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001196 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1197 if sw != '9000':
1198 print("Programming PLMNwAcT failed with code %s"%sw)
1199
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001200 # EF.OPLMNwAcT
1201 if p.get('mcc') and p.get('mnc'):
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001202 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1203 if sw != '9000':
1204 print("Programming OPLMNwAcT failed with code %s"%sw)
1205
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001206 # EF.AD
1207 if p.get('mcc') and p.get('mnc'):
Philipp Maier6e507a72019-04-01 16:33:48 +02001208 sw = self.update_ad(p['mnc'])
1209 if sw != '9000':
1210 print("Programming AD failed with code %s"%sw)
1211
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +02001212 return None
Philipp Maierc8ce82a2018-07-04 17:57:20 +02001213
Todd Neal9eeadfc2018-04-25 15:36:29 -05001214
herlesupreethb0c7d122020-12-23 09:25:46 +01001215class SysmoISIMSJA2(UsimCard, IsimCard):
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001216 """
1217 sysmocom sysmoISIM-SJA2
1218 """
1219
1220 name = 'sysmoISIM-SJA2'
1221
1222 def __init__(self, ssc):
1223 super(SysmoISIMSJA2, self).__init__(ssc)
1224 self._scc.cla_byte = "00"
1225 self._scc.sel_ctrl = "0004" #request an FCP
1226
1227 @classmethod
1228 def autodetect(kls, scc):
1229 try:
1230 # Try card model #1
1231 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 30 34 05 4B A9"
1232 if scc.get_atr() == toBytes(atr):
1233 return kls(scc)
1234
1235 # Try card model #2
1236 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 75 31 33 02 51 B2"
1237 if scc.get_atr() == toBytes(atr):
1238 return kls(scc)
Philipp Maierb3e11ea2020-03-11 12:32:44 +01001239
1240 # Try card model #3
1241 atr = "3B 9F 96 80 1F 87 80 31 E0 73 FE 21 1B 67 4A 4C 52 75 31 04 51 D5"
1242 if scc.get_atr() == toBytes(atr):
1243 return kls(scc)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001244 except:
1245 return None
1246 return None
1247
1248 def program(self, p):
1249 # authenticate as ADM using default key (written on the card..)
1250 if not p['pin_adm']:
1251 raise ValueError("Please provide a PIN-ADM as there is no default one")
1252 self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
1253
1254 # This type of card does not allow to reprogram the ICCID.
1255 # Reprogramming the ICCID would mess up the card os software
1256 # license management, so the ICCID must be kept at its factory
1257 # setting!
1258 if p.get('iccid'):
1259 print("Warning: Programming of the ICCID is not implemented for this type of card.")
1260
1261 # select DF_GSM
1262 self._scc.select_file(['7f20'])
1263
1264 # write EF.IMSI
1265 if p.get('imsi'):
1266 self._scc.update_binary('6f07', enc_imsi(p['imsi']))
1267
1268 # EF.PLMNsel
1269 if p.get('mcc') and p.get('mnc'):
1270 sw = self.update_plmnsel(p['mcc'], p['mnc'])
1271 if sw != '9000':
1272 print("Programming PLMNsel failed with code %s"%sw)
1273
1274 # EF.PLMNwAcT
1275 if p.get('mcc') and p.get('mnc'):
1276 sw = self.update_plmn_act(p['mcc'], p['mnc'])
1277 if sw != '9000':
1278 print("Programming PLMNwAcT failed with code %s"%sw)
1279
1280 # EF.OPLMNwAcT
1281 if p.get('mcc') and p.get('mnc'):
1282 sw = self.update_oplmn_act(p['mcc'], p['mnc'])
1283 if sw != '9000':
1284 print("Programming OPLMNwAcT failed with code %s"%sw)
1285
Harald Welte32f0d412020-05-05 17:35:57 +02001286 # EF.HPLMNwAcT
1287 if p.get('mcc') and p.get('mnc'):
1288 sw = self.update_hplmn_act(p['mcc'], p['mnc'])
1289 if sw != '9000':
1290 print("Programming HPLMNwAcT failed with code %s"%sw)
1291
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001292 # EF.AD
1293 if p.get('mcc') and p.get('mnc'):
1294 sw = self.update_ad(p['mnc'])
1295 if sw != '9000':
1296 print("Programming AD failed with code %s"%sw)
1297
1298 # EF.SMSP
1299 if p.get('smsp'):
1300 r = self._scc.select_file(['3f00', '7f10'])
1301 data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
1302
Supreeth Herlec6019232020-03-26 10:00:45 +01001303 # EF.MSISDN
1304 # TODO: Alpha Identifier (currently 'ff'O * 20)
1305 # TODO: Capability/Configuration1 Record Identifier
1306 # TODO: Extension1 Record Identifier
1307 if p.get('msisdn') is not None:
1308 msisdn = enc_msisdn(p['msisdn'])
1309 content = 'ff' * 20 + msisdn + 'ff' * 2
1310
1311 r = self._scc.select_file(['3f00', '7f10'])
1312 data, sw = self._scc.update_record('6F40', 1, content, force_len=True)
1313
Supreeth Herlea97944b2020-03-26 10:03:25 +01001314 # EF.ACC
1315 if p.get('acc'):
1316 sw = self.update_acc(p['acc'])
1317 if sw != '9000':
1318 print("Programming ACC failed with code %s"%sw)
1319
Supreeth Herle80164052020-03-23 12:06:29 +01001320 # Populate AIDs
1321 self.read_aids()
1322
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001323 # update EF-SIM_AUTH_KEY (and EF-USIM_AUTH_KEY_2G, which is
1324 # hard linked to EF-USIM_AUTH_KEY)
1325 self._scc.select_file(['3f00'])
1326 self._scc.select_file(['a515'])
1327 if p.get('ki'):
1328 self._scc.update_binary('6f20', p['ki'], 1)
1329 if p.get('opc'):
1330 self._scc.update_binary('6f20', p['opc'], 17)
1331
1332 # update EF-USIM_AUTH_KEY in ADF.ISIM
herlesupreeth1a13c442020-09-11 21:16:51 +02001333 if '9000' == self.select_adf_by_aid(adf="isim"):
Philipp Maierd9507862020-03-11 12:18:29 +01001334 if p.get('ki'):
1335 self._scc.update_binary('af20', p['ki'], 1)
1336 if p.get('opc'):
1337 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001338
Supreeth Herlecf727f22020-03-24 17:32:21 +01001339 # update EF.P-CSCF in ADF.ISIM
1340 if self.file_exists(EF_ISIM_ADF_map['PCSCF']):
1341 if p.get('pcscf'):
1342 sw = self.update_pcscf(p['pcscf'])
1343 else:
1344 sw = self.update_pcscf("")
1345 if sw != '9000':
1346 print("Programming P-CSCF failed with code %s"%sw)
1347
1348
Supreeth Herle79f43dd2020-03-25 11:43:19 +01001349 # update EF.DOMAIN in ADF.ISIM
1350 if self.file_exists(EF_ISIM_ADF_map['DOMAIN']):
1351 if p.get('ims_hdomain'):
1352 sw = self.update_domain(domain=p['ims_hdomain'])
1353 else:
1354 sw = self.update_domain()
1355
1356 if sw != '9000':
1357 print("Programming Home Network Domain Name failed with code %s"%sw)
1358
Supreeth Herlea5bd9682020-03-26 09:16:14 +01001359 # update EF.IMPI in ADF.ISIM
1360 # TODO: Validate IMPI input
1361 if self.file_exists(EF_ISIM_ADF_map['IMPI']):
1362 if p.get('impi'):
1363 sw = self.update_impi(p['impi'])
1364 else:
1365 sw = self.update_impi()
1366 if sw != '9000':
1367 print("Programming IMPI failed with code %s"%sw)
1368
Supreeth Herlebe7007e2020-03-26 09:27:45 +01001369 # update EF.IMPU in ADF.ISIM
1370 # TODO: Validate IMPU input
1371 # Support multiple IMPU if there is enough space
1372 if self.file_exists(EF_ISIM_ADF_map['IMPU']):
1373 if p.get('impu'):
1374 sw = self.update_impu(p['impu'])
1375 else:
1376 sw = self.update_impu()
1377 if sw != '9000':
1378 print("Programming IMPU failed with code %s"%sw)
1379
herlesupreeth1a13c442020-09-11 21:16:51 +02001380 if '9000' == self.select_adf_by_aid():
Harald Welteca673942020-06-03 15:19:40 +02001381 # update EF-USIM_AUTH_KEY in ADF.USIM
Philipp Maierd9507862020-03-11 12:18:29 +01001382 if p.get('ki'):
1383 self._scc.update_binary('af20', p['ki'], 1)
1384 if p.get('opc'):
1385 self._scc.update_binary('af20', p['opc'], 17)
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001386
Harald Welteca673942020-06-03 15:19:40 +02001387 # update EF.EHPLMN in ADF.USIM
Harald Welte1e424202020-08-31 15:04:19 +02001388 if self.file_exists(EF_USIM_ADF_map['EHPLMN']):
Harald Welteca673942020-06-03 15:19:40 +02001389 if p.get('mcc') and p.get('mnc'):
1390 sw = self.update_ehplmn(p['mcc'], p['mnc'])
1391 if sw != '9000':
1392 print("Programming EHPLMN failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001393
1394 # update EF.ePDGId in ADF.USIM
1395 if self.file_exists(EF_USIM_ADF_map['ePDGId']):
1396 if p.get('epdgid'):
herlesupreeth5d0a30c2020-09-29 09:44:24 +02001397 sw = self.update_epdgid(p['epdgid'])
Supreeth Herle47790342020-03-25 12:51:38 +01001398 else:
1399 sw = self.update_epdgid("")
1400 if sw != '9000':
1401 print("Programming ePDGId failed with code %s"%sw)
Supreeth Herle8e0fccd2020-03-23 12:10:56 +01001402
Supreeth Herlef964df42020-03-24 13:15:37 +01001403 # update EF.ePDGSelection in ADF.USIM
1404 if self.file_exists(EF_USIM_ADF_map['ePDGSelection']):
1405 if p.get('epdgSelection'):
1406 epdg_plmn = p['epdgSelection']
1407 sw = self.update_ePDGSelection(epdg_plmn[:3], epdg_plmn[3:])
1408 else:
1409 sw = self.update_ePDGSelection("", "")
1410 if sw != '9000':
1411 print("Programming ePDGSelection failed with code %s"%sw)
1412
1413
Supreeth Herleacc222f2020-03-24 13:26:53 +01001414 # After successfully programming EF.ePDGId and EF.ePDGSelection,
1415 # Set service 106 and 107 as available in EF.UST
Supreeth Herle44e04622020-03-25 10:34:28 +01001416 # Disable service 95, 99, 115 if ISIM application is present
Supreeth Herleacc222f2020-03-24 13:26:53 +01001417 if self.file_exists(EF_USIM_ADF_map['UST']):
1418 if p.get('epdgSelection') and p.get('epdgid'):
1419 sw = self.update_ust(106, 1)
1420 if sw != '9000':
1421 print("Programming UST failed with code %s"%sw)
1422 sw = self.update_ust(107, 1)
1423 if sw != '9000':
1424 print("Programming UST failed with code %s"%sw)
1425
Supreeth Herle44e04622020-03-25 10:34:28 +01001426 sw = self.update_ust(95, 0)
1427 if sw != '9000':
1428 print("Programming UST failed with code %s"%sw)
1429 sw = self.update_ust(99, 0)
1430 if sw != '9000':
1431 print("Programming UST failed with code %s"%sw)
1432 sw = self.update_ust(115, 0)
1433 if sw != '9000':
1434 print("Programming UST failed with code %s"%sw)
1435
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001436 return
1437
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001438
Todd Neal9eeadfc2018-04-25 15:36:29 -05001439# In order for autodetection ...
Harald Weltee10394b2011-12-07 12:34:14 +01001440_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
Alexander Chemerise0d9d882018-01-10 14:18:32 +09001441 SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1,
Philipp Maier0ad5bcf2019-12-31 17:55:47 +01001442 FairwavesSIM, OpenCellsSim, WavemobileSim, SysmoISIMSJA2 ]
Alexander Chemeris8ad124a2018-01-10 14:17:55 +09001443
1444def card_autodetect(scc):
1445 for kls in _cards_classes:
1446 card = kls.autodetect(scc)
1447 if card is not None:
1448 card.reset()
1449 return card
1450 return None
Supreeth Herle4c306ab2020-03-18 11:38:00 +01001451
1452def card_detect(ctype, scc):
1453 # Detect type if needed
1454 card = None
1455 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
1456
1457 if ctype in ("auto", "auto_once"):
1458 for kls in _cards_classes:
1459 card = kls.autodetect(scc)
1460 if card:
1461 print("Autodetected card type: %s" % card.name)
1462 card.reset()
1463 break
1464
1465 if card is None:
1466 print("Autodetection failed")
1467 return None
1468
1469 if ctype == "auto_once":
1470 ctype = card.name
1471
1472 elif ctype in ctypes:
1473 card = ctypes[ctype](scc)
1474
1475 else:
1476 raise ValueError("Unknown card type: %s" % ctype)
1477
1478 return card