blob: 7d09fa930172405f92c558d0b42ddcf2cc51d80d [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: SIM Card commands according to ISO 7816-4 and TS 11.11
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Welte917d98c2021-04-21 11:51:25 +02008# Copyright (C) 2010-2021 Harald Welte <laforge@gnumonks.org>
Sylvain Munaut76504e02010-12-07 00:24:32 +01009#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22#
23
Harald Welte15fae982021-04-10 10:22:27 +020024from construct import *
25from pySim.construct import LV
Harald Welteec950532021-10-20 13:09:00 +020026from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len, Hexstr, h2i
Philipp Maier46f09af2021-03-25 20:24:27 +010027from pySim.exceptions import SwMatchError
Sylvain Munaut76504e02010-12-07 00:24:32 +010028
29class SimCardCommands(object):
30 def __init__(self, transport):
Daniel Willmann677d41b2020-10-19 10:34:31 +020031 self._tp = transport
Harald Welte0f96c022021-05-23 14:07:23 +020032 self.cla_byte = "a0"
Philipp Maier41460862017-03-21 12:05:30 +010033 self.sel_ctrl = "0000"
Jan Balke14b350f2015-01-26 11:15:25 +010034
Philipp Maiercdfdd412019-12-20 13:39:24 +010035 # Extract a single FCP item from TLV
36 def __parse_fcp(self, fcp):
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020037 # see also: ETSI TS 102 221, chapter 11.1.1.3.1 Response for MF,
38 # DF or ADF
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020039 from pytlv.TLV import TLV
Philipp Maier91f26d72019-03-20 12:12:51 +010040 tlvparser = TLV(['82', '83', '84', 'a5', '8a', '8b', '8c', '80', 'ab', 'c6', '81', '88'])
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020041
42 # pytlv is case sensitive!
43 fcp = fcp.lower()
44
45 if fcp[0:2] != '62':
46 raise ValueError('Tag of the FCP template does not match, expected 62 but got %s'%fcp[0:2])
47
48 # Unfortunately the spec is not very clear if the FCP length is
49 # coded as one or two byte vale, so we have to try it out by
50 # checking if the length of the remaining TLV string matches
51 # what we get in the length field.
52 # See also ETSI TS 102 221, chapter 11.1.1.3.0 Base coding.
53 exp_tlv_len = int(fcp[2:4], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070054 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020055 skip = 4
56 else:
57 exp_tlv_len = int(fcp[2:6], 16)
Vadim Yanitskiy99affe12020-02-15 05:03:09 +070058 if len(fcp[4:]) // 2 == exp_tlv_len:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020059 skip = 6
60
61 # Skip FCP tag and length
62 tlv = fcp[skip:]
Philipp Maiercdfdd412019-12-20 13:39:24 +010063 return tlvparser.parse(tlv)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020064
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020065 # Tell the length of a record by the card response
66 # USIMs respond with an FCP template, which is different
67 # from what SIMs responds. See also:
68 # USIM: ETSI TS 102 221, chapter 11.1.1.3 Response Data
69 # SIM: GSM 11.11, chapter 9.2.1 SELECT
Harald Welteee3501f2021-04-02 13:00:18 +020070 def __record_len(self, r) -> int:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020071 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010072 tlv_parsed = self.__parse_fcp(r[-1])
73 file_descriptor = tlv_parsed['82']
74 # See also ETSI TS 102 221, chapter 11.1.1.4.3 File Descriptor
75 return int(file_descriptor[4:8], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020076 else:
77 return int(r[-1][28:30], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020078
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020079 # Tell the length of a binary file. See also comment
80 # above.
Harald Welteee3501f2021-04-02 13:00:18 +020081 def __len(self, r) -> int:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020082 if self.sel_ctrl == "0004":
Philipp Maiercdfdd412019-12-20 13:39:24 +010083 tlv_parsed = self.__parse_fcp(r[-1])
84 return int(tlv_parsed['80'], 16)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +020085 else:
86 return int(r[-1][4:8], 16)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +020087
Harald Welteee3501f2021-04-02 13:00:18 +020088 def get_atr(self) -> str:
89 """Return the ATR of the currently inserted card."""
Alexander Chemerisd2d660a2017-07-18 16:52:25 +030090 return self._tp.get_atr()
91
Harald Weltec0499c82021-01-21 16:06:50 +010092 def try_select_path(self, dir_list):
Harald Welteee3501f2021-04-02 13:00:18 +020093 """ Try to select a specified path given as list of hex-string FIDs"""
Harald Welteca673942020-06-03 15:19:40 +020094 rv = []
95 if type(dir_list) is not list:
96 dir_list = [dir_list]
97 for i in dir_list:
98 data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
99 rv.append((data, sw))
100 if sw != '9000':
101 return rv
102 return rv
103
Harald Weltec0499c82021-01-21 16:06:50 +0100104 def select_path(self, dir_list):
Harald Welteee3501f2021-04-02 13:00:18 +0200105 """Execute SELECT for an entire list/path of FIDs.
106
107 Args:
108 dir_list: list of FIDs representing the path to select
109
110 Returns:
111 list of return values (FCP in hex encoding) for each element of the path
112 """
Sylvain Munaut76504e02010-12-07 00:24:32 +0100113 rv = []
Vadim Yanitskiyedf873d2020-02-27 01:40:14 +0700114 if type(dir_list) is not list:
115 dir_list = [dir_list]
Sylvain Munaut76504e02010-12-07 00:24:32 +0100116 for i in dir_list:
Harald Welte85484a92021-01-21 16:08:56 +0100117 data, sw = self.select_file(i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100118 rv.append(data)
119 return rv
120
Harald Welteee3501f2021-04-02 13:00:18 +0200121 def select_file(self, fid:str):
122 """Execute SELECT a given file by FID."""
Harald Welte85484a92021-01-21 16:08:56 +0100123 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
124
Harald Welteee3501f2021-04-02 13:00:18 +0200125 def select_adf(self, aid:str):
126 """Execute SELECT a given Applicaiton ADF."""
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700127 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100128 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
129
Harald Welteee3501f2021-04-02 13:00:18 +0200130 def read_binary(self, ef, length:int=None, offset:int=0):
131 """Execute READD BINARY.
132
133 Args:
134 ef : string or list of strings indicating name or path of transparent EF
135 length : number of bytes to read
136 offset : byte offset in file from which to start reading
137 """
Harald Weltec0499c82021-01-21 16:06:50 +0100138 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100139 if len(r[-1]) == 0:
140 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100141 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200142 length = self.__len(r) - offset
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100143 total_data = ''
Harald Welte611dd782021-10-14 20:44:23 +0200144 chunk_offset = 0
145 while chunk_offset < length:
146 chunk_len = min(255, length-chunk_offset)
147 pdu = self.cla_byte + 'b0%04x%02x' % (offset + chunk_offset, chunk_len)
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100148 data,sw = self._tp.send_apdu(pdu)
149 if sw == '9000':
150 total_data += data
Harald Welte611dd782021-10-14 20:44:23 +0200151 chunk_offset += chunk_len
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100152 else:
153 raise ValueError('Failed to read (offset %d)' % (offset))
154 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100155
Harald Welteee3501f2021-04-02 13:00:18 +0200156 def update_binary(self, ef, data:str, offset:int=0, verify:bool=False, conserve:bool=False):
157 """Execute UPDATE BINARY.
158
159 Args:
160 ef : string or list of strings indicating name or path of transparent EF
161 data : hex string of data to be written
162 offset : byte offset in file from which to start writing
163 verify : Whether or not to verify data after write
164 """
Philipp Maier38c74f62021-03-17 17:19:52 +0100165 data_length = len(data) // 2
166
167 # Save write cycles by reading+comparing before write
168 if conserve:
169 data_current, sw = self.read_binary(ef, data_length, offset)
170 if data_current == data:
171 return None, sw
172
Harald Weltec0499c82021-01-21 16:06:50 +0100173 self.select_path(ef)
andrew-ma2e6dc032021-07-31 22:18:24 -0700174 total_data = ''
175 total_sw = "9000"
Harald Welte80901d62021-10-14 19:13:08 +0200176 chunk_offset = 0
andrew-ma2e6dc032021-07-31 22:18:24 -0700177 while chunk_offset < data_length:
178 chunk_len = min(255, data_length - chunk_offset)
179 # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2
Harald Welte80901d62021-10-14 19:13:08 +0200180 pdu = self.cla_byte + 'd6%04x%02x' % (offset + chunk_offset, chunk_len) + data[chunk_offset*2 : (chunk_offset+chunk_len)*2]
andrew-ma2e6dc032021-07-31 22:18:24 -0700181 chunk_data, chunk_sw = self._tp.send_apdu(pdu)
182 if chunk_sw == total_sw:
183 total_data += chunk_data
184 chunk_offset += chunk_len
185 else:
186 total_sw = chunk_sw
187 raise ValueError('Failed to write chunk (chunk_offset %d, chunk_len %d)' % (chunk_offset, chunk_len))
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200188 if verify:
189 self.verify_binary(ef, data, offset)
andrew-ma2e6dc032021-07-31 22:18:24 -0700190 return total_data, total_sw
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200191
Harald Welteee3501f2021-04-02 13:00:18 +0200192 def verify_binary(self, ef, data:str, offset:int=0):
193 """Verify contents of transparent EF.
194
195 Args:
196 ef : string or list of strings indicating name or path of transparent EF
197 data : hex string of expected data
198 offset : byte offset in file from which to start verifying
199 """
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200200 res = self.read_binary(ef, len(data) // 2, offset)
201 if res[0].lower() != data.lower():
202 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100203
Harald Welteee3501f2021-04-02 13:00:18 +0200204 def read_record(self, ef, rec_no:int):
205 """Execute READ RECORD.
206
207 Args:
208 ef : string or list of strings indicating name or path of linear fixed EF
209 rec_no : record number to read
210 """
Harald Weltec0499c82021-01-21 16:06:50 +0100211 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200212 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100213 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100214 return self._tp.send_apdu(pdu)
215
Harald Welteee3501f2021-04-02 13:00:18 +0200216 def update_record(self, ef, rec_no:int, data:str, force_len:bool=False, verify:bool=False,
217 conserve:bool=False):
Philipp Maier42804d72021-04-30 11:56:23 +0200218 res = self.select_path(ef)
219
220 if force_len:
221 # enforce the record length by the actual length of the given data input
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700222 rec_length = len(data) // 2
Philipp Maier42804d72021-04-30 11:56:23 +0200223 else:
224 # determine the record length from the select response of the file and pad
225 # the input data with 0xFF if necessary. In cases where the input data
226 # exceed we throw an exception.
227 rec_length = self.__record_len(res)
228 if (len(data) // 2 > rec_length):
229 raise ValueError('Data length exceeds record length (expected max %d, got %d)' % (rec_length, len(data) // 2))
230 elif (len(data) // 2 < rec_length):
231 data = rpad(data, rec_length * 2)
Philipp Maier38c74f62021-03-17 17:19:52 +0100232
233 # Save write cycles by reading+comparing before write
234 if conserve:
235 data_current, sw = self.read_record(ef, rec_no)
236 data_current = data_current[0:rec_length*2]
237 if data_current == data:
238 return None, sw
239
Jan Balke14b350f2015-01-26 11:15:25 +0100240 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200241 res = self._tp.send_apdu_checksw(pdu)
242 if verify:
243 self.verify_record(ef, rec_no, data)
244 return res
245
Harald Welteee3501f2021-04-02 13:00:18 +0200246 def verify_record(self, ef, rec_no:int, data:str):
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200247 res = self.read_record(ef, rec_no)
248 if res[0].lower() != data.lower():
249 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100250
251 def record_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200252 """Determine the record size of given file.
253
254 Args:
255 ef : string or list of strings indicating name or path of linear fixed EF
256 """
Harald Weltec0499c82021-01-21 16:06:50 +0100257 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200258 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100259
260 def record_count(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200261 """Determine the number of records in given file.
262
263 Args:
264 ef : string or list of strings indicating name or path of linear fixed EF
265 """
Harald Weltec0499c82021-01-21 16:06:50 +0100266 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200267 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100268
Philipp Maier32daaf52020-05-11 21:48:33 +0200269 def binary_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200270 """Determine the size of given transparent file.
271
272 Args:
273 ef : string or list of strings indicating name or path of transparent EF
274 """
Harald Weltec0499c82021-01-21 16:06:50 +0100275 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200276 return self.__len(r)
277
Harald Welte917d98c2021-04-21 11:51:25 +0200278 # TS 102 221 Section 11.3.1 low-level helper
279 def _retrieve_data(self, tag:int, first:bool=True):
280 if first:
281 pdu = '80cb008001%02x' % (tag)
282 else:
283 pdu = '80cb000000'
284 return self._tp.send_apdu_checksw(pdu)
285
286 # TS 102 221 Section 11.3.1
287 def retrieve_data(self, ef, tag:int):
288 """Execute RETRIEVE DATA.
289
290 Args
291 ef : string or list of strings indicating name or path of transparent EF
292 tag : BER-TLV Tag of value to be retrieved
293 """
294 r = self.select_path(ef)
295 if len(r[-1]) == 0:
296 return (None, None)
297 total_data = ''
298 # retrieve first block
299 data, sw = self._retrieve_data(tag, first=True)
300 total_data += data
301 while sw == '62f1' or sw == '62f2':
302 data, sw = self._retrieve_data(tag, first=False)
303 total_data += data
304 return total_data, sw
305
306 # TS 102 221 Section 11.3.2 low-level helper
307 def _set_data(self, data:str, first:bool=True):
308 if first:
309 p1 = 0x80
310 else:
311 p1 = 0x00
312 if isinstance(data, bytes) or isinstance(data, bytearray):
313 data = b2h(data)
314 pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data)
315 return self._tp.send_apdu_checksw(pdu)
316
317 def set_data(self, ef, tag:int, value:str, verify:bool=False, conserve:bool=False):
318 """Execute SET DATA.
319
320 Args
321 ef : string or list of strings indicating name or path of transparent EF
322 tag : BER-TLV Tag of value to be stored
323 value : BER-TLV value to be stored
324 """
325 r = self.select_path(ef)
326 if len(r[-1]) == 0:
327 return (None, None)
328
329 # in case of deleting the data, we only have 'tag' but no 'value'
330 if not value:
331 return self._set_data('%02x' % tag, first=True)
332
333 # FIXME: proper BER-TLV encode
334 tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2)))
335 tlv = tl + value
336 tlv_bin = h2b(tlv)
337
338 first = True
339 total_len = len(tlv_bin)
340 remaining = tlv_bin
341 while len(remaining) > 0:
342 fragment = remaining[:255]
343 rdata, sw = self._set_data(fragment, first=first)
344 first = False
345 remaining = remaining[255:]
346 return rdata, sw
347
Harald Welteee3501f2021-04-02 13:00:18 +0200348 def run_gsm(self, rand:str):
349 """Execute RUN GSM ALGORITHM."""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100350 if len(rand) != 32:
351 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100352 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100353 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100354
Harald Welte15fae982021-04-10 10:22:27 +0200355 def authenticate(self, rand:str, autn:str, context='3g'):
356 """Execute AUTHENTICATE (USIM/ISIM)."""
357 # 3GPP TS 31.102 Section 7.1.2.1
358 AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV))
359 AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV)
360 AuthResp3GSuccess = Struct(Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV))
361 AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess)
362 # build parameters
363 cmd_data = {'rand': rand, 'autn': autn}
364 if context == '3g':
365 p2 = '81'
366 elif context == 'gsm':
367 p2 = '80'
Harald Welte59f9a382021-05-22 00:17:26 +0200368 (data, sw) = self._tp.send_apdu_constr_checksw(self.cla_byte, '88', '00', p2, AuthCmd3G, cmd_data, AuthResp3G)
Harald Welte15fae982021-04-10 10:22:27 +0200369 if 'auts' in data:
370 ret = {'synchronisation_failure': data}
371 else:
372 ret = {'successful_3g_authentication': data}
373 return (ret, sw)
374
Harald Welte34b05d32021-05-25 22:03:13 +0200375 def status(self):
376 """Execute a STATUS command as per TS 102 221 Section 11.1.2."""
377 return self._tp.send_apdu_checksw('80F20000ff')
378
Harald Weltea4631612021-04-10 18:17:55 +0200379 def deactivate_file(self):
380 """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14."""
381 return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None)
382
Harald Welte485692b2021-05-25 22:21:44 +0200383 def activate_file(self, fid):
Harald Weltea4631612021-04-10 18:17:55 +0200384 """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15."""
Harald Welte485692b2021-05-25 22:21:44 +0200385 return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid)
Harald Weltea4631612021-04-10 18:17:55 +0200386
Harald Welte703f9332021-04-10 18:39:32 +0200387 def manage_channel(self, mode='open', lchan_nr=0):
388 """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17."""
389 if mode == 'close':
390 p1 = 0x80
391 else:
392 p1 = 0x00
393 pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr)
394 return self._tp.send_apdu_checksw(pdu)
395
Sylvain Munaut76504e02010-12-07 00:24:32 +0100396 def reset_card(self):
Harald Welteee3501f2021-04-02 13:00:18 +0200397 """Physically reset the card"""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100398 return self._tp.reset_card()
399
Philipp Maier46f09af2021-03-25 20:24:27 +0100400 def _chv_process_sw(self, op_name, chv_no, pin_code, sw):
401 if sw_match(sw, '63cx'):
402 raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' %
403 (op_name, chv_no, b2h(pin_code).upper(), int(sw[3])))
404 elif (sw != '9000'):
405 raise SwMatchError(sw, '9000')
406
Harald Welteee3501f2021-04-02 13:00:18 +0200407 def verify_chv(self, chv_no:int, code:str):
408 """Verify a given CHV (Card Holder Verification == PIN)"""
409 fc = rpad(b2h(code), 16)
Philipp Maiera31e9a92021-03-11 13:46:32 +0100410 data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
Harald Welteee3501f2021-04-02 13:00:18 +0200411 self._chv_process_sw('verify', chv_no, code, sw)
Philipp Maier46f09af2021-03-25 20:24:27 +0100412 return (data, sw)
413
Harald Welteee3501f2021-04-02 13:00:18 +0200414 def unblock_chv(self, chv_no:int, puk_code:str, pin_code:str):
415 """Unblock a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100416 fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16)
417 data, sw = self._tp.send_apdu(self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc)
418 self._chv_process_sw('unblock', chv_no, pin_code, sw)
419 return (data, sw)
420
Harald Welteee3501f2021-04-02 13:00:18 +0200421 def change_chv(self, chv_no:int, pin_code:str, new_pin_code:str):
422 """Change a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100423 fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16)
424 data, sw = self._tp.send_apdu(self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc)
425 self._chv_process_sw('change', chv_no, pin_code, sw)
426 return (data, sw)
427
Harald Welteee3501f2021-04-02 13:00:18 +0200428 def disable_chv(self, chv_no:int, pin_code:str):
429 """Disable a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100430 fc = rpad(b2h(pin_code), 16)
431 data, sw = self._tp.send_apdu(self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc)
432 self._chv_process_sw('disable', chv_no, pin_code, sw)
433 return (data, sw)
434
Harald Welteee3501f2021-04-02 13:00:18 +0200435 def enable_chv(self, chv_no:int, pin_code:str):
436 """Enable a given CHV (Card Holder Verification == PIN)"""
Philipp Maier46f09af2021-03-25 20:24:27 +0100437 fc = rpad(b2h(pin_code), 16)
438 data, sw = self._tp.send_apdu(self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc)
439 self._chv_process_sw('enable', chv_no, pin_code, sw)
440 return (data, sw)
Harald Weltef2011662021-05-24 23:19:30 +0200441
442 def envelope(self, payload:str):
443 """Send one ENVELOPE command to the SIM"""
444 return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload))
Harald Welte846a8982021-10-08 15:47:16 +0200445
446 def terminal_profile(self, payload:str):
447 """Send TERMINAL PROFILE to card"""
448 data_length = len(payload) // 2
449 data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload)
450 return (data, sw)
Harald Welteec950532021-10-20 13:09:00 +0200451
452 # ETSI TS 102 221 11.1.22
453 def suspend_uicc(self, min_len_secs:int=60, max_len_secs:int=43200):
454 """Send SUSPEND UICC to the card."""
455 def encode_duration(secs:int) -> Hexstr:
456 if secs >= 10*24*60*60:
457 return '04%02x' % (secs // (10*24*60*60))
458 elif secs >= 24*60*60:
459 return '03%02x' % (secs // (24*60*60))
460 elif secs >= 60*60:
461 return '02%02x' % (secs // (60*60))
462 elif secs >= 60:
463 return '01%02x' % (secs // 60)
464 else:
465 return '00%02x' % secs
466 def decode_duration(enc:Hexstr) -> int:
467 time_unit = enc[:2]
468 length = h2i(enc[2:4])
469 if time_unit == '04':
470 return length * 10*24*60*60
471 elif time_unit == '03':
472 return length * 24*60*60
473 elif time_unit == '02':
474 return length * 60*60
475 elif time_unit == '01':
476 return length * 60
477 elif time_unit == '00':
478 return length
479 else:
480 raise ValueError('Time unit must be 0x00..0x04')
481 min_dur_enc = encode_duration(min_len_secs)
482 max_dur_enc = encode_duration(max_len_secs)
483 data, sw = self._tp.send_apdu_checksw('8076000004' + min_dur_enc + max_dur_enc)
484 negotiated_duration_secs = decode_duration(data[:4])
485 resume_token = data[4:]
486 return (negotiated_duration_secs, resume_token, sw)