blob: cea330e7544f2bf1069a1ede4f675dece2aada29 [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
Philipp Maier796ca3d2021-11-01 17:13:57 +010026from pySim.utils import rpad, b2h, h2b, sw_match, bertlv_encode_len, Hexstr, h2i, str_sanitize
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):
Philipp Maier712251a2021-11-04 17:09:37 +010093 """ Try to select a specified path
94
95 Args:
96 dir_list : list of hex-string FIDs
97 """
98
Harald Welteca673942020-06-03 15:19:40 +020099 rv = []
100 if type(dir_list) is not list:
101 dir_list = [dir_list]
102 for i in dir_list:
103 data, sw = self._tp.send_apdu(self.cla_byte + "a4" + self.sel_ctrl + "02" + i)
104 rv.append((data, sw))
105 if sw != '9000':
106 return rv
107 return rv
108
Harald Weltec0499c82021-01-21 16:06:50 +0100109 def select_path(self, dir_list):
Harald Welteee3501f2021-04-02 13:00:18 +0200110 """Execute SELECT for an entire list/path of FIDs.
111
112 Args:
113 dir_list: list of FIDs representing the path to select
114
115 Returns:
116 list of return values (FCP in hex encoding) for each element of the path
117 """
Sylvain Munaut76504e02010-12-07 00:24:32 +0100118 rv = []
Vadim Yanitskiyedf873d2020-02-27 01:40:14 +0700119 if type(dir_list) is not list:
120 dir_list = [dir_list]
Sylvain Munaut76504e02010-12-07 00:24:32 +0100121 for i in dir_list:
Harald Welte85484a92021-01-21 16:08:56 +0100122 data, sw = self.select_file(i)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100123 rv.append(data)
124 return rv
125
Harald Welteee3501f2021-04-02 13:00:18 +0200126 def select_file(self, fid:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100127 """Execute SELECT a given file by FID.
128
129 Args:
130 fid : file identifier as hex string
131 """
132
Harald Welte85484a92021-01-21 16:08:56 +0100133 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + self.sel_ctrl + "02" + fid)
134
Harald Welteee3501f2021-04-02 13:00:18 +0200135 def select_adf(self, aid:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100136 """Execute SELECT a given Applicaiton ADF.
137
138 Args:
139 aid : application identifier as hex string
140 """
141
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700142 aidlen = ("0" + format(len(aid) // 2, 'x'))[-2:]
Philipp Maier0ad5bcf2019-12-31 17:55:47 +0100143 return self._tp.send_apdu_checksw(self.cla_byte + "a4" + "0404" + aidlen + aid)
144
Harald Welteee3501f2021-04-02 13:00:18 +0200145 def read_binary(self, ef, length:int=None, offset:int=0):
146 """Execute READD BINARY.
147
148 Args:
149 ef : string or list of strings indicating name or path of transparent EF
150 length : number of bytes to read
151 offset : byte offset in file from which to start reading
152 """
Harald Weltec0499c82021-01-21 16:06:50 +0100153 r = self.select_path(ef)
Max5491c482019-01-03 11:29:25 +0100154 if len(r[-1]) == 0:
155 return (None, None)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100156 if length is None:
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200157 length = self.__len(r) - offset
Philipp Maiere087f902021-11-03 11:46:05 +0100158 if length < 0:
159 return (None, None)
160
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100161 total_data = ''
Harald Welte611dd782021-10-14 20:44:23 +0200162 chunk_offset = 0
163 while chunk_offset < length:
164 chunk_len = min(255, length-chunk_offset)
165 pdu = self.cla_byte + 'b0%04x%02x' % (offset + chunk_offset, chunk_len)
Philipp Maier796ca3d2021-11-01 17:13:57 +0100166 try:
167 data, sw = self._tp.send_apdu_checksw(pdu)
168 except Exception as e:
169 raise ValueError('%s, failed to read (offset %d)' % (str_sanitize(str(e)), offset))
170 total_data += data
171 chunk_offset += chunk_len
Sebastian Viviani0e9f93f2020-04-17 16:42:09 +0100172 return total_data, sw
Sylvain Munaut76504e02010-12-07 00:24:32 +0100173
Harald Welteee3501f2021-04-02 13:00:18 +0200174 def update_binary(self, ef, data:str, offset:int=0, verify:bool=False, conserve:bool=False):
175 """Execute UPDATE BINARY.
176
177 Args:
178 ef : string or list of strings indicating name or path of transparent EF
179 data : hex string of data to be written
180 offset : byte offset in file from which to start writing
181 verify : Whether or not to verify data after write
182 """
Philipp Maier38c74f62021-03-17 17:19:52 +0100183 data_length = len(data) // 2
184
185 # Save write cycles by reading+comparing before write
186 if conserve:
187 data_current, sw = self.read_binary(ef, data_length, offset)
188 if data_current == data:
189 return None, sw
190
Harald Weltec0499c82021-01-21 16:06:50 +0100191 self.select_path(ef)
andrew-ma2e6dc032021-07-31 22:18:24 -0700192 total_data = ''
Harald Welte80901d62021-10-14 19:13:08 +0200193 chunk_offset = 0
andrew-ma2e6dc032021-07-31 22:18:24 -0700194 while chunk_offset < data_length:
195 chunk_len = min(255, data_length - chunk_offset)
196 # chunk_offset is bytes, but data slicing is hex chars, so we need to multiply by 2
Harald Welte80901d62021-10-14 19:13:08 +0200197 pdu = self.cla_byte + 'd6%04x%02x' % (offset + chunk_offset, chunk_len) + data[chunk_offset*2 : (chunk_offset+chunk_len)*2]
Philipp Maier796ca3d2021-11-01 17:13:57 +0100198 try:
199 chunk_data, chunk_sw = self._tp.send_apdu_checksw(pdu)
200 except Exception as e:
201 raise ValueError('%s, failed to write chunk (chunk_offset %d, chunk_len %d)' % \
202 (str_sanitize(str(e)), chunk_offset, chunk_len))
203 total_data += data
204 chunk_offset += chunk_len
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200205 if verify:
206 self.verify_binary(ef, data, offset)
Philipp Maier796ca3d2021-11-01 17:13:57 +0100207 return total_data, chunk_sw
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200208
Harald Welteee3501f2021-04-02 13:00:18 +0200209 def verify_binary(self, ef, data:str, offset:int=0):
210 """Verify contents of transparent EF.
211
212 Args:
213 ef : string or list of strings indicating name or path of transparent EF
214 data : hex string of expected data
215 offset : byte offset in file from which to start verifying
216 """
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200217 res = self.read_binary(ef, len(data) // 2, offset)
218 if res[0].lower() != data.lower():
219 raise ValueError('Binary verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100220
Harald Welteee3501f2021-04-02 13:00:18 +0200221 def read_record(self, ef, rec_no:int):
222 """Execute READ RECORD.
223
224 Args:
225 ef : string or list of strings indicating name or path of linear fixed EF
226 rec_no : record number to read
227 """
Harald Weltec0499c82021-01-21 16:06:50 +0100228 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200229 rec_length = self.__record_len(r)
Jan Balke14b350f2015-01-26 11:15:25 +0100230 pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100231 return self._tp.send_apdu(pdu)
232
Harald Welteee3501f2021-04-02 13:00:18 +0200233 def update_record(self, ef, rec_no:int, data:str, force_len:bool=False, verify:bool=False,
234 conserve:bool=False):
Philipp Maier712251a2021-11-04 17:09:37 +0100235 """Execute UPDATE RECORD.
236
237 Args:
238 ef : string or list of strings indicating name or path of linear fixed EF
239 rec_no : record number to read
240 data : hex string of data to be written
241 force_len : enforce record length by using the actual data length
242 verify : verify data by re-reading the record
243 conserve : read record and compare it with data, skip write on match
244 """
Philipp Maier42804d72021-04-30 11:56:23 +0200245 res = self.select_path(ef)
246
247 if force_len:
248 # enforce the record length by the actual length of the given data input
Vadim Yanitskiy99affe12020-02-15 05:03:09 +0700249 rec_length = len(data) // 2
Philipp Maier42804d72021-04-30 11:56:23 +0200250 else:
251 # determine the record length from the select response of the file and pad
252 # the input data with 0xFF if necessary. In cases where the input data
253 # exceed we throw an exception.
254 rec_length = self.__record_len(res)
255 if (len(data) // 2 > rec_length):
256 raise ValueError('Data length exceeds record length (expected max %d, got %d)' % (rec_length, len(data) // 2))
257 elif (len(data) // 2 < rec_length):
258 data = rpad(data, rec_length * 2)
Philipp Maier38c74f62021-03-17 17:19:52 +0100259
260 # Save write cycles by reading+comparing before write
261 if conserve:
262 data_current, sw = self.read_record(ef, rec_no)
263 data_current = data_current[0:rec_length*2]
264 if data_current == data:
265 return None, sw
266
Jan Balke14b350f2015-01-26 11:15:25 +0100267 pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200268 res = self._tp.send_apdu_checksw(pdu)
269 if verify:
270 self.verify_record(ef, rec_no, data)
271 return res
272
Harald Welteee3501f2021-04-02 13:00:18 +0200273 def verify_record(self, ef, rec_no:int, data:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100274 """Verify record against given data
275
276 Args:
277 ef : string or list of strings indicating name or path of linear fixed EF
278 rec_no : record number to read
279 data : hex string of data to be verified
280 """
Philipp Maier30eb8ca2020-05-11 22:51:37 +0200281 res = self.read_record(ef, rec_no)
282 if res[0].lower() != data.lower():
283 raise ValueError('Record verification failed (expected %s, got %s)' % (data.lower(), res[0].lower()))
Sylvain Munaut76504e02010-12-07 00:24:32 +0100284
285 def record_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200286 """Determine the record size of given file.
287
288 Args:
289 ef : string or list of strings indicating name or path of linear fixed EF
290 """
Harald Weltec0499c82021-01-21 16:06:50 +0100291 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200292 return self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100293
294 def record_count(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200295 """Determine the number of records in given file.
296
297 Args:
298 ef : string or list of strings indicating name or path of linear fixed EF
299 """
Harald Weltec0499c82021-01-21 16:06:50 +0100300 r = self.select_path(ef)
Philipp Maier0e3fcaa2018-06-13 12:34:03 +0200301 return self.__len(r) // self.__record_len(r)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100302
Philipp Maier32daaf52020-05-11 21:48:33 +0200303 def binary_size(self, ef):
Harald Welteee3501f2021-04-02 13:00:18 +0200304 """Determine the size of given transparent file.
305
306 Args:
307 ef : string or list of strings indicating name or path of transparent EF
308 """
Harald Weltec0499c82021-01-21 16:06:50 +0100309 r = self.select_path(ef)
Philipp Maier32daaf52020-05-11 21:48:33 +0200310 return self.__len(r)
311
Harald Welte917d98c2021-04-21 11:51:25 +0200312 # TS 102 221 Section 11.3.1 low-level helper
313 def _retrieve_data(self, tag:int, first:bool=True):
314 if first:
315 pdu = '80cb008001%02x' % (tag)
316 else:
317 pdu = '80cb000000'
318 return self._tp.send_apdu_checksw(pdu)
319
Harald Welte917d98c2021-04-21 11:51:25 +0200320 def retrieve_data(self, ef, tag:int):
Philipp Maier51e4cb72021-10-29 16:48:31 +0200321 """Execute RETRIEVE DATA, see also TS 102 221 Section 11.3.1.
Harald Welte917d98c2021-04-21 11:51:25 +0200322
323 Args
324 ef : string or list of strings indicating name or path of transparent EF
325 tag : BER-TLV Tag of value to be retrieved
326 """
327 r = self.select_path(ef)
328 if len(r[-1]) == 0:
329 return (None, None)
330 total_data = ''
331 # retrieve first block
332 data, sw = self._retrieve_data(tag, first=True)
333 total_data += data
334 while sw == '62f1' or sw == '62f2':
335 data, sw = self._retrieve_data(tag, first=False)
336 total_data += data
337 return total_data, sw
338
339 # TS 102 221 Section 11.3.2 low-level helper
340 def _set_data(self, data:str, first:bool=True):
341 if first:
342 p1 = 0x80
343 else:
344 p1 = 0x00
345 if isinstance(data, bytes) or isinstance(data, bytearray):
346 data = b2h(data)
347 pdu = '80db00%02x%02x%s' % (p1, len(data)//2, data)
348 return self._tp.send_apdu_checksw(pdu)
349
350 def set_data(self, ef, tag:int, value:str, verify:bool=False, conserve:bool=False):
351 """Execute SET DATA.
352
353 Args
354 ef : string or list of strings indicating name or path of transparent EF
355 tag : BER-TLV Tag of value to be stored
356 value : BER-TLV value to be stored
357 """
358 r = self.select_path(ef)
359 if len(r[-1]) == 0:
360 return (None, None)
361
362 # in case of deleting the data, we only have 'tag' but no 'value'
363 if not value:
364 return self._set_data('%02x' % tag, first=True)
365
366 # FIXME: proper BER-TLV encode
367 tl = '%02x%s' % (tag, b2h(bertlv_encode_len(len(value)//2)))
368 tlv = tl + value
369 tlv_bin = h2b(tlv)
370
371 first = True
372 total_len = len(tlv_bin)
373 remaining = tlv_bin
374 while len(remaining) > 0:
375 fragment = remaining[:255]
376 rdata, sw = self._set_data(fragment, first=first)
377 first = False
378 remaining = remaining[255:]
379 return rdata, sw
380
Harald Welteee3501f2021-04-02 13:00:18 +0200381 def run_gsm(self, rand:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100382 """Execute RUN GSM ALGORITHM.
383
384 Args:
385 rand : 16 byte random data as hex string (RAND)
386 """
Sylvain Munaut76504e02010-12-07 00:24:32 +0100387 if len(rand) != 32:
388 raise ValueError('Invalid rand')
Harald Weltec0499c82021-01-21 16:06:50 +0100389 self.select_path(['3f00', '7f20'])
Jan Balke14b350f2015-01-26 11:15:25 +0100390 return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391
Harald Welte15fae982021-04-10 10:22:27 +0200392 def authenticate(self, rand:str, autn:str, context='3g'):
Philipp Maier712251a2021-11-04 17:09:37 +0100393 """Execute AUTHENTICATE (USIM/ISIM).
394
395 Args:
396 rand : 16 byte random data as hex string (RAND)
397 autn : 8 byte Autentication Token (AUTN)
398 context : 16 byte random data ('3g' or 'gsm')
399 """
Harald Welte15fae982021-04-10 10:22:27 +0200400 # 3GPP TS 31.102 Section 7.1.2.1
401 AuthCmd3G = Struct('rand'/LV, 'autn'/Optional(LV))
402 AuthResp3GSyncFail = Struct(Const(b'\xDC'), 'auts'/LV)
403 AuthResp3GSuccess = Struct(Const(b'\xDB'), 'res'/LV, 'ck'/LV, 'ik'/LV, 'kc'/Optional(LV))
404 AuthResp3G = Select(AuthResp3GSyncFail, AuthResp3GSuccess)
405 # build parameters
406 cmd_data = {'rand': rand, 'autn': autn}
407 if context == '3g':
408 p2 = '81'
409 elif context == 'gsm':
410 p2 = '80'
Harald Welte59f9a382021-05-22 00:17:26 +0200411 (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 +0200412 if 'auts' in data:
413 ret = {'synchronisation_failure': data}
414 else:
415 ret = {'successful_3g_authentication': data}
416 return (ret, sw)
417
Harald Welte34b05d32021-05-25 22:03:13 +0200418 def status(self):
419 """Execute a STATUS command as per TS 102 221 Section 11.1.2."""
420 return self._tp.send_apdu_checksw('80F20000ff')
421
Harald Weltea4631612021-04-10 18:17:55 +0200422 def deactivate_file(self):
423 """Execute DECATIVATE FILE command as per TS 102 221 Section 11.1.14."""
424 return self._tp.send_apdu_constr_checksw(self.cla_byte, '04', '00', '00', None, None, None)
425
Harald Welte485692b2021-05-25 22:21:44 +0200426 def activate_file(self, fid):
Philipp Maier712251a2021-11-04 17:09:37 +0100427 """Execute ACTIVATE FILE command as per TS 102 221 Section 11.1.15.
428
429 Args:
430 fid : file identifier as hex string
431 """
Harald Welte485692b2021-05-25 22:21:44 +0200432 return self._tp.send_apdu_checksw(self.cla_byte + '44000002' + fid)
Harald Weltea4631612021-04-10 18:17:55 +0200433
Harald Welte703f9332021-04-10 18:39:32 +0200434 def manage_channel(self, mode='open', lchan_nr=0):
Philipp Maier712251a2021-11-04 17:09:37 +0100435 """Execute MANAGE CHANNEL command as per TS 102 221 Section 11.1.17.
436
437 Args:
438 mode : logical channel operation code ('open' or 'close')
439 lchan_nr : logical channel number (1-19, 0=assigned by UICC)
440 """
Harald Welte703f9332021-04-10 18:39:32 +0200441 if mode == 'close':
442 p1 = 0x80
443 else:
444 p1 = 0x00
445 pdu = self.cla_byte + '70%02x%02x00' % (p1, lchan_nr)
446 return self._tp.send_apdu_checksw(pdu)
447
Sylvain Munaut76504e02010-12-07 00:24:32 +0100448 def reset_card(self):
Harald Welteee3501f2021-04-02 13:00:18 +0200449 """Physically reset the card"""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100450 return self._tp.reset_card()
451
Philipp Maier46f09af2021-03-25 20:24:27 +0100452 def _chv_process_sw(self, op_name, chv_no, pin_code, sw):
453 if sw_match(sw, '63cx'):
454 raise RuntimeError('Failed to %s chv_no 0x%02X with code 0x%s, %i tries left.' %
455 (op_name, chv_no, b2h(pin_code).upper(), int(sw[3])))
456 elif (sw != '9000'):
457 raise SwMatchError(sw, '9000')
458
Harald Welteee3501f2021-04-02 13:00:18 +0200459 def verify_chv(self, chv_no:int, code:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100460 """Verify a given CHV (Card Holder Verification == PIN)
461
462 Args:
463 chv_no : chv number (1=CHV1, 2=CHV2, ...)
464 code : chv code as hex string
465 """
Harald Welteee3501f2021-04-02 13:00:18 +0200466 fc = rpad(b2h(code), 16)
Philipp Maiera31e9a92021-03-11 13:46:32 +0100467 data, sw = self._tp.send_apdu(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
Harald Welteee3501f2021-04-02 13:00:18 +0200468 self._chv_process_sw('verify', chv_no, code, sw)
Philipp Maier46f09af2021-03-25 20:24:27 +0100469 return (data, sw)
470
Harald Welteee3501f2021-04-02 13:00:18 +0200471 def unblock_chv(self, chv_no:int, puk_code:str, pin_code:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100472 """Unblock a given CHV (Card Holder Verification == PIN)
473
474 Args:
475 chv_no : chv number (1=CHV1, 2=CHV2, ...)
476 puk_code : puk code as hex string
477 pin_code : new chv code as hex string
478 """
Philipp Maier46f09af2021-03-25 20:24:27 +0100479 fc = rpad(b2h(puk_code), 16) + rpad(b2h(pin_code), 16)
480 data, sw = self._tp.send_apdu(self.cla_byte + '2C00' + ('%02X' % chv_no) + '10' + fc)
481 self._chv_process_sw('unblock', chv_no, pin_code, sw)
482 return (data, sw)
483
Harald Welteee3501f2021-04-02 13:00:18 +0200484 def change_chv(self, chv_no:int, pin_code:str, new_pin_code:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100485 """Change a given CHV (Card Holder Verification == PIN)
486
487 Args:
488 chv_no : chv number (1=CHV1, 2=CHV2, ...)
489 pin_code : current chv code as hex string
490 new_pin_code : new chv code as hex string
491 """
Philipp Maier46f09af2021-03-25 20:24:27 +0100492 fc = rpad(b2h(pin_code), 16) + rpad(b2h(new_pin_code), 16)
493 data, sw = self._tp.send_apdu(self.cla_byte + '2400' + ('%02X' % chv_no) + '10' + fc)
494 self._chv_process_sw('change', chv_no, pin_code, sw)
495 return (data, sw)
496
Harald Welteee3501f2021-04-02 13:00:18 +0200497 def disable_chv(self, chv_no:int, pin_code:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100498 """Disable a given CHV (Card Holder Verification == PIN)
499
500 Args:
501 chv_no : chv number (1=CHV1, 2=CHV2, ...)
502 pin_code : current chv code as hex string
503 new_pin_code : new chv code as hex string
504 """
Philipp Maier46f09af2021-03-25 20:24:27 +0100505 fc = rpad(b2h(pin_code), 16)
506 data, sw = self._tp.send_apdu(self.cla_byte + '2600' + ('%02X' % chv_no) + '08' + fc)
507 self._chv_process_sw('disable', chv_no, pin_code, sw)
508 return (data, sw)
509
Harald Welteee3501f2021-04-02 13:00:18 +0200510 def enable_chv(self, chv_no:int, pin_code:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100511 """Enable a given CHV (Card Holder Verification == PIN)
512
513 Args:
514 chv_no : chv number (1=CHV1, 2=CHV2, ...)
515 pin_code : chv code as hex string
516 """
Philipp Maier46f09af2021-03-25 20:24:27 +0100517 fc = rpad(b2h(pin_code), 16)
518 data, sw = self._tp.send_apdu(self.cla_byte + '2800' + ('%02X' % chv_no) + '08' + fc)
519 self._chv_process_sw('enable', chv_no, pin_code, sw)
520 return (data, sw)
Harald Weltef2011662021-05-24 23:19:30 +0200521
522 def envelope(self, payload:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100523 """Send one ENVELOPE command to the SIM
524
525 Args:
526 payload : payload as hex string
527 """
Harald Weltef2011662021-05-24 23:19:30 +0200528 return self._tp.send_apdu_checksw('80c20000%02x%s' % (len(payload)//2, payload))
Harald Welte846a8982021-10-08 15:47:16 +0200529
530 def terminal_profile(self, payload:str):
Philipp Maier712251a2021-11-04 17:09:37 +0100531 """Send TERMINAL PROFILE to card
532
533 Args:
534 payload : payload as hex string
535 """
Harald Welte846a8982021-10-08 15:47:16 +0200536 data_length = len(payload) // 2
537 data, sw = self._tp.send_apdu(('80100000%02x' % data_length) + payload)
538 return (data, sw)
Harald Welteec950532021-10-20 13:09:00 +0200539
540 # ETSI TS 102 221 11.1.22
541 def suspend_uicc(self, min_len_secs:int=60, max_len_secs:int=43200):
Philipp Maier712251a2021-11-04 17:09:37 +0100542 """Send SUSPEND UICC to the card.
543
544 Args:
545 min_len_secs : mimumum suspend time seconds
546 max_len_secs : maximum suspend time seconds
547 """
Harald Welteec950532021-10-20 13:09:00 +0200548 def encode_duration(secs:int) -> Hexstr:
549 if secs >= 10*24*60*60:
550 return '04%02x' % (secs // (10*24*60*60))
551 elif secs >= 24*60*60:
552 return '03%02x' % (secs // (24*60*60))
553 elif secs >= 60*60:
554 return '02%02x' % (secs // (60*60))
555 elif secs >= 60:
556 return '01%02x' % (secs // 60)
557 else:
558 return '00%02x' % secs
559 def decode_duration(enc:Hexstr) -> int:
560 time_unit = enc[:2]
561 length = h2i(enc[2:4])
562 if time_unit == '04':
563 return length * 10*24*60*60
564 elif time_unit == '03':
565 return length * 24*60*60
566 elif time_unit == '02':
567 return length * 60*60
568 elif time_unit == '01':
569 return length * 60
570 elif time_unit == '00':
571 return length
572 else:
573 raise ValueError('Time unit must be 0x00..0x04')
574 min_dur_enc = encode_duration(min_len_secs)
575 max_dur_enc = encode_duration(max_len_secs)
576 data, sw = self._tp.send_apdu_checksw('8076000004' + min_dur_enc + max_dur_enc)
577 negotiated_duration_secs = decode_duration(data[:4])
578 resume_token = data[4:]
579 return (negotiated_duration_secs, resume_token, sw)